Home > Software design >  Each memeber of a list of floats in a list is smaller than previous
Each memeber of a list of floats in a list is smaller than previous

Time:12-17

I have a long list (1000 ) of numbers that is mix of integers and floats (so 1.3 and 2.5 but also 3 or 5).

Generally, they should be following the decreasing pattern so from the biggest to the lowest.

But there are some black sheeps that break this rule and I want to find them.

Here is part of my list:

list = [100.242, 95, 94.3, 96, 65.5, 67.7, 51.25, 43, 23.99] # 96 and 67.7 are bad actors

Now, I need to make a function that will pick out those bad numbers and put them in a list I can print.

Any idea how to do that?

CodePudding user response:

Enum.reduce/3 is always to the rescue in these kinds of problems

Enum.reduce(list, {[], []}, fn
  e, {[], []} -> {[e], []}
  e, {[h|t], ko} when e > h -> {[h|t], [e|ko]}
  e, {ok, ko} -> {[e|ok], ko}
end)
#⇒ {[23.99, 43, 51.25, 65.5, 94.3, 95, 100.242], [67.7, 96]}

Plain recursion would also work perfectly.

  • Related