Permalink
Browse files

Function for Truncate and verify if a number is truncatable

  • Loading branch information...
1 parent 121ab80 commit 77cf16ec4ae847a3b2e43127b50236298f316f52 @fsouza committed Jul 22, 2011
Showing with 110 additions and 2 deletions.
  1. +70 −1 problem_037/37.go
  2. +40 −1 problem_037/37_test.go
View
@@ -1 +1,70 @@
-package main
+package main
+
+import (
+ "strconv"
+)
+
+func BuildPrimesList(limit float64) []int {
+ primes := make([]int, 0)
+ primesCh := GetPrimes(limit)
+
+ for prime := range primesCh {
+ if prime == 0 {
+ break
+ }
+
+ primes = append(primes, prime)
+ }
+
+ return primes
+}
+
+func IsPresent(slice []int, number int) bool {
+ for _, element := range slice {
+ if element == number {
+ return true
+ }
+ }
+
+ return false
+}
+
+func Truncate(number int, from string) int {
+ digits := []int(strconv.Itoa(number))
+ length := len(digits)
+
+ if length == 1 {
+ return 0
+ }
+
+ if from == "right" {
+ digits = digits[:length - 1]
+ } else {
+ digits = digits[1:]
+ }
+
+ newNumber, _ := strconv.Atoi(string(digits))
+ return newNumber
+}
+
+func TruncateRight(number int) int {
+ return Truncate(number, "right")
+}
+
+func TruncateLeft(number int) int {
+ return Truncate(number, "left")
+}
+
+func IsTruncatable(number int, primes []int) bool {
+ operations := []string{"right", "left"}
+ for _, operation := range operations {
+ copyNumber := number
+ for copyNumber = Truncate(copyNumber, operation); copyNumber != 0; copyNumber = TruncateRight(copyNumber) {
+ if !IsPresent(primes, copyNumber) {
+ return false
+ }
+ }
+ }
+
+ return true
+}
View
@@ -1 +1,40 @@
-package main
+package main
+
+import (
+ "testing"
+)
+
+func TestIsTruncatable(t *testing.T) {
+ primes := BuildPrimesList(3798)
+ expected := true
+ got := IsTruncatable(3797, primes)
+ if expected != got {
+ t.Errorf("Assertion error.\nExpected: %v.\nGot: %v.", expected, got)
+ }
+}
+
+func TestTruncate(t *testing.T) {
+ expected := 123
+ got := Truncate(1234, "right")
+ if expected != got {
+ t.Errorf("Assertion error.\nExpected: %v.\nGot: %v.", expected, got)
+ }
+}
+
+
+func TestTruncateRight(t *testing.T) {
+ expected := 123
+ got := TruncateRight(1234)
+ if expected != got {
+ t.Errorf("Assertion error.\nExpected: %v.\nGot: %v.", expected, got)
+ }
+}
+
+func TestTruncateLeft(t *testing.T) {
+ expected := 234
+ got := TruncateLeft(1234)
+ if expected != got {
+ t.Errorf("Assertion error.\nExpected: %v.\nGot: %v.", expected, got)
+ }
+}
+

0 comments on commit 77cf16e

Please sign in to comment.