kimc0de

kimc0de

How to compare integer in a list and return a list of integer and its frequencies

Hi all, I’m trying to do some Leetcode exercises in elixir.
I have a function that takes an integer and it needs to return a list of lists that includes the digit frequency and the digit itself.
Something list this for example number = 11223411 => return [ [2,1], [2,2], [1,3] [1,4], [2,1] ]
The first number is the frequency and the second one is the digit itself. I’m stuck on counting the digit.

So here’s where I am

    list_of_integer = Integer.digits(number)
    list_length = len(list_of_integer)

    for n <- 0..(list_length-2) do
         if (Enum.at(list_of_integer, n) == (Enum.at(list_of_integer, n + 1))) do 
               # here am not really sure what to do next.. is it the right approach tho? :(     
         end
    end

This Leetcode is number 38 ‘count and say’. If anyone has done it, I would appreciate it if you could share your approach to solving this.

Marked As Solved

al2o3cr

al2o3cr

A general note: 99.9% of the time, if you find yourself writing Enum.at inside of a loop - especially with an index value that can go all the way to the end - you should consider a different approach. The motivation is that every call to Enum.at takes time proportional to the index so accessing elements at the end gets increasingly expensive.

For this specific problem, it’s worth calling out how this isn’t solved by Integer.digits + Enum.frequencies: the digits are only counted when they are together.

Skimming through the list of functions in Enum (you should do this, A LOT) we find a promising function: chunk_by:

https://hexdocs.pm/elixir/Enum.html#chunk_by/2

An example of using this looks like:

number
|> Integer.digits()
|> Enum.chunk_by(& &1)

which would result in [[1, 1], [2, 2], [3], [4], [1, 1]] where each element of the list is a list of the same number over and over.

Then you can transform that result into the counts you’re expecting:

number
|> Integer.digits()
|> Enum.chunk_by(& &1)
|> Enum.map(fn many_digits -> [length(many_digits), hd(many_digits)] end)

Also Liked

LostKobrakai

LostKobrakai

With elixir you don’t (and usually can’t) solve issues by using loops like you’d do in non-functional languages. You’d want to look into reducing over your data to get to the expected result. for might look like a loop, but it’s not.

kokolegorille

kokolegorille

You should try not to think how You would solve this in your previous language. It will only slow You down.

A good start, as mentionned by @al2o3cr is to learn the Enum module.

A solution with Enum.reduce might look like this. What You need to understand, value don’t change, but can be transformed.

{list, previous, count} = Enum.reduce(list_of_integer, {[], nil, 0}, fn integer, {list, previous, count} -> 
  if integer == previous do
    ... return an acc with incremented count
  else
   ... return an acc with count = 1, previous = integer, update list with new element
  end
end)
mpope

mpope

Could use Enum.reduce/3!

reducer = fn (digit, acc) ->
  case acc[digit] do
    nil -> Map.put(acc, digit, 1)
    current_count -> Map.put(acc, digit, current_count + 1)
  end
end

11223411
|> Integer.to_string
|> String.graphemes
|> Enum.reduce(%{}, reducer)
|> Map.to_list

Result: [{"1", 4}, {"2", 2}, {"3", 1}, {"4", 1}]

Where Next?

Popular in Questions Top

Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement