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
afterDelay(4, () -> {
    B
    afterDelay(1, () -> C);
    D
    onKeyPress(() -> {
        E
        onKeyPress(() -> {
            F
        });
        G
    });
    H
});
I
afterDelay(1, () -> {
    J
    afterDelay(1, () -> K);
    L
    onKeyPress(() -> {
        M
        onClick(() -> {
            N
        });
        O
    });
    P
});
Q
onKeyPress(() -> {
    R
    twice(() -> {
        S
        onClick(() -> T);
        U
    });
    V
    afterDelay(1, () -> {
        W
        twice(() -> {
            X
        });
        Y
    });
    Z
});
AA
twice(() -> {
    AB
    onClick(() -> {
        AC
        twice(() -> AD);
        AE
    });
    AF
    afterDelay(2, () -> AG);
    AH
});
AI
afterDelay(3, () -> {
    AJ
    afterDelay(2, () -> {
        AK
        twice(() -> {
            AL
        });
        AM
    });
    AN
    onClick(() -> AO);
    AP
});
AQ

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
KEY
TICK
TICK
TICK
TICK
KEY
KEY
TICK
TICK
TICK
TICK
CLICK
TICK
TICK
KEY
KEY

Solution

A
AB
AB

CLICK
AC
AD
AD
AC
AD
AD

KEY
R
S
S

TICK

TICK
J
W
X
X

TICK
AG
AG

TICK
AJ
K

KEY
R
S
S
M

KEY
R
S
S
M

TICK
B

TICK
W
X
X
W
X
X

TICK
AK
AL
AL
C

TICK

CLICK
AC
AD
AD
AC
AD
AD
T
T
AO
T
T
N
T
T
N

TICK

TICK

KEY
R
S
S
M
E

KEY
R
S
S
M
E
F

AFTER
I
Q
AA
AF
AH
AF
AH
AI
AQ
AE
AE
U
U
V
Z
L
P
Y
AN
AP
U
U
V
Z
O
U
U
V
Z
O
D
H
Y
Y
AM
AE
AE
U
U
V
Z
O
G
U
U
V
Z
O
G

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
Hi!

Related puzzles: