Pages

Showing posts with label memoization. Show all posts
Showing posts with label memoization. Show all posts

Wednesday, July 13, 2011

Problem #15

Problem link
Solution:
package main

var arr [][]uint64

func main() {
arr = make([][]uint64, 21)
for i := range arr {
arr[i] = make([]uint64, 21)
for j := range arr[i] {
arr[i][j] = uint64(0)
}
}
arr[20][20] = uint64(1)
println(noOfRoutes(0, 0))
}

func noOfRoutes(i, j int) uint64 {
if arr[i][j] != uint64(0) {
return arr[i][j]
}
var result uint64
if i < 20 && j < 20 {
result = noOfRoutes(i+1, j) + noOfRoutes(i, j+1)
} else if i < 20 && j == 20 {
result = noOfRoutes(i+1, j)
} else {
result = noOfRoutes(i, j+1)
}
arr[i][j] = result
return result
}



Result: 137846528820
Time: 0m0.003s

Problem #18

Problem link
Solution:
package main

import (
"io/ioutil"
"strconv"
"strings"
)

var arr [][]int
var bests [][]int

func main() {
fileBuf, err := ioutil.ReadFile("018_input.txt")
if err != nil {
panic(err.String())
}
fileStr := strings.Trim(string(fileBuf), "")
oneDArrStr := strings.Split(fileStr, "\n", -1)
var line []string
arr = make([][]int, 15)
bests = make([][]int, len(arr))
for i := range arr {
line = strings.Split(oneDArrStr[i], " ", -1)
arr[i] = make([]int, len(line))
bests[i] = make([]int, len(arr[i]))
for j := range line {
arr[i][j], _ = strconv.Atoi(line[j])
bests[i][j] = -1
}
}
println(bestSum(0, 0))
}

func bestSum(i, j int) int {
var result int
if bests[i][j] != -1 {
result = bests[i][j]
} else if i == len(arr)-1 {
result = arr[i][j]
return arr[i][j]
} else {
sumLeft, sumRight := bestSum(i+1, j), bestSum(i+1, j+1)
if sumLeft > sumRight {
result = arr[i][j] + sumLeft
} else {
result = arr[i][j] + sumRight
}
}
bests[i][j] = result
return result
}


Tree is read from a file named as 018_input.txt and also memoization is used for this problem.

Result: 1074
Time: 0m0.005s

Problem #37

Problem link
Solution:
package main

import (
"strconv"
)

func main() {
arr := make([]bool, 1000000)
left := make([]bool, 1000000)
right := make([]bool, 1000000)

//manuel setting for the values less than 10
left[2], left[3], left[5], left[7] = true, true, true, true
right[2], right[3], right[5], right[7] = true, true, true, true
arr[0], arr[1], arr[6], arr[9] = true, true, true, true
a := []int{3, 5, 7}
for i := range a {
for k := a[i] * 2; k < len(arr); k += a[i] {
arr[k] = true
}
}

//calculate other primes and check the condition.
var k, tmp int
prime, counter, sum := 11, 0, 0
for {
if right[prime/10] {
right[prime] = true
}
tmp, _ = strconv.Atoi(strconv.Itoa(prime)[1:])
if left[tmp] {
left[prime] = true
if right[prime] {
sum += prime
counter++
if counter == 11 {
println(sum)
return
}
}
}
for k = prime * 2; k < len(arr); k += prime {
arr[k] = true
}
for k = prime + 2; k < len(arr) && arr[k]; k += 2 {
}
if k < len(arr) {
prime = k
} else {
break
}
}
}



Result: 748317
Time: 0m0.083s