16 Dezember 2020

Wenn das Kopfrechnen Grenzen hat

Homeschooling setzt Eltern auch schon bei 3.-Klasse-Aufgaben vor Grenzen. Das habe ich selbst gemerkt. Aber im Hunderterbereich muss auch ich mit schriftlich rechnen. Da ich von Haus aus faul bin, habe ich aber ein kleines Programm geschrieben, das mir die Arbeit erleichtert:

Some more context

As I had been asked. The riddles basically look likes this:

10_15
___
25_50

With this being the solution

10515
152035
252550

as

  • Row-wise:
    • 10+5 = 15
    • 15+20 = 35
    • 25+25 = 50
  • and column-wise:
    • 10+15 = 25
    • 5+20 = 25
    • 15+35 = 50

How the problem is modeled

The table is represented as a 2d-Array (first dimension: rows, second dimension: cols). If a number value is given, the „cell“ is given that particular value, otherwise the value in None.

Solving a riddle

First, we have to find out, whether we still have to calculate something. The function not_solved() iterates through all cells, as soon it finds a value still being None, it returns True. Otherwise it returns False.

As long as not_solved() returns True, we look on each row individually (line 10-22). For each row, we iniate nn as an empty list, then each cell is checked. If the value is None, we save the column number in nf (line 14f.), otherwise we put the value in the nn-list (line 17). If there are two values in the nn-list, we can solve this row (line 18-22) and the row lacks a solution. There are two cases now:

  1. The sum is the value missing (right column): Then, we have to add the two other values. As we have saved them along the way in nn, we just add these two values, and put this value in the cell. (line 20)
  2. The sum is one of the values given: Then we subtract the maximum value in the nn list (which has to be the sum) from its minimal value. And put this result in the empty cell. (line 22)

After all rows are checked, the same is done with the columns, before the while-loop is iniated once more.

Solving multiple riddles

As there was more than one riddle. All of them were put in a dictionary (fields, lines 38-47) with the task number (e.g. 3a1) as key and the riddle model as values.

Then, each riddle is solved (line 50) and the solutions are printed line-by-line (line 52f.).