Skip to content

Commit

Permalink
Add game-of-life exercise
Browse files Browse the repository at this point in the history
  • Loading branch information
atk committed Nov 27, 2024
1 parent a18349c commit ba00596
Show file tree
Hide file tree
Showing 11 changed files with 8,531 additions and 28 deletions.
25 changes: 25 additions & 0 deletions exercises/practice/game-of-life/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Instructions

After each generation, the cells interact with their eight neighbors, which are cells adjacent horizontally, vertically, or diagonally.

The following rules are applied to each cell:

- Any live cell with two or three live neighbors lives on.
- Any dead cell with exactly three live neighbors becomes a live cell.
- All other cells die or stay dead.

Given an array of 1s and 0s (corresponding to live and dead cells) and the number of cols and rows, apply these rules to each cell, and return the next generation as an offset of an u8 array or 1s and 0s with the same length.

```js
// test data
[
[0, 0, 0],
[0, 0, 0],
[1, 1, 1]
]

// wasm data (* refers to the offset)
*Uint8Array[0, 0, 0, 0, 0, 0, 1, 1, 1] (i32.const 3) (i32.const 3)
```

You should be aware of the edges of your matrix represented as an array and need to prevent non-neighbors to leak into your count.
9 changes: 9 additions & 0 deletions exercises/practice/game-of-life/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Introduction

[Conway's Game of Life][game-of-life] is a fascinating cellular automaton created by the British mathematician John Horton Conway in 1970.

The game consists of a two-dimensional grid of cells that can either be "alive" or "dead."

After each generation, the cells interact with their eight neighbors via a set of rules, which define the new generation.

[game-of-life]: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
22 changes: 22 additions & 0 deletions exercises/practice/game-of-life/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"authors": [
"atk"
],
"files": {
"solution": [
"game-of-life.wat"
],
"test": [
"game-of-life.spec.js"
],
"example": [
".meta/game-of-life.wat"
],
"invalidator": [
"package.json"
]
},
"blurb": "Implement Conway's Game of Life.",
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life"
}
46 changes: 46 additions & 0 deletions exercises/practice/game-of-life/.meta/game-of-life.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
(module
(memory (export "mem") 1)

;;
;; Create the next frame of Conway's Game of Life
;;
;; @param {i32} offset - The offset of the current frame in linear memory
;; @param {i32} length - The length of the current frame in linear memory
;;
;; @returns {(i32,i32)} - The offset and length of the next frame in linear memory
;;
(func (export "next") (param $offset i32) (param $cols i32) (param $rows i32) (result i32)
(local $pos i32) (local $nbpos i32) (local $length i32) (local $count i32) (local $edges i32) (local $bottom i32)
(local.set $length (i32.mul (local.get $cols) (local.get $rows)))
(local.set $bottom (i32.mul (i32.sub (local.get $rows) (i32.const 1)) (local.get $cols)))
(loop $cell
(local.set $edges
(i32.or (i32.shl (i32.lt_u (local.get $pos) (local.get $cols)) (i32.const 3)) ;; top
(i32.or (i32.shl (i32.ge_u (local.get $pos) (local.get $bottom)) (i32.const 2)) ;; bottom
(i32.or (i32.shl (i32.eqz (i32.rem_u (local.get $pos) (local.get $cols))) (i32.const 1)) ;; left
(i32.eq (i32.rem_u (i32.add (local.get $pos) (i32.const 1)) (local.get $cols)) (i32.const 0)))))) ;; right
(local.set $count
(i32.add (i32.add (i32.add (i32.add (i32.add (i32.add (i32.add
(i32.and (i32.eqz (i32.and (local.get $edges) (i32.const 10))) ;; -1, -1
(i32.load8_u (i32.sub (i32.sub (i32.add (local.get $offset) (local.get $pos)) (local.get $cols)) (i32.const 1))))
(i32.and (i32.eqz (i32.shr_u (local.get $edges) (i32.const 3))) ;; 0, -1
(i32.load8_u (i32.sub (i32.add (local.get $offset) (local.get $pos)) (local.get $cols)))))
(i32.and (i32.eqz (i32.and (local.get $edges) (i32.const 9))) ;; 1, -1
(i32.load8_u (i32.add (i32.sub (i32.add (local.get $offset) (local.get $pos)) (local.get $cols)) (i32.const 1)))))
(i32.and (i32.eqz (i32.and (local.get $edges) (i32.const 2))) ;; -1, 0
(i32.load8_u (i32.sub (i32.add (local.get $offset) (local.get $pos)) (i32.const 1)))))
(i32.and (i32.eqz (i32.and (local.get $edges) (i32.const 1))) ;; 1, 0
(i32.load8_u (i32.add (i32.add (local.get $offset) (local.get $pos)) (i32.const 1)))))
(i32.and (i32.eqz (i32.and (local.get $edges) (i32.const 6))) ;; -1, 1
(i32.load8_u (i32.sub (i32.add (i32.add (local.get $offset) (local.get $pos)) (local.get $cols)) (i32.const 1)))))
(i32.and (i32.eqz (i32.and (local.get $edges) (i32.const 4))) ;; 0, 1
(i32.load8_u (i32.add (i32.add (local.get $offset) (local.get $pos)) (local.get $cols)))))
(i32.and (i32.eqz (i32.and (local.get $edges) (i32.const 5))) ;; 1, 1
(i32.load8_u (i32.add (i32.add (i32.add (local.get $offset) (local.get $pos)) (local.get $cols)) (i32.const 1))))))
(i32.store8 (i32.add (i32.const 128) (local.get $pos))
(i32.eq (i32.or (i32.load8_u (i32.add (local.get $offset) (local.get $pos)))
(local.get $count)) (i32.const 3)))
(local.set $pos (i32.add (local.get $pos) (i32.const 1)))
(br_if $cell (i32.lt_u (local.get $pos) (local.get $length))))
)
)
21 changes: 21 additions & 0 deletions exercises/practice/game-of-life/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Exercism

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 4 additions & 0 deletions exercises/practice/game-of-life/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
presets: ["@exercism/babel-preset-javascript"],
plugins: [],
};
185 changes: 185 additions & 0 deletions exercises/practice/game-of-life/game-of-life.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import { compileWat, WasmRunner } from "@exercism/wasm-lib";

let wasmModule;
let currentInstance;

beforeAll(async () => {
try {
const watPath = new URL("./game-of-life.wat", import.meta.url);
const { buffer } = await compileWat(watPath);
wasmModule = await WebAssembly.compile(buffer);
} catch (err) {
console.log(`Error compiling *.wat: \n${err}`);
process.exit(1);
}
});

function next(input) {
const inputBufferOffset = 64;
const inputBufferCapacity = 256;
const cells = input.flat();
const rows = input.length;
const cols = cells.length / rows;

if (cells.length > inputBufferCapacity)
throw new Error(`Matrix is too large for buffer of size ${inputBufferCapacity} byte`);

// write current
const inputSegment = currentInstance.get_mem_as_u8(
inputBufferOffset,
cells.length
);
inputSegment.set(cells, 0);

// Pass offset, cols and rows to WebAssembly function
const outputOffset = currentInstance.exports.next(
inputBufferOffset,
cols,
rows
);

const outputSegment = currentInstance.get_mem_as_u8(
outputOffset,
cells.length
)

// decode the same matrix from the returned offset
const output = [...outputSegment.values()].reduce(
(board, cell) => {
if (board.length === 0 || board.at(-1).length === cols) board.push([]);
board.at(-1).push(cell);
return board;
},
[]
);

return output;
}

// serialize the matrix to make the output more helpful
const serialize = (matrix) =>
matrix.map(line => line.join('')).join('\n');

describe("Game of Life", () => {
beforeEach(async () => {
currentInstance = null;
if (!wasmModule) {
return Promise.reject();
}
try {
currentInstance = await new WasmRunner(wasmModule);
return Promise.resolve();
} catch (err) {
console.log(`Error instantiating WebAssembly module: ${err}`);
return Promise.reject();
}
});

test("live cell with zero neighbors dies", () => {
const expected = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
const actual = next([
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
]);
expect(serialize(actual)).toEqual(serialize(expected));
});

xtest("live cells with only one neighbor dies", () => {
const expected = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
const actual = next([
[0, 0, 0],
[0, 1, 0],
[0, 1, 0]
]);
expect(serialize(actual)).toEqual(serialize(expected));
});

xtest("live cells with two neighbors stay alive", () => {
const expected = [
[0, 0, 0],
[1, 0, 1],
[0, 0, 0]
];
const actual = next([
[1, 0, 1],
[1, 0, 1],
[1, 0, 1]
]);
expect(serialize(actual)).toEqual(serialize(expected));
});

xtest("live cells with three neighbors stay alive", () => {
const expected = [
[0, 0, 0],
[1, 0, 0],
[1, 1, 0]
];
const actual = next([
[0, 1, 0],
[1, 0, 0],
[1, 1, 0]
]);
expect(serialize(actual)).toEqual(serialize(expected));
});

xtest("dead cells with three neighbors come alive", () => {
const expected = [
[0, 0, 0],
[1, 1, 0],
[0, 0, 0]
];
const actual = next([
[1, 1, 0],
[0, 0, 0],
[1, 0, 0]
]);
expect(serialize(actual)).toEqual(serialize(expected));
});

xtest("live cells with four or more neighbors dies", () => {
const expected = [
[1, 0, 1],
[0, 0, 0],
[1, 0, 1]
];
const actual = next([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
]);
expect(serialize(actual)).toEqual(serialize(expected));
});

xtest("bigger matrix", () => {
const expected = [
[1, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0],
[1, 0, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 0, 0, 1, 0, 0, 1],
[1, 1, 0, 1, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1]
];
const actual = next([
[1, 1, 0, 1, 1, 0, 0, 0],
[1, 0, 1, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 0],
[1, 0, 0, 0, 1, 1, 0, 0],
[1, 1, 0, 0, 0, 1, 1, 1],
[0, 0, 1, 0, 1, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 1]
]);
expect(serialize(actual)).toEqual(serialize(expected));
});
});
15 changes: 15 additions & 0 deletions exercises/practice/game-of-life/game-of-life.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
(module
(memory (export "mem") 1)

;;
;; Create the next frame of Conway's Game of Life
;;
;; @param {i32} offset - The offset of the current frame in linear memory
;; @param {i32} length - The length of the current frame in linear memory
;;
;; @returns {(i32,i32)} - The offset and length of the next frame in linear memory
;;
(func (export "next") (param $offset i32) (param $cols i32) (param $rows i32) (result i32)
(return (local.get $offset))
)
)
Loading

0 comments on commit ba00596

Please sign in to comment.