From 6a5bafe3d99c26e78c4ce240eb54a917259a9861 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Sun, 28 Aug 2016 00:23:47 +0200 Subject: Solve palindrome --- go/palindrome-products/palindrome_products.go | 53 +++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 go/palindrome-products/palindrome_products.go (limited to 'go/palindrome-products/palindrome_products.go') 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 +} -- cgit v1.2.3