Sha256: 58c6290a9581b5295e81f8415419f5c7e97e8a2ac9a8848de61a74be77167064

Contents?: true

Size: 1.02 KB

Versions: 118

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

118 entries across 118 versions & 1 rubygems

Version Path
trackler-2.2.1.56 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.55 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.54 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.53 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.52 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.51 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.50 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.49 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.48 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.47 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.46 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.45 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.44 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.43 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.42 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.41 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.40 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.39 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.38 tracks/go/exercises/palindrome-products/example.go
trackler-2.2.1.37 tracks/go/exercises/palindrome-products/example.go