Skip to content

Add sump up to number problem #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions dp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,7 @@ DP is well-suited for tackling an array of complex problems, including those in
### Rod Cutting

Given a list containing price a table such as `{1,5,8,9,10}` indicating the price of a rod of a given length (1 inch rod is $1, 2 inch rod is $5, 5 inch rod is $10) and number n like 3, indicating the length of a given rod, calculate maximum revenue that can be earned by cutting the rod and selling the pieces when cutting is free. [Solution](rod_cutting.go), [Tests](rod_cutting_test.go)

### Sum Up to Number

Given a set of positive integers like `{1,2,3,4,5}` and an integer like `7` write a function that returns true if there are two numbers in the list that sum up to the given integer and false otherwise. [Solution](sum_up_to_integer.go), [Tests](sum_up_to_integer_test.go)
22 changes: 22 additions & 0 deletions dp/sum_up_to_integer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package dp

func SumUpToInteger(numbers []int, sum int) bool {
dp := make([]bool, sum+1)
dp[0] = true

for i := 1; i <= sum; i++ {
if numbers[0] == i {
dp[i] = true
}
}

for i := 1; i < len(numbers); i++ {
for j := sum; j >= 0; j-- {
if !dp[j] && j >= numbers[i] {
dp[j] = dp[j-numbers[i]]
}
}
}

return dp[sum]
}
29 changes: 29 additions & 0 deletions dp/sum_up_to_integer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package dp

import (
"testing"
)

func TestSumUpToInteger(t *testing.T) {
tests := []struct {
numbers []int
sum int
sumsUp bool
}{
{[]int{1}, 1, true},
{[]int{1, 2}, 2, true},
{[]int{1, 2}, 3, true},
{[]int{1, 2}, 4, false},
{[]int{1, 2, 3, 4, 5}, 7, true},
{[]int{1, 2, 3, 4, 5}, 8, true},
{[]int{1, 2, 3, 4, 5}, 15, true},
{[]int{1, 2, 3, 4, 5}, 16, false},
{[]int{1, 5, 8, 9, 10, 20, 30}, 25, true},
}

for i, test := range tests {
if got := SumUpToInteger(test.numbers, test.sum); got != test.sumsUp {
t.Fatalf("Failed test case #%d. Want %t got %t", i, test.sumsUp, got)
}
}
}