Closures and event handling: Correct Solution


Suppose we are in an environment where CLICK, TICK, and KEY events can occur, and we have the following functions available:

onClick(closure)

Executes closure after every subsequent CLICK event.

onKeyPress(closure)

Executes closure after every subsequent KEY event.

afterDelay(tickCount, closure)

Executes closure once after exactly tickCount TICK events have occurred.

twice(closure)

Immediately executes closure two times.

Multiple closures can be registered to handle the same event. If this happens, they execute in the order they were registered.


Part 1

Consider the following code:

A
twice(() -> {
    B
    afterDelay(2, () -> {
        C
        onKeyPress(() -> {
            D
        });
        E
    });
    F
    onClick(() -> {
        G
        twice(() -> H);
        I
    });
    J
});
K
afterDelay(1, () -> L);
M
onClick(() -> N);
O
onKeyPress(() -> {
    P
    afterDelay(2, () -> {
        Q
        onClick(() -> {
            R
        });
        S
    });
    T
    onClick(() -> {
        U
        twice(() -> {
            V
        });
        W
    });
    X
});
Y
afterDelay(2, () -> {
    Z
    onKeyPress(() -> AA);
    AB
    afterDelay(2, () -> {
        AC
        twice(() -> {
            AD
        });
        AE
    });
    AF
});
AG

Write out the order in which all the marked statements will execute given the following sequence of events (showing both the marked statements and the event names):

CLICK
CLICK
TICK
TICK
TICK
TICK
KEY
KEY
TICK
CLICK
TICK
TICK
CLICK
CLICK
TICK

Solution

A
B
B

CLICK
G
H
H
G
H
H
N

CLICK
G
H
H
G
H
H
N

TICK

TICK
L

TICK
C
C
Z

TICK

KEY
P
D
D
AA

KEY
P
D
D
AA

TICK

CLICK
G
H
H
G
H
H
N
U
V
V
U
V
V

TICK
AC
AD
AD

TICK
Q
Q

CLICK
G
H
H
G
H
H
N
U
V
V
U
V
V
R
R

CLICK
G
H
H
G
H
H
N
U
V
V
U
V
V
R
R

TICK

AFTER
F
J
F
J
K
M
O
Y
AG
I
I
I
I
E
E
AB
AF
T
X
T
X
I
I
W
W
AE
S
S
I
I
W
W
I
I
W
W

Part 2

Consider the following code:

public class StatefulPuzzle {
    private int x = 0;

    public void run() {
        onClick(() -> {
            x++;
            System.out.println("x=" + x);
        });

        if (x < 1) {
            onClick(() -> {
                System.out.println("Hi!");
            });
        }

        onClick(() -> {
            if (x > 0) {
                System.out.println("Bye!");
            }
        });

        System.out.println("End of run()");
    }
}

Given a call to run() followed by two CLICK events, what would this code print?

Solution

End of run()
x=1
x=2

Related puzzles: