Skip to content

Instantly share code, notes, and snippets.

View houmanka's full-sized avatar

Houman Kargaran houmanka

View GitHub Profile
@houmanka
houmanka / russian_peasant_multiplication_increment.ex
Created March 27, 2020 07:08
russian_peasant_multiplication_increment
defmodule RussianPeasantMultiplication.Increment do
import Monad.Result
@errors %{
zero: "Must be greater than zero",
number: "Requested number and Max round must be numbers"
}
@doc """
@houmanka
houmanka / russian_peasant_multiplication_decrement.ex
Created March 26, 2020 08:44
RussianPeasantMultiplication.Decrement
defmodule RussianPeasantMultiplication.Decrement do
import Monad.Result
@errors %{
zero: "Must be greater than zero",
number_only: "Must be non negetive number"
}
@doc """
defmodule AncientEgyptianMultiplication do
require Integer
def decompose(n) do
power_ready = case Integer.is_odd(n) do
true -> n - 1
false -> n
end
greatest_pow_2 = of(power_ready, []) |> count_of
decompose(n, greatest_pow_2, [])
@houmanka
houmanka / AEM_Step5.exs
Created March 19, 2020 22:58
AEM multiplication
defmodule AncientEgyptianMultiplication do
require Integer
def multiply(first, second) do
decomposed = decompose(first)
multiply(decomposed, second, [])
end
def multiply([], _, state), do: sum_of(state)
# 128 × 13 + 64 × 13 + 32 × 13 + 8 × 13 + 4 × 13 + 2 × 13
def multiply([head | tail], second, state) do
defmodule AncientEgyptianMultiplication do
require Integer
def sum_of([head | tail]) do
sum_of(tail, head)
end
def sum_of([], state), do: state
def sum_of([head | tail], state) do
sum_of(tail, state + head)
@houmanka
houmanka / AEM_decomposition.exs
Created March 19, 2020 09:29
AEM decomposition
defmodule AncientEgyptianMultiplication do
require Integer
def decompose(n) do
power_ready = case Integer.is_odd(n) do
true -> n - 1
false -> n
end
greatest_pow_2 = of(power_ready, []) |> count_of
decompose(n, greatest_pow_2, [])
@houmanka
houmanka / counter.exs
Created March 19, 2020 09:22
Counter with no Enum
defmodule AncientEgyptianMultiplication do
def count_of([_head | tail]) do
count_of(tail, 1)
end
def count_of([], state), do: state
def count_of([_head | tail], state) do
count_of(tail, state + 1)
end
end
@houmanka
houmanka / AEM_Step3.exs
Created March 19, 2020 09:15
Finding the greatest power of 2
defmodule AncientEgyptianMultiplication do
require Integer
def of(n, state) when n <= 1, do: state
def of(n, state) do
n = (n / 2)
|> Kernel.trunc
state = state ++ [n]
of(n, state)
end
@houmanka
houmanka / AEM_Step2.exs
Created March 19, 2020 09:02
A bit more intelligent
defmodule AncientEgyptianMultiplication do
require Integer
def of(n, _, state) when n <= 1, do: state
def of(n, closest_number, state) do
pow_2 = :math.pow(2, closest_number)
case pow_2 < n do
true ->
state = state ++ [pow_2]
@houmanka
houmanka / AEM_Step1.exs
Last active March 18, 2020 12:14
Crude Recursion
"""
238 - 128 = 110
110 - 64 = 46
46 - 32 = 14
14 - 8 = 6
6 - 4 = 2
2 - 2 = 0
"""