Row order or column order

A two-dimensional array is stored row by row. Walking it by rows touches neighbours one after the other, and walking it by columns jumps across the array.

What to build

A program that counts how many blocks a tiny cache must load when a program visits every element of the array in a given order.

Requirements

  • The array has rows rows and cols columns, stored row by row, so element (r, c) has index r × cols + c. Memory is cut into blocks of block elements, and block number is index ÷ block, rounded down.
  • The cache holds only one block, the one used last. An access to another block loads it (one block load) and replaces the old one.
  • The order is row (go along each row in turn) or col (go down each column in turn). Print block loads N.

Input

One line: rows, cols, block and the order.

Output

One line.

Constraints

1 ≤ rows, cols ≤ 100; 1 ≤ block ≤ 64.

Example

Input:

4 4 4 row

Output:

block loads 4

Why it works

Visiting by rows follows memory order, so each block is loaded once and then used block times. Visiting by columns jumps cols elements each time and often lands in a different block, so blocks are reloaded again and again.

Examples

Example 1 · Input
4 4 4 row
Expected output
block loads 4
Example 2 · Input
4 4 4 col
Expected output
block loads 16

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Element (r, c) of a row-major array has index r * cols + c, and lives in block index // block.

Hint 2

Visit order by rows is r outer, c inner; by columns is c outer, r inner. Keep the block number you loaded last.

Solution

Show one correct solution (try it yourself first)
rows, cols, block, order = input().split()
rows, cols, block = int(rows), int(cols), int(block)
if order == "row":
    seq = [(r, c) for r in range(rows) for c in range(cols)]
else:
    seq = [(r, c) for c in range(cols) for r in range(rows)]
held, loads = None, 0
for r, c in seq:
    b = (r * cols + c) // block
    if b != held:
        loads += 1
        held = b
print("block loads", loads)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: The memory hierarchy →