We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Post 33
Hacker Rank 07 - FIlter Elements
Published on: 2025-06-02
Tags:
elixir, Blog, Side Project, Hacker Rank, Phoenix
For this one we are given a pair of: number_of_elements, number_threshold list_of_elements Our goal is to take the list_of_elements and see how many of the elements have a count equal to or above the number_threshold. If there is no element to meet the criteria output -1 for the list 9 2 4 5 2 5 4 3 1 3 4 Output: 4 5 3 For this exercise I wanted to have a list of the elements and a tuple/map for the {element, count} In this way I can be sure the elements remain in the order you see them and then still be able to keep track of the count. I won't go over how I got the input into the format [number_threshold, [list_of_elements]] But once you have them into this format I was able to use this function: def map_each_pair(pairs) do Enum.map(pairs, fn {number, elements} -> {number, count_with_order(elements)} end) end # This is the helper function that will map the format above to the format we will need to # pass to the count with order. As you might be able to see we want the number (threshold) and then # the count_with_order/1 defp count_with_order(list) do {counts, reversed_order} = Enum.reduce(list, {%{}, []}, fn elem, {map, order} -> # takes the elements and runs them through updated_map = Map.update(map, elem, 1, &(&1 + 1)) # takes the current set of element pairs updated_order = if Map.has_key?(map, elem), do: order, else: [elem | order] # if the element is in the list dont effect the order, if it is the append {updated_map, updated_order} # after all the elements are set you now have the order and the set of counts end) Enum.reverse(reversed_order) # reverse the order to make sure its in the right order |> Enum.map(fn key -> {key, counts[key]} end) # Take the map and be sure it is in a list end This will take the format from above and then map the {element, count} and while maintain the order you see them in. Check out the comments above for each step. def number_of_elements(list) do Enum.map(list, fn {number, counted_list} -> # we want to check to see if the counts are above a certain threshold counted_list |> Enum.filter(fn {_el, size} -> size >= number end) # Filters out the counts |> Enum.map(fn {el, _} -> el end) # maps just the elements |> is_empty() # See function below end) end defp is_empty([]), do: [-1] # if the list is empty do -1 defp is_empty(list) when is_list(list), do: list # If it has elements just return the element This takes a list of the format above, and then does work on them to get them to only keep the elements that are above the right count. You should now have a list that contains all the elements that are above the threshold. Ill leave the printing up to the reader.
