Similar subtraction between 2 maps

I have another subtraction, similar to Subtraction between 2 List of maps

but this time, its between 2 maps,

%{89.394 => 4.3, 90.15 => 1.305, 90.394 => 2.245}

and

%{90.15 => 3.4, 100.15 => 3.8}

I am trying to produce the result

%{80.394 => 4.3, 90.15 => -0.15} in the first map

and

%{100.15 => 3.8} in the second map.

Any advice?

What have you tried so far? At a minimum, describe what the rules are that lead to the results from the inputs.

1 Like

I’m not sure how clear I can explain this but here goes:-

  1. The second map has to compare its keys with the first map i.e. if the second map’s key is lesser than or equal to the first map’s key, the second map’s value has to subtract the first map’s value.

so here first map = %{89.394 => 4.3, 90.15 => 1.305, 90.394 => 2.245}
and second_map = %{90.15 => 3.4, 100.15 => 3.8}

  1. first_map keys that are greater than or equal to 2nd map keys are 90.394 and 90.15

  2. The value from second map i.e. 90.15 => 3.4 minus 90.394 => 2.245 first leaving a balance in the second map of 90.15 => 1.155

  3. The balance i.e. 90.15 => 1.155 must minus 90.15 => 1.305 from the first map, producing a negative balance 90.15 => -0.15 .

  4. The negative balance will be in the first_map %{90.15 => -0.15, 89.394 => 4.3}
    and the second map will be left with %{100.15 => 3.8}

OK cool, so try to convert that to Elixir code, and then we can offer feedback. You won’t learn anything we just hand you the solutions to these kinds of questions.

1 Like

I’d suggest that you formulate a much clearer, more rigorous problem description before attempting to actually code it. Often the solution will fall out of the problem description once the problem is well enough described.

For example, in an attempt to understand your description I arrived at:

Note that the description works with mutable A and B sets (maps) - while everything is immutable in Elixir.

Bonus: Enum.split_with/2 might come in handy.

1 Like