Skip to content

Instantly share code, notes, and snippets.

@brweber2
Created April 27, 2016 12:14
Show Gist options
  • Save brweber2/5d594842ac81d55d92ee6b44510bfc45 to your computer and use it in GitHub Desktop.
Save brweber2/5d594842ac81d55d92ee6b44510bfc45 to your computer and use it in GitHub Desktop.
# Use this code and data to answer the questions.
defmodule Millenium.Falcon do
def rebel?(c = %{rebel: true}) do
c.type != :droid
end
def rebel?(_), do: false
def fill_ship(characters) do
characters
|> Enum.map(&(&1.name))
|> Enum.join(",")
end
end
characters = [
%{name: "Han", type: :human, rebel: true, weight: 185},
%{name: "Jabba", type: :hutt, rebel: false, weight: 2200},
%{name: "Chewie", type: :wookie, rebel: true, weight: 350},
%{name: "r2d2", type: :droid, rebel: true, weight: 250},
%{name: "Luke", type: :human, rebel: true, weight: 140},
%{name: "Boba Fett", type: :human, rebel: false, weight: 175},
]
# Question 1 - Create a list of all the rebel scum
characters
|> Enum.filter(&Millenium.Falcon.rebel?/1)
|> IO.inspect
# Question 2 - Fill the Millenium Falcon with all the rebels
characters
|> Enum.filter(&Millenium.Falcon.rebel?/1)
|> Millenium.Falcon.fill_ship
|> IO.puts
# Question 3 - How much do all the humans weigh?
characters
|> Enum.filter(fn(c) -> Map.get(c, :type) == :human end)
|> Enum.reduce(0, fn(h, acc) -> h.weight + acc end)
|> IO.puts
# Question 4 (BONUS) - If the Millenium Falcon can hold 1000 pounds, what is the optimal set of characters?
characters
|> Enum.sort(fn(c1,c2) -> c1.weight < c2.weight end)
|> Enum.flat_map_reduce(0, fn(c,acc) -> if c.weight + acc < 1000, do: {[c], c.weight + acc}, else: {:halt, acc} end)
|> elem(0)
|> IO.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment