Sha256: 8c5e2d683de658adc6700ab57266715b24e0d42cbfb1ac509472a6e69b006000

Contents?: true

Size: 1.02 KB

Versions: 155

Compression:

Stored size: 1.02 KB

Contents

package palindrome

import (
	"fmt"
	"strconv"
)

const testVersion = 1

func isPal(x int) bool {
	s := strconv.Itoa(x)
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		if s[i] != s[j] {
			return false
		}
	}
	return true
}

type Product struct {
	Product        int
	Factorizations [][2]int
}

func Products(fmin, fmax int) (pmin, pmax Product, err error) {
	if fmin > fmax {
		err = fmt.Errorf("fmin > fmax: %d > %d", fmin, fmax)
		return
	}
	for x := fmin; x <= fmax; x++ {
		for y := x; y <= fmax; y++ {
			p := x * y
			if !isPal(p) {
				continue
			}
			compare := func(current *Product, better bool) {
				switch {
				case current.Factorizations == nil || better:
					*current = Product{p, [][2]int{{x, y}}}
				case p == current.Product:
					current.Factorizations =
						append(current.Factorizations, [2]int{x, y})
				}
			}
			compare(&pmin, p < pmin.Product)
			compare(&pmax, p > pmax.Product)
		}
	}
	if len(pmin.Factorizations) == 0 {
		err = fmt.Errorf("No palindromes in range [%d, %d].", fmin, fmax)
	}
	return
}

Version data entries

155 entries across 155 versions & 1 rubygems

Version Path
trackler-2.0.6.40 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.39 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.38 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.37 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.36 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.35 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.34 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.33 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.32 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.31 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.30 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.29 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.28 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.27 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.26 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.25 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.24 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.23 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.22 tracks/go/exercises/palindrome-products/example.go
trackler-2.0.6.21 tracks/go/exercises/palindrome-products/example.go