Skip to content

Instantly share code, notes, and snippets.

@vysakh0
Last active June 29, 2016 14:51
Show Gist options
  • Save vysakh0/ffb4ee20e4d799b318ddfb5522148425 to your computer and use it in GitHub Desktop.
Save vysakh0/ffb4ee20e4d799b318ddfb5522148425 to your computer and use it in GitHub Desktop.
Find if subarray with given sum exists
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
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