Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Simple life

Name: Anonymous 2007-09-08 12:44 ID:fuIqtYYp

import qualified Data.Map as M

type Location = (Int,Int)

main = renderloop [(1,2),(2,3),(3,1),(3,2),(3,3)]
 where renderloop = mapM_ (\v -> render 20 v >> getLine) . iterate count

count :: [Location] -> [Location]
count locs = M.keys live ++ [v| v <-locs, M.member v still]
 where neighborCount = foldl foldFun M.empty . concatMap allNeighbors
       (live,still) = M.partition (== 3) . M.filter (`elem` [2,3]) . neighborCount $ locs

foldFun :: M.Map Location Int -> Location -> M.Map Location Int
foldFun map loc = M.insertWith (+) loc 1 map

allNeighbors :: Location -> [Location]
allNeighbors (x,y) = [(nx,ny) | nx <- [x+1,x-1,x], ny <- [y+1,y-1,y], (x,y) /= (nx,ny) ]

render size locs = mapM_ (putStrLn . makeRow locs size) (reverse [0..size])
makeRow locs wid r = map (\x -> if x `elem` inds then '#' else '.') [0..wid]
 where inds = [j | (p,j) <- locs, p == r]

:)

Name: Anonymous 2007-09-08 21:55 ID:B2apljO6


#!/usr/bin/perl6
use warnings;
use strict;

my $life = new life(20);

while(1)
{
  $life.display();
}

class life
{
  has Int          $.count;
  has Int          $.dimension;
  has Array of Int @.grid is dim ($.dimension, $.dimension);

  method CREATE(Int $dimension)
  {
    $.count = 0;
    $.dimension   = $dimension;

    loop (my $x = 0; $x < $dimenion; $x++)
    {
      loop (my $y = 0; $y < $dimension; $y++)
      {
        @.grid[$x][$y] = 0;
      }
    }
    @.grid[$dimension / 2 - 1][$dimension / 2] = 1;
    @.grid[$dimension / 2 - 1][$dimension / 2 + 1] = 1;
    @.grid[$dimension / 2][$dimension / 2] = 1;
    @.grid[$dimension / 2][$dimension / 2 - 1] = 1;
    @.grid[$dimension / 2 + 1][$dimension / 2] = 1;
  }

  method calculate() is private
  {
    my @newgrid;
    loop (my $x = 0; $x < .dimension; $x++)
    {
      loop (my $y = 0; $y < .dimension; $y++)
      {
        my $live = 0;
        for ($x - 1, $y - 1, $x, $y - 1, $x + 1, $y - 1, $x - 1, $y, $
+x + 1,
          $y, $x - 1, $y + 1, $x, $y + 1, $x + 1, $y + 1) -> ($nx, $ny
+)
        {
          next if 0 > $nx > .dimension || 0 > $ny > .dimension;
          $live++ if @.grid[$nx][$ny] == 1;
        }
        $newgrid[$x][$y] = given @.grid[$x][$y]
        {
          when 0   { 1 if $live == 3};
          when 1   { 1 if 1 <  $live < 4 }:
        } || 0;
      }
    }
    @.grid = @newgrid;
  }

  method display
  {
    loop (my $x = 0; $x < $.dimension; $x++)
    {
      loop (my $y = 0; $y < $.dimension; $y++)
      {
        print $.grid[$x][$y] ? '+' : '.';
      }
      print "\n";
    }
    print "Turn $(++$.count), press enter for next turn, ctl-c to quit
+';
    <STDIN>;

    .calculate();
  }
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List