Last active
September 15, 2016 10:54
-
-
Save leorog/d12d3b4dc419de51c8dc04f67492d024 to your computer and use it in GitHub Desktop.
WhichIsFaster?
This file contains hidden or 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 Solution do | |
| def recur(x, acc \\ 0) | |
| def recur(0, acc), do: acc | |
| def recur(target, acc) do | |
| if (rem(target, 3) == 0 or rem(target, 5) == 0) do | |
| recur(target - 1, acc + target) | |
| else | |
| recur(target - 1, acc) | |
| end | |
| end | |
| def unfold(target) do | |
| Stream.unfold(target, fn(0) -> nil; x -> {x, x - 1} end) | |
| |> Stream.filter(fn(x) -> rem(x, 3) == 0 or rem(x, 5) == 0 end) | |
| |> Enum.reduce(&Kernel.+/2) | |
| end | |
| def enum(target) do | |
| 1..target | |
| |> Enum.to_list | |
| |> Enum.filter(&(rem(&1, 3) == 0 or rem(&1, 5) == 0)) | |
| |> Enum.sum | |
| end | |
| end | |
| :timer.tc(fn -> Solution.recur(999) end) | |
| :timer.tc(fn -> Solution.unfold(999) end) | |
| :timer.tc(fn -> Solution.enum(999) end) | |
| # {167, 233168} | |
| # {876, 233168} | |
| # {828, 233168} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment