summaryrefslogtreecommitdiff
path: root/go/palindrome-products/palindrome_products.go
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2016-08-28 00:23:47 +0200
committerDimitri Sokolyuk <demon@dim13.org>2016-08-28 00:23:47 +0200
commit6a5bafe3d99c26e78c4ce240eb54a917259a9861 (patch)
tree9f7be1a2c46e6bab9b3ae976379c91b45c56524a /go/palindrome-products/palindrome_products.go
parenta593ae4ca4e3af5c419461284c97a6cc91466d1b (diff)
Solve palindrome
Diffstat (limited to 'go/palindrome-products/palindrome_products.go')
-rw-r--r--go/palindrome-products/palindrome_products.go53
1 files changed, 53 insertions, 0 deletions
diff --git a/go/palindrome-products/palindrome_products.go b/go/palindrome-products/palindrome_products.go
new file mode 100644
index 0000000..42e7bc4
--- /dev/null
+++ b/go/palindrome-products/palindrome_products.go
@@ -0,0 +1,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
+}