File size: 993 Bytes
9461f74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
defmodule Bob.Hasher do
  @moduledoc """
  Bob's implementation of the integer hashing challenge.
  Uses iterative approaches for better performance.
  """

  @doc """
  Computes SHA-256 hash of a string.
  """
  def sha256(input) do
    :crypto.hash(:sha256, input) |> Base.encode16(case: :lower)
  end

  @doc """
  Sums a list of integers iteratively.
  """
  def sum_list(list) do
    do_sum(list, 0)
  end

  defp do_sum([], acc), do: acc
  defp do_sum([head | tail], acc), do: do_sum(tail, acc + head)

  @doc """
  Computes factorial iteratively.
  """
  def factorial(n) do
    do_factorial(n, 1)
  end

  defp do_factorial(0, acc), do: acc
  defp do_factorial(n, acc), do: do_factorial(n - 1, acc * n)

  @doc """
  Main entry point that routes to the appropriate function.
  """
  def solve(:sha256_forge, input), do: sha256(input)
  def solve(:sum_list, input), do: sum_list(input)
  def solve(:factorial_5, input), do: factorial(input)
  def solve(_challenge, _input), do: nil
end