Skip to content

Commit 34f5c59

Browse files
committed
add rod cutting problem
1 parent c7447ef commit 34f5c59

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

dynamic-programming/rod-cutting.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Solution to Rod cutting problem
2+
// https://en.wikipedia.org/wiki/Cutting_stock_problem
3+
// http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/
4+
5+
package dpRodCutting
6+
7+
// package main
8+
9+
import "fmt"
10+
11+
func max(a, b int) int {
12+
if a > b {
13+
return a
14+
} else {
15+
return b
16+
}
17+
18+
}
19+
20+
// solve the problem recursively: initial approach
21+
func cutRodRec(price []int, length int) int {
22+
if length == 0 {
23+
return 0
24+
}
25+
26+
q := -1
27+
for i := 1; i <= length; i++ {
28+
q = max(q, price[i]+cutRodRec(price, length-i))
29+
}
30+
return q
31+
}
32+
33+
// solve the same problem using dynamic programming
34+
func cutRodDp(price []int, length int) int {
35+
r := make([]int, length+1) // a.k.a the memoization array
36+
r[0] = 0 // cost of 0 length rod is 0
37+
38+
for j := 1; j <= length; j++ { // for each length (subproblem)
39+
q := -1
40+
for i := 1; i <= j; i++ {
41+
q = max(q, price[i]+r[j-i]) // avoiding recursive call
42+
}
43+
r[j] = q
44+
}
45+
46+
return r[length]
47+
}
48+
49+
/*
50+
func main() {
51+
length := 10
52+
price := []int{0, 1, 5, 8, 9, 17, 17, 17, 20, 24, 30}
53+
// price := []int{0, 10, 5, 8, 9, 17, 17, 17, 20, 24, 30}
54+
55+
// fmt.Print(price[5]+price[length-5], "\n")
56+
57+
fmt.Print(cutRodRec(price, length), "\n")
58+
fmt.Print(cutRodDp(price, length), "\n")
59+
}
60+
*/

0 commit comments

Comments
 (0)