Skip to content

Instantly share code, notes, and snippets.

@Faheetah
Last active November 27, 2025 03:14
Show Gist options
  • Select an option

  • Save Faheetah/5081eeefbda50c18ff8c893f38664898 to your computer and use it in GitHub Desktop.

Select an option

Save Faheetah/5081eeefbda50c18ff8c893f38664898 to your computer and use it in GitHub Desktop.
Elixir fizzbuzz gore
Enum.each(elem(Enum.map_reduce(1..99, %{3 => 7379564129366843424, 5 => 7094711452935659552, 0 => 7379564130479733370}, fn i, acc -> {<<Map.get(acc, rem(i,15), :binary.decode_unsigned(String.pad_trailing(to_string(i),8)))::64>>, acc} end),0), &IO.puts/1)
Enum.each( # iterate over the final resulting list - ["1 ", "2 ", "fizz ", "4 ", "buzz ", "6 ",...
elem( # select the first element, dropping the map_reduce accumulator - {["1 ", "2 ", "fizz ", "4 ", "buzz ", "6 ", ... %{0 => 7379564130479733370, 3 => 7379564129366843424, 5 => 7094711452935659552}}
Enum.map_reduce( # reduce over:
1..99, # range of 1 through 99
%{ # using a map of
3 => 7379564129366843424, # :binary.decode_unsigned("fizz ") aka <<105,102,122,122,32,32,32,32>>
5 => 7094711452935659552, # :binary.decode_unsigned("buzz ") aka <<98,117,122,122,32,32,32,32>>
0 => 7379564130479733370 # :binary.decode_unsigned("fizzbuzz") aka <<105,102,122,122,98,117,122,122>>
}, # end of map
fn i, acc -> # map_reduce iterator function
{ # return a tuple of
<< # extract an integer from:
Map.get( # get from the accumulator map:
acc, # the accumulator (above map of integers)
rem(i,15), # using the key that matches the current number mod 15
:binary.decode_unsigned( # default to a 64 bit unsigned integer decoded from:
String.pad_trailing( # pad a string to ensure it can match 8 bytes
to_string(i), # convert the current number to a string
8 # pad to 8 bytes
) # end of String.pad_trailing
) # end of :binary.decode_unsigned
) # end of Map.get
::64>>, # extract the integer as 64 bits, returning a number similar to the accumulator map values
acc # include the accumulator in the map_reduce return tuple
} # end of return tuple
end # end of map_reduce iterator function
), # end of map_reduce
0 # select the first element
), # end of elem
&IO.puts/1 # print each element
) # end of Enum.each
# same as above but without the binary manipulation and using pipes
Enum.map_reduce(1..99, %{3 => "fizz", 5 => "buzz", 0 => "fizzbuzz"}, fn i, acc -> {Map.get(acc, rem(i,15), i), acc} end) |> elem(0) |> Enum.each(&IO.puts/1)
# more idiomatic using &Enum.each/3
Enum.each(1..99, & Map.get(%{3 => "fizz", 5 => "buzz", 0 => "fizzbuzz"}, rem(&1, 15), &1) |> IO.puts)
@Faheetah
Copy link
Author

If anybody is wondering why, the answer is because binaries are fun.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment