about summary refs log blame commit diff stats
path: root/ts/bun/index.ts
blob: 6eae1c1ddd6004ccadcf3147f6d3bb455d06d593 (plain) (tree)
1
                       


























                                                                                            
                                                                        

          

 

                                                              
                                                 

                          
       


                       


              


                     








                       


                    






                       

  
                        
                     

                      
                   

                     
                  
type Grid = number[][];

export function printGrid(grid: Grid): void {
    grid.forEach(row => console.log(row.map(cell => cell ? '1' : '0').join(' ')));
    console.log('\n');
}

export function countNeighbors(grid: Grid, x: number, y: number): number {
    const neighborOffsets = [
        [-1, -1], [-1, 0], [-1, 1],
        [0, -1],           [0, 1],
        [1, -1],  [1, 0],  [1, 1]
    ];

    return neighborOffsets.reduce((count, [dx, dy]) => {
        const nx = x + dx;
        const ny = y + dy;
        if (nx >= 0 && ny >= 0 && nx < grid.length && ny < grid[0].length && grid[nx][ny]) {
            return count + 1;
        }
        return count;
    }, 0);
}

export function step(grid: Grid): Grid {
    return grid.map((row, x) =>
        row.map((cell, y) => {
            const neighbors = countNeighbors(grid, x, y);
            return neighbors === 3 || (neighbors === 2 && cell) ? 1 : 0;
        })
    );
}

export function simulate(initial: Grid, steps: number): void {
    let grid = initial;
    Array.from({ length: steps }).forEach(() => {
        printGrid(grid);
        grid = step(grid);
    });
}

const initial: Grid = [
    [0, 1, 0],
    [0, 1, 0],
    [0, 1, 0]
];

const flyer: Grid = [
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0],
    [0, 0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0]
];

const toad: Grid = [
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0],
    [0, 1, 0, 0, 1, 0],
    [0, 1, 0, 0, 1, 0],
    [0, 0, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0]
];

console.log('Initial:');
simulate(initial, 5);

console.log('Flyer:');
simulate(flyer, 5);

console.log('Toad:');
simulate(toad, 5);