Last active
June 29, 2016 14:51
-
-
Save vysakh0/ffb4ee20e4d799b318ddfb5522148425 to your computer and use it in GitHub Desktop.
Find if subarray with given sum exists
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
defmodule SubarraySum do | |
def run([], val), do: false | |
def run([ _ | rest ] = arr, val) do | |
run(arr, val, 0) || run(rest, val) | |
end | |
def run(_, val, val), do: true | |
def run([], _val, _res), do: false | |
def run(_, val, res) when(val < res), do: false | |
def run([ first | rest ], val, res) do | |
run(rest, val, first + res) | |
end | |
end |
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
defmodule SubarraySumTest do | |
use ExUnit.Case | |
test "find if consecutive elements sums to given num" do | |
assert SubarraySum.run([1, 3, 4, 5, 2], 12) === true | |
assert SubarraySum.run([1, 9, 4, 5, 2], 12) === false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment