forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c7447ef
commit 34f5c59
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
// Solution to Rod cutting problem | ||
// https://en.wikipedia.org/wiki/Cutting_stock_problem | ||
// http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/ | ||
|
||
package dpRodCutting | ||
|
||
// package main | ||
|
||
import "fmt" | ||
|
||
func max(a, b int) int { | ||
if a > b { | ||
return a | ||
} else { | ||
return b | ||
} | ||
|
||
} | ||
|
||
// solve the problem recursively: initial approach | ||
func cutRodRec(price []int, length int) int { | ||
if length == 0 { | ||
return 0 | ||
} | ||
|
||
q := -1 | ||
for i := 1; i <= length; i++ { | ||
q = max(q, price[i]+cutRodRec(price, length-i)) | ||
} | ||
return q | ||
} | ||
|
||
// solve the same problem using dynamic programming | ||
func cutRodDp(price []int, length int) int { | ||
r := make([]int, length+1) // a.k.a the memoization array | ||
r[0] = 0 // cost of 0 length rod is 0 | ||
|
||
for j := 1; j <= length; j++ { // for each length (subproblem) | ||
q := -1 | ||
for i := 1; i <= j; i++ { | ||
q = max(q, price[i]+r[j-i]) // avoiding recursive call | ||
} | ||
r[j] = q | ||
} | ||
|
||
return r[length] | ||
} | ||
|
||
/* | ||
func main() { | ||
length := 10 | ||
price := []int{0, 1, 5, 8, 9, 17, 17, 17, 20, 24, 30} | ||
// price := []int{0, 10, 5, 8, 9, 17, 17, 17, 20, 24, 30} | ||
// fmt.Print(price[5]+price[length-5], "\n") | ||
fmt.Print(cutRodRec(price, length), "\n") | ||
fmt.Print(cutRodDp(price, length), "\n") | ||
} | ||
*/ |