Sha256: 1924990583419dde0b82a041f8312847d14b951fae5c7ba45919ebeae735632a

Contents?: true

Size: 1018 Bytes

Versions: 122

Compression:

Stored size: 1018 Bytes

Contents

package palindrome

import (
	"fmt"
	"strconv"
)

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

122 entries across 122 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.179 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.178 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.177 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.176 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.175 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.174 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.173 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.172 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.171 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.170 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.169 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.167 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.166 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.165 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.164 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.163 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.162 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.161 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.160 tracks/go/exercises/palindrome-products/example.go