{
"id": "253",
"prompt": "A desktop-toy Newton's cradle in 1-D: three equal balls slide on a horizontal rail (x and v per ball in state slots, 1/8-px fixed point) and the walls reflect them. The whole trick for equal-mass elastic collisions is a velocity SWAP: when two adjacent balls come within one diameter, exchange their velocities and re-seat them a diameter apart so they never interpenetrate. Start with the left ball flying at the two parked in the middle and the impulse should hand off through the row forever - no energy loss anywhere.",
"solution_rl": "fn frame(t: i32) {\n let w: i32 = host::display::width();\n let h: i32 = host::display::height();\n if host::display::state_get(0) == 0 {\n host::display::state_set(0, 1);\n host::display::state_set(8, 60 * 8);\n host::display::state_set(9, 40);\n host::display::state_set(10, (w / 2 - 20) * 8);\n host::display::state_set(11, 0);\n host::display::state_set(12, (w / 2 + 20) * 8);\n host::display::state_set(13, 0);\n }\n let mut x = [0; 3];\n let mut v = [0; 3];\n let mut i: i32 = 0;\n while i < 3 {\n x[i] = host::display::state_get(8 + i * 2);\n v[i] = host::display::state_get(9 + i * 2);\n i = i + 1;\n }\n i = 0;\n while i < 3 {\n x[i] = x[i] + v[i];\n if x[i] < 20 * 8 { x[i] = 20 * 8; v[i] = -v[i]; }\n if x[i] > (w - 20) * 8 { x[i] = (w - 20) * 8; v[i] = -v[i]; }\n i = i + 1;\n }\n i = 0;\n while i < 2 {\n if x[i + 1] - x[i] < 224 {\n let tmp: i32 = v[i];\n v[i] = v[i + 1];\n v[i + 1] = tmp;\n let mid: i32 = (x[i] + x[i + 1]) / 2;\n x[i] = mid - 112;\n x[i + 1] = mid + 112;\n }\n i = i + 1;\n }\n i = 0;\n while i < 3 {\n host::display::state_set(8 + i * 2, x[i]);\n host::display::state_set(9 + i * 2, v[i]);\n i = i + 1;\n }\n host::display::clear(0x101014);\n let ty: i32 = h / 2;\n host::display::fill_rect(0, ty + 14, w, 3, 0x404048);\n let pal: [i32; 3] = [0xe05040, 0x40c060, 0x5080e0];\n i = 0;\n while i < 3 {\n host::display::fill_rect(x[i] / 8 - 14, ty - 14, 28, 28, pal[i]);\n host::display::fill_rect(x[i] / 8 - 8, ty - 8, 8, 8, 0xffffff);\n i = i + 1;\n }\n host::display::draw_string(8, 8, \"EQUAL MASS = SWAP V\", 0x707070, 1);\n host::display::present();\n}\n",
"tags": [
"simulation",
"collision",
"physics",
"state"
]
}