Combine transformations

Real programs chain many moves. Multiplying their matrices once gives a single matrix that does it all.

What to build

Apply a list of transformations in order, and print the one combined matrix and the image of a point.

Requirements

  • Read k moves, each on its own line: rot D, scale SX SY or shear K.
  • The first move is applied first. The combined matrix is T_k × … × T_2 × T_1.
  • Print the two rows of the combined matrix, then the image of the given point.

Input

Line 1: k (1 to 6). Then k move lines. Then a line with the point x and y.

Output

Three lines: a b and c d (the combined matrix), then point X Y. All numbers have 4 decimal places.

Constraints

Angles are between -360 and 360 and the other numbers between -5 and 5.

Example

Input:

2
rot 90
scale 2 3
1 1

Output:

0.0000 -2.0000
3.0000 0.0000
point -2.0000 3.0000

Why it works

Applying T1 and then T2 to p gives T2·(T1·p) = (T2·T1)·p, so the combined matrix puts the later moves on the left. Computing it once is faster than moving every point through every step.

Examples

Example 1 · Input
2
rot 90
scale 2 3
1 1
Expected output
0.0000 -2.0000
3.0000 0.0000
point -2.0000 3.0000
Example 2 · Input
2
scale 2 3
rot 90
1 1
Expected output
0.0000 -3.0000
2.0000 0.0000
point -3.0000 2.0000

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

Hints

Hint 1

Keep a combined matrix M, starting as the identity. For each move T in order, set M = T × M.

Hint 2

Moves: `rot D` rotates by D degrees, `scale SX SY` stretches, `shear K` sends (x, y) to (x + K·y, y).

Hint 3

Round each number with `round(v, 4) + 0.0` before printing with `:.4f`.

Solution

Show one correct solution (try it yourself first)
from math import cos, sin, radians

k = int(input())
moves = [input().split() for _ in range(k)]
x, y = [float(v) for v in input().split()]

def mul(a, b):
    return [[sum(a[i][t] * b[t][j] for t in range(2)) for j in range(2)] for i in range(2)]

def r(v):
    return f"{round(v, 4) + 0.0:.4f}"

M = [[1.0, 0.0], [0.0, 1.0]]
for m in moves:
    if m[0] == "rot":
        t = radians(float(m[1]))
        T = [[cos(t), -sin(t)], [sin(t), cos(t)]]
    elif m[0] == "scale":
        T = [[float(m[1]), 0.0], [0.0, float(m[2])]]
    else:
        T = [[1.0, float(m[1])], [0.0, 1.0]]
    M = mul(T, M)
print(r(M[0][0]), r(M[0][1]))
print(r(M[1][0]), r(M[1][1]))
print("point", r(M[0][0] * x + M[0][1] * y), r(M[1][0] * x + M[1][1] * y))

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

Lesson: Matrices as transformations →