summaryrefslogtreecommitdiff
path: root/go/palindrome-products/palindrome_products.go
blob: 42e7bc42ebd3835e4d598d546f5e80999b8f57bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package palindrome

import (
	"errors"
	"strconv"
)

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

func Products(fmin, fmax int) (pmin, pmax Product, err error) {
	fail := func(s string) (Product, Product, error) {
		return Product{}, Product{}, errors.New(s)
	}
	if fmin > fmax {
		return fail("fmin > fmax...")
	}

	pmin.Product = fmax * fmax
	pp := make(map[int][][2]int)

	for i := fmin; i <= fmax; i++ {
		for j := i; j <= fmax; j++ {
			if v := i * j; isPalindrom(v) {
				pp[v] = append(pp[v], [2]int{i, j})
				if v < pmin.Product {
					pmin.Product = v
				}
				if v > pmax.Product {
					pmax.Product = v
				}
			}
		}
	}
	if len(pp) == 0 {
		return fail("No palindromes...")
	}
	pmin.Factorizations = pp[pmin.Product]
	pmax.Factorizations = pp[pmax.Product]
	return
}

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