import asyncnet, asyncdispatch

type
  Client = tuple
    socket: AsyncSocket
    name: string
    connected: bool

var clients {.threadvar.}: seq[Client]

proc sendOthers(client: Client, line: string) {.async.} =
  for c in clients:
    if c != client and c.connected:
      await c.socket.send(line & "\c\L")

proc processClient(socket: AsyncSocket) {.async.} =
  await socket.send("Please enter your name: ")
  var client: Client = (socket, await socket.recvLine(), true)

  clients.add(client)
  asyncCheck client.sendOthers("+++ " & client.name & " arrived +++")

  while true:
    let line = await client.socket.recvLine()
    if line == "":
      asyncCheck client.sendOthers("--- " & client.name & " leaves ---")
      client.connected = false
      return
    asyncCheck client.sendOthers(client.name & "> " & line)

proc serve() {.async.} =
  clients = @[]
  var server = newAsyncSocket()
  server.bindAddr(Port(4004))
  server.listen()

  while true:
    let socket = await server.accept()
    asyncCheck processClient(socket)

asyncCheck serve()
runForever()


use System.IO.Net;
use System.Concurrency;
use Collection;

bundle Default {
  class ChatServer {
    @clients : StringMap;
    @clients_mutex : ThreadMutex;

    New() {
      @clients := StringMap->New();
      @clients_mutex := ThreadMutex->New("clients_mutex");
    }

    method : ValidLogin(login_name : String, clients : StringMap) ~ Bool {
      if(clients->Has(login_name)) {
        return false;
      };

      return true;
    }

    function : Main(args : String[]) ~ Nil {
      chat_server := ChatServer->New();
      chat_server->Run();
    }

    method : public : Broadcast(message : String, sender : Client) ~ Nil {
      client_array : Vector;
      critical(@clients_mutex) {
        client_array := @clients->GetValues();
      };
      each(i : client_array) {
        client := client_array->Get(i)->As(Client);
        if(client <> sender) {
          client->Send(message);
        };
      };
    }

    method : public : Disconnect(sender : Client) ~ Nil {
      send_name := sender->GetName();
      Broadcast("+++ {$send_name} has left +++", sender);
      critical(@clients_mutex) {
        @clients->Remove(sender->GetName());
      };
      sender->Close();
    }

    method : public : Run() ~ Nil {
      server := TCPSocketServer->New(4661);
      if(server->Listen(5)) {
        while(true) {
          client_sock := server->Accept();
          critical(@clients_mutex) {
            client_sock->WriteString("login: ");
            login_name := client_sock->ReadString();
            if(ValidLogin(login_name, @clients)) {
              client := Client->New(login_name, client_sock, @self);
              @clients->Insert(client->GetName(), client);
              client->Execute(Nil);
            }
            else {
              client_sock->WriteString("+++ login in use +++\r\n");
              client_sock->Close();
            };
          };
        };
      };
      server->Close();
    }
  }

  class Client from Thread {
    @client_sock : TCPSocket;
    @server : ChatServer;

    New(login_name : String, client_sock : TCPSocket, server : ChatServer) {
      Parent(login_name);
      @client_sock := client_sock;
      @server := server;
    }

    method : public : Close() ~ Nil {
      @client_sock->Close();
    }

    method : public : Send(message : String) ~ Nil {
      if(@client_sock->IsOpen() & message->Size() > 0) {
        @client_sock->WriteString("{$message}\r\n");
      }
      else {
        @server->Disconnect(@self);
      };
    }

    method : public : Run(param : Base) ~ Nil {
      client_name := GetName();
      @server->Broadcast("+++ {$client_name} has arrived +++", @self);

      message := @client_sock->ReadString();
      while(message->Size() > 0 & message->Equals("/quit") = false) {
        @server->Broadcast("{$client_name}> {$message}", @self);
        message := @client_sock->ReadString();
      };
      @server->Disconnect(@self);
    }
  }
}


PROC Main()
  INT x,w=[220],h=[190]
  BYTE y,i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6

  Graphics(8+16)
  Color=1
  COLOR1=$0C
  COLOR2=$02

  x=Rand(w)
  y=Rand(h)
  DO
    i=Rand(3)
    IF i=0 THEN
      x==/2
      y==/2
    ELSEIF i=1 THEN
      x=w/2+(w/2-x)/2
      y=h-(h-y)/2
    ELSE
      x=w-(w-x)/2
      y=y/2
    FI
    Plot((320-w)/2+x,191-y)
  UNTIL CH#$FF
  OD
  CH=$FF
RETURN


/* Chaos game - JAMBO hopper */

#include <jambo.h>

#define LIMITE  50000

Main
  ancho = 700, alto = 150
  x=0,y=0,color=0
  vertice=0,
  c=0, Let( c := Utf8(Chr(219)))
  Let(x := Int(Rand(ancho)))
  Let(y := Int(Rand(alto)))

  mid ancho=0, Let( mid ancho:= Div(ancho,2))

  i=LIMITE
  Void(pixeles)
  Loop
      Ceil(Rand(3)), Move to (vertice)
      If( Eq(vertice,1) )
          Let(x := Div(x, 2))
          Let(y := Div(y, 2))
          color=9
      Else If( Eq(vertice,2))
          Let(x := Add( mid ancho, Div(Sub(mid ancho, x), 2) ) )
          Let(y := Sub( alto, Div( Sub(alto, y), 2 )))
          color=10
      Else
          Let(x := Sub(ancho,  Div( Sub(ancho, x), 2)))
          Let(y := Div(y, 2))
          color=4
      End If
      Set( Int(y), Int(x), color),Apndrow(pixeles)
      --i
  Back if (i) is not zero

  Set video graph(2)
  Canvas-term
  Cls
  i=1
  Iterator(++i, Leq(i,LIMITE), Colorfore([i,3]Get(pixeles)), \
                               Locate( [i,1]Get(pixeles), [i,2]Get(pixeles) ), Print(c) ); Prnl
  Pause
  Set video text
End


(define (timestamp) (syscall 201 "%c"))

(fork-server 'chat-room (lambda ()
(let this ((visitors #empty))
(let* ((envelope (wait-mail))
       (sender msg envelope))
   (case msg
      (['join who name]
         (let ((visitors (put visitors who name)))
            (for-each (lambda (who)
                  (print-to (car who) name " joined to as"))
               (ff->alist visitors))
            (this visitors)))
      (['talk message]
         (for-each (lambda (who)
               (print-to (car who) (cdr who) ": " message))
            (ff->alist visitors))
         (this visitors))
      (['part who]
         (for-each (lambda (who)
               (print-to (car who) (visitors (car who) "unknown") " leaved"))
            (ff->alist visitors))
         (let ((visitors (del visitors who)))
            (this visitors))))))))

(define (on-accept name fd)
(lambda ()
   (print "# " (timestamp) "> we got new visitor: " name)
   (mail 'chat-room ['join fd name])

   (let*((ss1 ms1 (clock)))
      (let loop ((str #null) (stream (force (port->bytestream fd))))
         (cond
            ((null? stream)
               #false)
            ((function? stream)
               (mail 'chat-room ['talk (list->string (reverse str))])
               (loop #null (force stream)))
            (else
               (loop (cons (car stream) str) (cdr stream)))))
      (syscall 3 fd)
      (let*((ss2 ms2 (clock)))
         (print "# " (timestamp) "> visitor leave us. It takes "  (+ (* (- ss2 ss1) 1000) (- ms2 ms1)) "ms.")))
   (mail 'chat-room ['part fd])
   ))

(define (run port)
(let ((socket (syscall 41)))
   ; bind
   (let loop ((port port))
      (if (not (syscall 49 socket port)) ; bind
         (loop (+ port 2))
         (print "Server binded to " port)))
   ; listen
   (if (not (syscall 50 socket)) ; listen
      (shutdown (print "Can't listen")))

   ; accept
   (let loop ()
      (if (syscall 23 socket) ; select
         (let ((fd (syscall 43 socket))) ; accept
            ;(print "\n# " (timestamp) ": new request from " (syscall 51 fd))
            (fork (on-accept (syscall 51 fd) fd))))
      (sleep 0)
      (loop))))

(run 8080)


#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>

#define pi M_PI

int main(){

	time_t t;
	double side, vertices[3][3],seedX,seedY,windowSide;
	int i,iter,choice;

	printf("Enter triangle side length : ");
	scanf("%lf",&side);

	printf("Enter number of iterations : ");
	scanf("%d",&iter);

	windowSide = 10 + 2*side;

	initwindow(windowSide,windowSide,"Sierpinski Chaos");

	for(i=0;i<3;i++){
		vertices[i][0] = windowSide/2 + side*cos(i*2*pi/3);
		vertices[i][1] = windowSide/2 + side*sin(i*2*pi/3);
		putpixel(vertices[i][0],vertices[i][1],15);
	}

	srand((unsigned)time(&t));

	seedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4);
	seedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4);

	putpixel(seedX,seedY,15);

	for(i=0;i<iter;i++){
		choice = rand()%3;

		seedX = (seedX + vertices[choice][0])/2;
		seedY = (seedY + vertices[choice][1])/2;

		putpixel(seedX,seedY,15);
	}

	getch();

	closegraph();

	return 0;
}


use 5.010;
use strict;
use warnings;

use threads;
use threads::shared;

use IO::Socket::INET;
use Time::HiRes qw(sleep ualarm);

my $HOST = "localhost";
my $PORT = 4004;

my @open;
my %users : shared;

sub broadcast {
    my ($id, $message) = @_;
    print "$message\n";
    foreach my $i (keys %users) {
        if ($i != $id) {
            $open[$i]->send("$message\n");
        }
    }
}

sub sign_in {
    my ($conn) = @_;

    state $id = 0;

    threads->new(
        sub {
            while (1) {
                $conn->send("Please enter your name: ");
                $conn->recv(my $name, 1024, 0);

                if (defined $name) {
                    $name = unpack('A*', $name);

                    if (exists $users{$name}) {
                        $conn->send("Name entered is already in use.\n");
                    }
                    elsif ($name ne '') {
                        $users{$id} = $name;
                        broadcast($id, "+++ $name arrived +++");
                        last;
                    }
                }
            }
        }
    );

    ++$id;
    push @open, $conn;
}

my $server = IO::Socket::INET->new(
                                   Timeout   => 0,
                                   LocalPort => $PORT,
                                   Proto     => "tcp",
                                   LocalAddr => $HOST,
                                   Blocking  => 0,
                                   Listen    => 1,
                                   Reuse     => 1,
                                  );

local $| = 1;
print "Listening on $HOST:$PORT\n";

while (1) {
    my ($conn) = $server->accept;

    if (defined($conn)) {
        sign_in($conn);
    }

    foreach my $i (keys %users) {

        my $conn = $open[$i];
        my $message;

        eval {
            local $SIG{ALRM} = sub { die "alarm\n" };
            ualarm(500);
            $conn->recv($message, 1024, 0);
            ualarm(0);
        };

        if ([email protected] eq "alarm\n") {
            next;
        }

        if (defined($message)) {
            if ($message ne '') {
                $message = unpack('A*', $message);
                broadcast($i, "$users{$i}> $message");
            }
            else {
                broadcast($i, "--- $users{$i} leaves ---");
                delete $users{$i};
                undef $open[$i];
            }
        }
    }

    sleep(0.1);
}


using System.Diagnostics;
using System.Drawing;

namespace RosettaChaosGame
{
    class Program
    {
        static void Main(string[] args)
        {
            var bm = new Bitmap(600, 600);

            var referencePoints = new Point[] {
                new Point(0, 600),
                new Point(600, 600),
                new Point(300, 81)
            };
            var r = new System.Random();
            var p = new Point(r.Next(600), r.Next(600));
            for (int count = 0; count < 10000; count++)
            {
                bm.SetPixel(p.X, p.Y, Color.Magenta);
                int i = r.Next(3);
                p.X = (p.X + referencePoints[i].X) / 2;
                p.Y = (p.Y + referencePoints[i].Y) / 2;
            }
            const string filename = "Chaos Game.png";
            bm.Save(filename);
            Process.Start(filename);
        }
    }
}


--
-- demo\rosetta\ChatServer.exw
-- ========================
--
-- translation of (qchat) chatServ.exw
--
-- Run this first, then ChatClient.exw, see also IRC_Gateway.exw
--
-- Note that I've only got a 32-bit windows eulibnet.dll, but it should not
-- be dificult to use a "real" libnet.dll/so, or something a little newer.
--
without js
include pGUI.e
constant dl = `Download rosetta\eulibnet\ from http://phix.x10.mx/pmwiki/pmwiki.php?n=Main.Eulibnet`
assert(get_file_type("eulibnet")=FILETYPE_DIRECTORY,dl)
include eulibnet/eulibnet.ew
Ihandle log_list, log_window, statusbar, timer

atom listconn
constant IP = "127.0.0.1",
         port = "29029",
         IPaddress = IP & ":" & port
constant MAX_MSG = 550
sequence connections = {},
         nicknames = {}

constant max_log_len = 300

procedure log_to_window(string txt)
    integer count = to_number(IupGetAttribute(log_list,"COUNT"))
    if count > max_log_len then
        for t=1 to count-max_log_len do
            IupSetAttribute(log_list,"REMOVEITEM","1")
        end for
    end if
    IupSetAttribute(log_list,"APPENDITEM",txt)
    IupSetAttribute(log_list,"TOPITEM",IupGetAttribute(log_list,"COUNT"))
    IupUpdate(log_list)
end procedure

procedure message(string msg, sequence args={})
    if length(args) then msg = sprintf(msg,args) end if
    IupSetStrAttribute(statusbar, "TITLE", msg)
    log_to_window(msg)
end procedure

procedure shutDown()
    message("Shutting down euLibnet...")
    for i = 1 to length(connections) do
        if net_closeconn(connections[i]) then crash("Error closing connection!") end if
    end for
    if net_closeconn(listconn) then crash("Error closing listconn!") end if
    if net_shutdown() then crash("Error shutting down euLibnet!") end if
end procedure

procedure sendToAll(string msg)
    -- Send msg to all clients
    for i=1 to length(connections) do
        atom ci = connections[i]
        message("Sending to connection %d (%s)",{ci,nicknames[i]})
        if net_send_rdm(ci, msg) then
            message("Error sending to connection %d",{ci})
        end if
    end for
end procedure

procedure mainWindow_onOpen()
    message("Initializing euLibnet...")
    if net_init() then crash("Error initializing euLibnet!") end if
    message("done.")
    message("Initializing driver...")
    if net_initdriver(NET_DRIVER_WSOCK_WIN) != 1 then
        crash("Error initializing WinSock driver!")
    end if
    message("done.")
    message("Opening port " & IPaddress & "...")
    listconn = net_openconn(NET_DRIVER_WSOCK_WIN, IPaddress)
    if listconn = NULL then
        crash("Couldn't open connection (server already running?)")
    end if
    message("done.")
    if net_listen(listconn) then
        crash("Error trying to listen to port")
    end if
    message("Listening on port " & IPaddress)
end procedure

function timer_cb(Ihandle /*timer*/)
    integer conn = net_poll_listen(listconn)
    if conn != NULL then
         connections = append(connections, conn)
         nicknames = append(nicknames, "")
         message("New connection open from " & net_getpeer(conn))
    end if

    -- Check for messages from clients
    for i = 1 to length(connections) do
        integer ci = connections[i]
        if net_query_rdm(ci) > 0 then
            string ni = nicknames[i]
            --Get the message
            sequence msg = net_receive_rdm(ci, MAX_MSG)
            message("received msg \"%s\" of length %d from %d aka %s",{msg[2],msg[1],ci,ni})
            if msg[1] < 0 then --Exit on error
                {} = net_ignore_rdm(ci)
                sendToAll("Server error: some data may be lost")
                exit
            end if

            msg = msg[2]
            if length(msg) > 4 and equal(msg[1..3], "/n:") then
                if find(msg[4..length(msg)], nicknames) then
                    if net_send_rdm(ci, "/nt") then
                        message("Error sending to %d",{ci})
                    end if
                else
                    string prevname = ni
                    ni = msg[4..length(msg)]
                    nicknames[i] = ni
                    if length(prevname) = 0 then
                        sendToAll("/j:" & ni & " has joined")
                        -- send fake "has joined"s to the new joiner,
                        -- so that it can build a full members list (see allj)
                        for n=1 to length(nicknames) do
                            if n!=i then
                                msg = "/j:" & nicknames[n] & " has joined"
                                if net_send_rdm(ci, msg) then
                                    message("Error sending to connection %d",{ci})
                                    exit
                                end if
                            end if
                        end for
                    else
                        sendToAll("/c:" & prevname & " has changed name to " & ni)
                    end if
                end if
            elsif equal(msg, "/d") then
                msg = "/l:"& ni & " has left"
                message(msg)
                nicknames[i..i] = {}
                connections[i..i] = {}
                sendToAll(msg)
                exit
            -- Aside: bunch of popup and file transfer stuff was here in qchat.exw,
            --        all ripped out in the name of keeping this short and sweet.
            else
                sendToAll(ni & ": " & msg) -- (Add nickname to message)
            end if
        end if
    end for
    return IUP_IGNORE
end function

function close_cb(Ihandle /*ih*/)
    shutDown()
    return IUP_DEFAULT
end function

IupOpen()
log_list = IupList("EXPAND=YES, CANFOCUS=NO, MULTIPLE=YES")
statusbar = IupLabel("Loading...","EXPAND=HORIZONTAL")
log_window = IupDialog(IupVbox({log_list,statusbar}),
            `TITLE="Chat Server", RASTERSIZE=400x400`)
IupSetCallback(log_window,"CLOSE_CB",Icallback("close_cb"))
IupShow(log_window)
mainWindow_onOpen()
timer = IupTimer(Icallback("timer_cb"), 500)
IupMainLoop()
IupClose()


#include <windows.h>
#include <ctime>
#include <string>
#include <iostream>

const int BMP_SIZE = 600;

class myBitmap {
public:
    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
    ~myBitmap() {
        DeleteObject( pen ); DeleteObject( brush );
        DeleteDC( hdc ); DeleteObject( bmp );
    }
    bool create( int w, int h ) {
        BITMAPINFO bi;
        ZeroMemory( &bi, sizeof( bi ) );
        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );
        bi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;
        bi.bmiHeader.biCompression = BI_RGB;
        bi.bmiHeader.biPlanes      = 1;
        bi.bmiHeader.biWidth       =  w;
        bi.bmiHeader.biHeight      = -h;

        HDC dc = GetDC( GetConsoleWindow() );
        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
        if( !bmp ) return false;

        hdc = CreateCompatibleDC( dc );
        SelectObject( hdc, bmp );
        ReleaseDC( GetConsoleWindow(), dc );

        width = w; height = h;
        return true;
    }
    void clear( BYTE clr = 0 ) {
        memset( pBits, clr, width * height * sizeof( DWORD ) );
    }
    void setBrushColor( DWORD bClr ) {
        if( brush ) DeleteObject( brush );
        brush = CreateSolidBrush( bClr );
        SelectObject( hdc, brush );
    }
    void setPenColor( DWORD c ) {
        clr = c; createPen();
    }
    void setPenWidth( int w ) {
        wid = w; createPen();
    }
    void saveBitmap( std::string path ) {
        BITMAPFILEHEADER fileheader;
        BITMAPINFO       infoheader;
        BITMAP           bitmap;
        DWORD            wb;

        GetObject( bmp, sizeof( bitmap ), &bitmap );
        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];

        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

        infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
        infoheader.bmiHeader.biCompression = BI_RGB;
        infoheader.bmiHeader.biPlanes = 1;
        infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
        infoheader.bmiHeader.biHeight = bitmap.bmHeight;
        infoheader.bmiHeader.biWidth = bitmap.bmWidth;
        infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

        fileheader.bfType    = 0x4D42;
        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
        CloseHandle( file );

        delete [] dwpBits;
    }
    HDC getDC() const     { return hdc; }
    int getWidth() const  { return width; }
    int getHeight() const { return height; }
private:
    void createPen() {
        if( pen ) DeleteObject( pen );
        pen = CreatePen( PS_SOLID, wid, clr );
        SelectObject( hdc, pen );
    }
    HBITMAP bmp; HDC    hdc;
    HPEN    pen; HBRUSH brush;
    void    *pBits; int    width, height, wid;
    DWORD    clr;
};
class chaos {
public:
    void start() {
        POINT org;
        fillPts(); initialPoint( org ); initColors();
        int cnt = 0, i;
        bmp.create( BMP_SIZE, BMP_SIZE );
        bmp.clear( 255 );

        while( cnt++ < 1000000 ) {
            switch( rand() % 6 ) {
                case 0: case 3: i = 0; break;
                case 1: case 5: i = 1; break;
                case 2: case 4: i = 2;
            }
            setPoint( org, myPoints[i], i );
        }
        // --- edit this path --- //
        bmp.saveBitmap( "F:/st.bmp" );
    }
private:
    void setPoint( POINT &o, POINT v, int i ) {
        POINT z;
        o.x = ( o.x + v.x ) >> 1; o.y = ( o.y + v.y ) >> 1;
        SetPixel( bmp.getDC(), o.x, o.y, colors[i] );
    }
    void fillPts() {
        int a = BMP_SIZE - 1;
        myPoints[0].x = BMP_SIZE >> 1; myPoints[0].y = 0;
        myPoints[1].x = 0; myPoints[1].y = myPoints[2].x = myPoints[2].y = a;
    }
    void initialPoint( POINT& p ) {
        p.x = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );
        p.y = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );
    }
    void initColors() {
        colors[0] = RGB( 255, 0, 0 );
        colors[1] = RGB( 0, 255, 0 );
        colors[2] = RGB( 0, 0, 255 );
    }

    myBitmap bmp;
    POINT myPoints[3];
    COLORREF colors[3];
};
int main( int argc, char* argv[] ) {
    srand( ( unsigned )time( 0 ) );
    chaos c; c.start();
    return 0;
}


#!/usr/bin/picolisp /usr/lib/picolisp/lib.l

(de chat Lst
   (out *Sock
      (mapc prin Lst)
      (prinl) ) )

(setq *Port (port 4004))

(loop
   (setq *Sock (listen *Port))
   (NIL (fork) (close *Port))
   (close *Sock) )

(out *Sock
   (prin "Please enter your name: ")
   (flush) )
(in *Sock (setq *Name (line T)))

(tell 'chat "+++ " *Name " arrived +++")

(task *Sock
   (in @
      (ifn (eof)
         (tell 'chat *Name "> " (line T))
         (tell 'chat "--- " *Name " left ---")
         (bye) ) ) )
(wait)


:- initialization chat_server(5000).

chat_server(Port) :-
      tcp_socket(Socket),
      tcp_bind(Socket, Port),
      tcp_listen(Socket, 5),
      tcp_open_socket(Socket, AcceptFd, _),
      dispatch(AcceptFd).

dispatch(AcceptFd) :-
        tcp_accept(AcceptFd, Socket, _),
        thread_create(process_client(Socket, _), _, [detached(true)]),
        dispatch(AcceptFd).

process_client(Socket, _) :-
        setup_call_cleanup(
            tcp_open_socket(Socket, Str),
            handle_connection(Str),
            close(Str)).

% a connection was made, get the username and add the streams so the
% client can be broadcast to.
handle_connection(Str) :-
      send_msg(Str, msg_welcome, []),
      repeat,
      send_msg(Str, msg_username, []),
      read_line_to_string(Str, Name),
      connect_user(Name, Str), !.

% connections are stored here
:- dynamic(connected/2).

connect_user(Name, Str) :-
      connected(Name, _),
      send_msg(Str, msg_username_taken, []),
      fail.
connect_user(Name, Str) :-
      \+ connected(Name, _),
      send_msg(Str, msg_welcome_name, Name),

      % make sure that the connection is removed when the client leaves.
      setup_call_cleanup(
          assert(connected(Name, Str)),
          (
              broadcast(Name, msg_joined, Name),
              chat_loop(Name, Str), !,
              broadcast(Name, msg_left, Name)
          ),
          retractall(connected(Name, _))
      ).

% wait for a line to be sent then broadcast to the rest of the clients
% finish this goal when the client disconnects (end of stream)
chat_loop(Name, Str) :-
      read_line_to_string(Str, S),
      dif(S, end_of_file),
      broadcast(Name, msg_by_user, [Name, S]),
      chat_loop(Name, Str).
chat_loop(_, Str) :- at_end_of_stream(Str).

% send a message to all connected clients except Name (the sender)
broadcast(Name, Msg, Params) :-
    forall(
        (connected(N, Str), dif(N, Name)),
        (send_msg(Str, Msg, Params), send_msg(Str, msg_new_line, []))
    ).

send_msg(St, MsgConst, Params) :-
      call(MsgConst, Msg),
      format(St, Msg, Params),
      flush_output(St).

% constants for the various message types that are sent
msg_welcome('Welcome to Chatalot\n\r').
msg_username('Please enter your nickname: ').
msg_welcome_name('Welcome ~p\n\r').
msg_joined(' -- "~w" has joined the chat --').
msg_left(' -- "~w" has left the chat. --').
msg_username_taken('That username is already taken, choose another\n\r').
msg_new_line('\n\r').
msg_by_user('~w> ~w').


(defpackage #:chaos
  (:use #:cl
        #:opticl))

(in-package #:chaos)

(defparameter *image-size* 600)
(defparameter *margin* 50)
(defparameter *edge-size* (- *image-size* *margin* *margin*))
(defparameter *iterations* 1000000)

(defun chaos ()
  (let ((image (make-8-bit-rgb-image *image-size* *image-size* :initial-element 255))
        (a (list (- *image-size* *margin*) *margin*))
        (b (list (- *image-size* *margin*) (- *image-size* *margin*)))
        (c (list (- *image-size* *margin* (round (* (tan (/ pi 3)) *edge-size*) 2))
                 (round *image-size* 2)))
        (point (list (+ (random *edge-size*) *margin*)
                     (+ (random *edge-size*) *margin*))))
    (dotimes (i *iterations*)
      (let ((ref (ecase (random 3)
                   (0 a)
                   (1 b)
                   (2 c))))
        (setf point (list (round (+ (first  point) (first  ref)) 2)
                          (round (+ (second point) (second ref)) 2))))
      (setf (pixel image (first point) (second point))
            (values 255 0 0)))
    (write-png-file "chaos.png" image)))


#!/usr/bin/env python

import socket
import thread
import time

HOST = ""
PORT = 4004

def accept(conn):
    """
    Call the inner func in a thread so as not to block. Wait for a
    name to be entered from the given connection. Once a name is
    entered, set the connection to non-blocking and add the user to
    the users dict.
    """
    def threaded():
        while True:
            conn.send("Please enter your name: ")
            try:
                name = conn.recv(1024).strip()
            except socket.error:
                continue
            if name in users:
                conn.send("Name entered is already in use.\n")
            elif name:
                conn.setblocking(False)
                users[name] = conn
                broadcast(name, "+++ %s arrived +++" % name)
                break
    thread.start_new_thread(threaded, ())

def broadcast(name, message):
    """
    Send a message to all users from the given name.
    """
    print message
    for to_name, conn in users.items():
        if to_name != name:
            try:
                conn.send(message + "\n")
            except socket.error:
                pass

# Set up the server socket.
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking(False)
server.bind((HOST, PORT))
server.listen(1)
print "Listening on %s" % ("%s:%s" % server.getsockname())

# Main event loop.
users = {}
while True:
    try:
        # Accept new connections.
        while True:
            try:
                conn, addr = server.accept()
            except socket.error:
                break
            accept(conn)
        # Read from connections.
        for name, conn in users.items():
            try:
                message = conn.recv(1024)
            except socket.error:
                continue
            if not message:
                # Empty string is given on disconnect.
                del users[name]
                broadcast(name, "--- %s leaves ---" % name)
            else:
                broadcast(name, "%s> %s" % (name, message.strip()))
        time.sleep(.1)
    except (SystemExit, KeyboardInterrupt):
        break


unit main;

interface

uses
  Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls,
  System.Generics.Collections;

type
  TColoredPoint = record
    P: TPoint;
    Index: Integer;
    constructor Create(PX, PY: Integer; ColorIndex: Integer);
  end;

  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormPaint(Sender: TObject);
  private
    Buffer: TBitmap;
    Points: array[0..2] of TPoint;
    Stack: TStack<TColoredPoint>;
    Tick: TTimer;
    procedure Run(Sender: TObject);
    procedure AddPoint;
    function HalfWayPoint(a: TColoredPoint; b: TPoint; index: Integer): TColoredPoint;
    { Private declarations }
  public
    { Public declarations }
  end;

const
  Colors: array[0..2] of Tcolor = (clRed, clGreen, clBlue);

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TColoredPoint }

constructor TColoredPoint.Create(PX, PY: Integer; ColorIndex: Integer);
begin
  self.P := Tpoint.Create(PX, PY);
  self.Index := ColorIndex;
end;

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  Buffer := TBitmap.Create;
  Stack := TStack<TColoredPoint>.Create;
  Tick := TTimer.Create(nil);
  Caption := 'Chaos Game';

  DoubleBuffered := True;

  ClientHeight := 640;
  ClientWidth := 640;
  var margin := 60;
  var size := ClientWidth - 2 * margin;

  Points[0] := TPoint.Create(ClientWidth div 2, margin);
  Points[1] := TPoint.Create(margin, size);
  Points[2] := TPoint.Create(margin + size, size);

  Stack.Push(TColoredPoint.Create(-1, -1, Colors[0]));

  Tick.Interval := 10;
  Tick.OnTimer := Run;
end;

function TForm1.HalfWayPoint(a: TColoredPoint; b: TPoint; index: Integer): TColoredPoint;
begin
  Result := TColoredPoint.Create((a.p.X + b.x) div 2, (a.p.y + b.y) div 2, index);
end;

procedure TForm1.AddPoint;
begin
  var colorIndex := Random(3);
  var p1 := Stack.Peek;
  var p2 := Points[colorIndex];
  Stack.Push(HalfWayPoint(p1, p2, colorIndex));
end;

procedure TForm1.Run(Sender: TObject);
begin
  if Stack.Count < 50000 then
  begin
    for var i := 0 to 999 do
      AddPoint;
    Invalidate;
  end;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Tick.Free;
  Buffer.Free;
  Stack.Free;
end;

procedure TForm1.FormPaint(Sender: TObject);
begin
  for var p in Stack do
  begin
    with Canvas do
    begin
      Pen.Color := Colors[p.Index];
      Brush.Color := Colors[p.Index];
      Brush.Style := bsSolid;
      Ellipse(p.p.X - 1, p.p.y - 1, p.p.X + 1, p.p.y + 1);
    end;
  end;
end;
end.


F CastOut(Base, Start, End)
   V ran = (0 .< Base - 1).filter(y -> y % (@Base - 1) == (y * y) % (@Base - 1))
   V (x, y) = divmod(Start, Base - 1)
   [Int] r
   L
      L(n) ran
         V k = (Base - 1) * x + n
         I k < Start
            L.continue
         I k > End
            R r
         r.append(k)
      x++

L(v) CastOut(Base' 16, Start' 1, End' 255)
   print(v, end' ‘ ’)
print()
L(v) CastOut(Base' 10, Start' 1, End' 99)
   print(v, end' ‘ ’)
print()
L(v) CastOut(Base' 17, Start' 1, End' 288)
   print(v, end' ‘ ’)
print()


chat_loop <- function(server, sockets, delay = 0.5) {
    repeat {
        Sys.sleep(delay) # Saves CPU resources

        ## Exhausts queue each iteration
        while (in_queue(server))
            sockets <- new_socket_entry(server, sockets)

        ## Update which sockets have sent messages
        sockets <- check_messages(sockets)

        ## No sockets, nothing to do
        if (nrow(sockets) == 0)
            next

        ## No new messages, nothing to do
        if (all(!sockets$message_ready))
            next

        sockets <- read_messages(sockets) # Messages are stored until sent
        sockets <- drop_dead(sockets) # Dead = ready to read, but no data

        ## In case all sockets were dropped
        if (nrow(sockets) == 0)
            next

        sockets <- update_nicknames(sockets)
        sockets <- send_messages(sockets) # Only to users with nicknames
    }
}

check_messages <- function(sockets) {
    if (nrow(sockets) != 0)
        sockets$message_ready <- socketSelect(sockets$conn, timeout = 0)

    sockets
}

drop_dead <- function(sockets) {
    lapply(with(sockets, conn[!alive]), close)
    dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive])
    sockets <- sockets[sockets$alive, ]

    if (length(dropped) != 0) {
        send_named(sockets, paste0(dropped, " has disconnected."))
    }

    sockets
}

in_queue <- function(server) socketSelect(list(server), timeout = 0)
is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == ""
message_exists <- function(sockets) !is.na(sockets$message)

new_row <- function(df) {
    df[nrow(df) + 1, ] <- NA
    df
}

new_socket_entry <- function(server, sockets) {
    sockets <- new_row(sockets)
    n <- nrow(sockets)
    within(sockets, {
        conn[[n]] <- new_user(server)
        alive[n] <- TRUE
        message_ready[n] <- FALSE
    })
}

new_user <- function(server) {
    conn <- socketAccept(server)
    writeLines("Hello! Please enter a nickname.", conn)
    conn
}

nickname_exists <- function(sockets) !is.na(sockets$nickname)

read_messages <- function(sockets) {
    if (all(!sockets$message_ready))
        return(sockets)

    msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1)
    empty_msgs <- sapply(msgs, identical, character(0))
    sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE)
    msgs <- unlist(ifelse(empty_msgs, NA, msgs))
    within(sockets, message[message_ready] <- msgs)
}

send_messages <- function(sockets) {
    named_message <- message_exists(sockets) & nickname_exists(sockets)

    if (all(!named_message))
        return(sockets)

    rows <- which(named_message)
    socksub <- sockets[rows, ]
    time <- format(Sys.time(), "[%H:%M:%S] ")
    with(socksub, send_named(sockets, paste0(time, nickname, ": ", message)))
    within(sockets, message[rows] <- NA)
}

send_named <- function(sockets, msg) {
    has_nickname <- nickname_exists(sockets)
    invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg))
}

start_chat_server <- function(port = 50525) {
    server <- serverSocket(port) # Start listening
    on.exit(closeAllConnections()) # Cleanup connections

    ## All socket data is stored and passed using this object
    sockets <- data.frame(conn = I(list()), nickname = character(),
                          message = character(), alive = logical(),
                          message_ready = logical())

    ## Main event loop
    chat_loop(server, sockets)
}

update_nicknames <- function(sockets) {
    sent_nickname <- message_exists(sockets) & !nickname_exists(sockets)
    nickname_valid <- is_valid_name(sockets$message)

    if (all(!sent_nickname))
        return(sockets)

    is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) &
                              !is.na(message))
    sent_ok <- sent_nickname & nickname_valid & !is_taken
    sockets <- within(sockets, {
        nickname[sent_ok] <- message[sent_ok]
        message[sent_nickname] <- NA
        lapply(conn[sent_nickname & !nickname_valid], writeLines,
               text = "Alphanumeric characters only. Try again.")
        lapply(conn[is_taken], writeLines,
               text = "Name already taken. Try again.")
    })

    if (any(sent_ok))
        send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected."))

    sockets
}

start_chat_server()


#lang racket

(define outs (list (current-output-port)))
(define ((tell-all who o) line)
  (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c)))

(define ((client i o))
  (define nick (begin (display "Nick: " o) (read-line i)))
  (define tell (tell-all nick o))
  (let loop ([line "(joined)"])
    (if (eof-object? line)
      (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o))
      (begin (tell line) (loop (read-line i))))))

(define (chat-server listener)
  (define-values [i o] (tcp-accept listener))
  (for ([p (list i o)]) (file-stream-buffer-mode p 'none))
  (thread (client i o)) (set! outs (cons o outs)) (chat-server listener))

(void (thread (λ() (chat-server (tcp-listen 12321)))))
((client (current-input-port) (current-output-port)))


react {
    my %connections;

    whenever IO::Socket::Async.listen('localhost', 4004) -> $conn {
        my $name;

        $conn.print: "Please enter your name: ";

        whenever $conn.Supply.lines -> $message {
            if !$name {
                if %connections{$message} {
                    $conn.print: "Name already taken, choose another one: ";
                }
                else {
                    $name = $message;
                    %connections{$name} = $conn;
                    broadcast "+++ %s arrived +++", $name;
                }
            }
            else {
                broadcast "%s> %s", $name, $message;
            }
            LAST {
                broadcast "--- %s left ---", $name;
                %connections{$name}:delete;
                $conn.close ;
            }
            QUIT {
                 default {
                     say "oh no, $_";
                }
            }
        }
    }

    sub broadcast ($format, $from, *@message) {
        my $text = sprintf $format, $from, |@message;
        say $text;
        for %connections.kv -> $name, $conn {
            $conn.print: "$text\n" if $name ne $from;
        }
    }
}


; Chaos game

(defun make-array (size)
  "Create an empty array with size*size elements."
  (setq m-array (make-vector size nil))
  (dotimes (i size)
    (setf (aref m-array i) (make-vector size 0)))
  m-array)

(defun chaos-next (p)
  "Return the next coordinates."
  (let* ((points (list (cons 1 0) (cons -1 0) (cons 0 (sqrt 3))))
 	 (v (elt points (random 3)))
         (x (car p))
         (y (cdr p))
         (x2 (car v))
         (y2 (cdr v)))
      (setq nx (/ (+ x x2) 2.0))
      (setq ny (/ (+ y y2) 2.0))
      (cons nx ny)))

(defun chaos-lines (arr size)
  "Turn array into a string for XPM conversion."
  (setq all "")
  (dotimes (y size)
    (setq line "")
    (dotimes (x size)
      (setq line (concat line (if (= (elt (elt arr y) x) 1) "*" "."))))
    (setq all (concat all "\"" line "\",\n")))
  all)

(defun chaos-show (arr size)
  "Convert size*size array to XPM image and show it."
  (insert-image (create-image (concat (format "/* XPM */
static char * chaos[] = {
\"%i %i 2 1\",
\".      c #000000\",
\"*      c #00ff00\"," size size)
    (chaos-lines arr size) "};") 'xpm t)))

(defun chaos (size scale max-iter)
  "Play the chaos game."
  (let ((arr (make-array size))
        (p (cons 0 0)))
    (dotimes (it max-iter)
      (setq p (chaos-next p))
      (setq x (round (+ (/ size 2) (* scale (car p)))))
      (setq y (round (+ (- size 10) (* -1 scale (cdr p)))))
      (setf (elt (elt arr y) x) 1))
    (chaos-show arr size)))

(chaos 400 180 50000)


*      Casting out nines         08/02/2017
CASTOUT CSECT
       USING  CASTOUT,R13        base register
       B      72(R15)            skip savearea
       DC     17F'0'             savearea
       STM    R14,R12,12(R13)    prolog
       ST     R13,4(R15)         " <-
       ST     R15,8(R13)         " ->
       LR     R13,R15            " addressability
       L      R1,LOW             low
       XDECO  R1,XDEC            edit low
       MVC    PGT+4(4),XDEC+8    output low
       L      R1,HIGH            high
       XDECO  R1,XDEC            edit high
       MVC    PGT+12(4),XDEC+8   output low
       L      R1,BASE            base
       XDECO  R1,XDEC            edit base
       MVC    PGT+24(4),XDEC+8   output base
       XPRNT  PGT,L'PGT          print buffer
       L      R2,BASE            base
       BCTR   R2,0               -1
       ST     R2,RM              rm=base-1
       LA     R8,PG              ipg=0
       SR     R7,R7              j=0
       L      R6,LOW             i=low
       DO WHILE=(C,R6,LE,HIGH)   do i=low to high
         LR     R5,R6              i
         SR     R4,R4              clear for div
         D      R4,RM              /rm
         LR     R2,R4              r2=i mod rm
         LR     R5,R6              i
         MR     R4,R6              i*i
         SR     R4,R4              clear for div
         D      R4,RM              /rm
         IF CR,R2,EQ,R4 THEN       if (i//rm)=(i*i//rm) then
           LA     R7,1(R7)           j=j+1
           XDECO  R6,XDEC            edit i
           MVC    0(4,R8),XDEC+8     output i
           LA     R8,4(R8)           ipg=ipg+4
           IF C,R7,EQ,=F'20' THEN    if j=20 then
             XPRNT  PG,L'PG            print buffer
             LA     R8,PG              ipg=0
             SR     R7,R7              j=0
             MVC    PG,=CL80' '        clear buffer
           ENDIF  ,                  end if
         ENDIF  ,                  end if
         LA     R6,1(R6)           i=i+1
       ENDDO  ,                  end do i
       IF LTR,R7,NE,R7 THEN      if j<>0  then
         XPRNT  PG,L'PG            print buffer
       ENDIF  ,                  end if
       L      R13,4(0,R13)       epilog
       LM     R14,R12,12(R13)    " restore
       XR     R15,R15            " rc=0
       BR     R14                exit
LOW    DC     F'1'               low
HIGH   DC     F'500'             high
BASE   DC     F'10'              base
RM     DS     F                  rm
PGT    DC     CL80'for  ... to  ...    base ...'    buffer
PG     DC     CL80' '                               buffer
XDEC   DS     CL12               temp for xdeco
       YREGS
       END    CASTOUT


INT FUNC Power(INT a,b)
  INT i,res

  res=1
  FOR i=1 TO b
  DO
    res==*a
  OD
RETURN (res)

PROC Main()
  DEFINE BASE="10"
  DEFINE N="2"
  INT i,max,count,total,perc

  max=Power(BASE,N)
  count=0 total=0
  FOR i=1 TO max
  DO
    total==+1
    IF i MOD (BASE-1)=(i*i) MOD (BASE-1) THEN
      count==+1
      PrintI(i) Put(32)
    FI
  OD
  perc=100-100*count/total
  PrintF("%E%ETrying %I numbers instead of %I numbers saves %I%%",count,total,perc)
RETURN


BEGIN # casting out nines - translated from the Action! sample #
    INT base   = 10;
    INT n      =  2;
    INT count :=  0;
    INT total :=  0;
    FOR i TO base ^ n DO
        total +:= 1;
        IF i MOD ( base - 1 ) = ( i * i ) MOD ( base - 1 ) THEN
            count +:= 1;
            print( ( whole( i, 0 ), " " ) )
        FI
    OD;
    print( ( newline, newline, "Trying ", whole( count, 0 )
           , " numbers instead of ", whole( total, 0 )
           , " numbers saves ", fixed( 100 - ( ( 100 * count ) / total ), -6, 2 )
           , "%", newline
           )
         )
END


N: 2
base: 10
c1: 0
c2: 0

loop 1..(base^N)-1 'k [
    c1: c1 + 1

    if (k%base-1)= (k*k)%base-1 [
        c2: c2 + 1
        prints ~"|k| "
    ]
]

print ""
print ["Trying" c2 "numbers instead of" c1 "numbers saves" 100.0 - 100.0*c2//c1 "%"]


require 'gserver'

class ChatServer < GServer
  def initialize *args
    super

    #Keep a list for broadcasting messages
    @chatters = []

    #We'll need this for thread safety
    @mutex = Mutex.new
  end

  #Send message out to everyone but sender
  def broadcast message, sender = nil
    #Need to use \r\n for our Windows friends
    message = message.strip << "\r\n"

    #Mutex for safety - GServer uses threads
    @mutex.synchronize do
      @chatters.each do |chatter|
        begin
          chatter.print message unless chatter == sender
        rescue
          @chatters.delete chatter
        end
      end
    end
  end

  #Handle each connection
  def serve io
    io.print 'Name: '
    name = io.gets

    #They might disconnect
    return if name.nil?

    name.strip!

    broadcast "--+ #{name} has joined +--"

    #Add to our list of connections
    @mutex.synchronize do
      @chatters << io
    end

    #Get and broadcast input until connection returns nil
    loop do
      message = io.gets

      if message
        broadcast "#{name}> #{message}", io
      else
        break
      end
    end

    broadcast "--+ #{name} has left +--"
  end
end

#Start up the server on port 7000
#Accept connections for any IP address
#Allow up to 100 connections
#Send information to stderr
#Turn on informational messages
ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join


use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, RwLock};
use std::thread;

type Username = String;

/// Sends a message to all clients except the sending client.
fn broadcast_message(
    user: &str,
    clients: &mut HashMap<String, TcpStream>,
    message: &str,
) -> io::Result<()> {
    for (client, stream) in clients.iter_mut() {
        if client != user {
            writeln!(stream, "{}", message)?;
        }
    }

    Ok(())
}

fn chat_loop(listener: &TcpListener) -> io::Result<()> {
    let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> =
        Arc::new(RwLock::new(HashMap::new()));

    println!("Accepting connections on {}", listener.local_addr()?.port());

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                let client_clients = Arc::clone(&local_clients);
                thread::spawn(move || -> io::Result<()> {
                    let mut reader = BufReader::new(stream.try_clone()?);
                    let mut writer = stream;

                    let mut name = String::new();
                    loop {
                        write!(writer, "Please enter a username: ")?;
                        reader.read_line(&mut name)?;
                        name = name.trim().to_owned();

                        let clients = client_clients.read().unwrap();
                        if !clients.contains_key(&name) {
                            writeln!(writer, "Welcome, {}!", &name)?;
                            break;
                        }

                        writeln!(writer, "That username is taken.")?;
                        name.clear();
                    }

                    {
                        let mut clients = client_clients.write().unwrap();
                        clients.insert(name.clone(), writer);
                        broadcast_message(
                            &name,
                            &mut *clients,
                            &format!("{} has joined the chat room.", &name),
                        )?;
                    }

                    for line in reader.lines() {
                        let mut clients = client_clients.write().unwrap();
                        broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?;
                    }

                    {
                        let mut clients = client_clients.write().unwrap();
                        clients.remove(&name);
                        broadcast_message(
                            &name,
                            &mut *clients,
                            &format!("{} has left the chat room.", &name),
                        )?;
                    }

                    Ok(())
                });
            }
            Err(e) => {
                println!("Connection failed: {}", e);
            }
        }
    }

    Ok(())
}

fn main() {
    let listener = TcpListener::bind(("localhost", 7000)).unwrap();
    chat_loop(&listener).unwrap();
}


open System.Windows.Forms
open System.Drawing
open System

let sz = 300
let polygon = [Point(sz/2, int (float sz*(1.0-sin(Math.PI/3.0)))); Point(0, sz-1); Point(sz-1, sz-1)]

let bmp = new Bitmap(sz, sz)
let paint (p: Point) = bmp.SetPixel(p.X, p.Y, Color.Black)

let random = Random()
let seed = Point(int (random.NextDouble() * float sz), int (random.NextDouble() * float sz))
let midpoint (p1: Point) (p2: Point) = Point((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2)
let randomVertex() = polygon.[random.Next(polygon.Length)]
let step p _ =
    paint p
    midpoint p (randomVertex())
Seq.init 100000 id |> Seq.fold step seed

let f = new Form()
f.ClientSize <- bmp.Size
f.Paint.Add (fun args -> args.Graphics.DrawImage(bmp, Point(0, 0)))
f.Show()


# syntax: GAWK -f CASTING_OUT_NINES.AWK
# converted from C
BEGIN {
    base = 10
    for (k=1; k<=base^2; k++) {
      c1++
      if (k % (base-1) == (k*k) % (base-1)) {
        c2++
        printf("%d ",k)
      }
    }
    printf("\nTrying %d numbers instead of %d numbers saves %.2f%%\n",c2,c1,100-(100*c2/c1))
    exit(0)
}


#include <stdio.h>
#include <math.h>

int main() {
    const int N = 2;
    int base = 10;
    int c1 = 0;
    int c2 = 0;
    int k;

    for (k = 1; k < pow(base, N); k++) {
        c1++;
        if (k % (base - 1) == (k * k) % (base - 1)) {
            c2++;
            printf("%d ", k);
        }
    }

    printf("\nTring %d numbers instead of %d numbers saves %f%%\n", c2, c1, 100.0 - 100.0 * c2 / c1);
    return 0;
}


// Casting Out Nines
//
// Nigel Galloway. June 24th., 2012
//
#include <iostream>
int main() {
	int Base = 10;
	const int N = 2;
	int c1 = 0;
	int c2 = 0;
	for (int k=1; k<pow((double)Base,N); k++){
		c1++;
		if (k%(Base-1) == (k*k)%(Base-1)){
			c2++;
			std::cout << k << " ";
		}
	}
	std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 - ((double)c2/c1)*100 << "%" <<std::endl;
	return 0;
}


package require Tcl 8.6

# Write a message to everyone except the sender of the message
proc writeEveryoneElse {sender message} {
    dict for {who ch} $::cmap {
	if {$who ne $sender} {
	    puts $ch $message
	}
    }
}

# How to read a line (up to 256 chars long) in a coroutine
proc cgets {ch var} {
    upvar 1 $var v
    while {[gets $ch v] < 0} {
	if {[eof $ch] || [chan pending input $ch] > 256} {
	    return false
	}
	yield
    }
    return true
}

# The chatting, as seen by one user
proc chat {ch addr port} {
    ### CONNECTION CODE ###
    #Log "connection from ${addr}:${port} on channel $ch"
    fconfigure $ch -buffering none -blocking 0 -encoding utf-8
    fileevent $ch readable [info coroutine]
    global cmap
    try {

	### GET THE NICKNAME OF THE USER ###
	puts -nonewline $ch "Please enter your name: "
	if {![cgets $ch name]} {
	    return
	}
	#Log "Mapping ${addr}:${port} to ${name} on channel $ch"
	dict set cmap $name $ch
	writeEveryoneElse $name "+++ $name arrived +++"

	### MAIN CHAT LOOP ###
	while {[cgets $ch line]} {
	    writeEveryoneElse $name "$name> $line"
	}

    } finally {
	### DISCONNECTION CODE ###
	if {[info exists name]} {
	    writeEveryoneElse $name "--- $name left ---"
	    dict unset cmap $name
	}
	close $ch
	#Log "disconnection from ${addr}:${port} on channel $ch"
    }
}

# Service the socket by making corouines running [chat]
socket -server {coroutine c[incr count] chat} 4004
set ::cmap {};		# Dictionary mapping nicks to channels
vwait forever;		# Run event loop


Imports System.Net.Sockets
Imports System.Text
Imports System.Threading

Module Module1

    Class State
        Private ReadOnly client As TcpClient
        Private ReadOnly sb As New StringBuilder

        Public Sub New(name As String, client As TcpClient)
            Me.Name = name
            Me.client = client
        End Sub

        Public ReadOnly Property Name As String

        Public Sub Send(text As String)
            Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text))
            client.GetStream().Write(bytes, 0, bytes.Length)
        End Sub
    End Class

    ReadOnly connections As New Dictionary(Of Integer, State)
    Dim listen As TcpListener
    Dim serverThread As Thread

    Sub Main()
        listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004)
        serverThread = New Thread(New ThreadStart(AddressOf DoListen))
        serverThread.Start()
    End Sub

    Private Sub DoListen()
        listen.Start()
        Console.WriteLine("Server: Started server")

        Do
            Console.Write("Server: Waiting...")
            Dim client = listen.AcceptTcpClient()
            Console.WriteLine(" Connected")

            ' New thread with client
            Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))

            clientThread.Start(client)
        Loop
    End Sub

    Private Sub DoClient(client As TcpClient)
        Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId)
        Dim bytes = Encoding.ASCII.GetBytes("Enter name: ")
        client.GetStream().Write(bytes, 0, bytes.Length)

        Dim done As Boolean
        Dim name As String
        Do
            If Not client.Connected Then
                Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
                client.Close()
                Thread.CurrentThread.Abort() ' Kill thread
            End If

            name = Receive(client)
            done = True

            For Each cl In connections
                Dim state = cl.Value
                If state.Name = name Then
                    bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ")
                    client.GetStream().Write(bytes, 0, bytes.Length)
                    done = False
                End If
            Next
        Loop While Not done

        connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))
        Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
        Broadcast(String.Format("+++ {0} arrived +++", name))

        Do
            Dim text = Receive(client)
            If text = "/quit" Then
                Broadcast(String.Format("Connection from {0} closed.", name))
                connections.Remove(Thread.CurrentThread.ManagedThreadId)
                Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
                Exit Do
            End If

            If Not client.Connected Then
                Exit Do
            End If

            Broadcast(String.Format("{0}> {1}", name, text))
        Loop

        Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
        client.Close()
        Thread.CurrentThread.Abort()
    End Sub

    Private Function Receive(client As TcpClient) As String
        Dim sb As New StringBuilder
        Do
            If client.Available > 0 Then
                While client.Available > 0
                    Dim ch = Chr(client.GetStream.ReadByte())
                    If ch = vbCr Then
                        ' ignore
                        Continue While
                    End If
                    If ch = vbLf Then
                        Return sb.ToString()
                    End If
                    sb.Append(ch)
                End While

                ' pause
                Thread.Sleep(100)
            End If
        Loop
    End Function

    Private Sub Broadcast(text As String)
        Console.WriteLine(text)
        For Each client In connections
            If client.Key <> Thread.CurrentThread.ManagedThreadId Then
                Dim state = client.Value
                state.Send(text)
            End If
        Next
    End Sub

End Module


PROGRAM CHAOS
 IMPLICIT NONE
 REAL, DIMENSION(3):: KA, KN ! Koordinates old/new
 REAL, DIMENSION(3):: DA, DB, DC ! Triangle
 INTEGER:: I, Z
 INTEGER, PARAMETER:: UT = 17
 ! Define corners of triangle
 DA = (/    0., 0.,   0. /)
 DB = (/  600., 0.,   0. /)
 DC = (/  500., 0., 400. /)
 ! Define starting point
 KA = (/  500., 0., 100. /)
 OPEN (UNIT = UT, FILE = 'aus.csv')
 DO I=1, 1000000
  Z = ZAHL()
  WRITE (UT, '(3(F12.6, ";"))') KA
  SELECT CASE (Z)
   CASE (1)
    CALL MITTELP(KA, DA, KN)
   CASE (2)
    CALL MITTELP(KA, DB, KN)
   CASE (3)
    CALL MITTELP(KA, DC, KN)
  END SELECT
  KA = KN
 END DO
 CLOSE (UT)
 CONTAINS
  ! Calculates center of two points
  SUBROUTINE MITTELP(P1, P2, MP)
   REAL, INTENT(IN), DIMENSION(3):: P1, P2
   REAL, INTENT(OUT), DIMENSION(3):: MP
   MP = (P1 + P2) / 2.
  END SUBROUTINE MITTELP
  ! Returns random number
  INTEGER FUNCTION ZAHL()
   REAL:: ZZ
   CALL RANDOM_NUMBER(ZZ)
   ZZ = ZZ * 3.
   ZAHL = FLOOR(ZZ) + 1
   IF (ZAHL .GT. 3) ZAHL = 3
  END FUNCTION ZAHL
END PROGRAM CHAOS


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CastingOutNines {
    public static class Helper {
        public static string AsString<T>(this IEnumerable<T> e) {
            var it = e.GetEnumerator();

            StringBuilder builder = new StringBuilder();
            builder.Append("[");

            if (it.MoveNext()) {
                builder.Append(it.Current);
            }
            while (it.MoveNext()) {
                builder.Append(", ");
                builder.Append(it.Current);
            }

            builder.Append("]");
            return builder.ToString();
        }
    }

    class Program {
        static List<int> CastOut(int @base, int start, int end) {
            int[] ran = Enumerable
                .Range(0, @base - 1)
                .Where(a => a % (@base - 1) == (a * a) % (@base - 1))
                .ToArray();
            int x = start / (@base - 1);

            List<int> result = new List<int>();
            while (true) {
                foreach (int n in ran) {
                    int k = (@base - 1) * x + n;
                    if (k < start) {
                        continue;
                    }
                    if (k > end) {
                        return result;
                    }
                    result.Add(k);
                }
                x++;
            }
        }

        static void Main() {
            Console.WriteLine(CastOut(16, 1, 255).AsString());
            Console.WriteLine(CastOut(10, 1, 99).AsString());
            Console.WriteLine(CastOut(17, 1, 288).AsString());
        }
    }
}


/* chat_server.wren */

class Clients {
    foreign static max
    foreign static count
    foreign static isActive(vmi)
    foreign static connfd(vmi)
    foreign static uid(vmi)
    foreign static name(vmi)
    foreign static setName(vmi, s)
    foreign static printAddr(vmi)
    foreign static delete(vmi)
}

class Mutex {
    foreign static clientsLock()
    foreign static clientsUnlock()

    foreign static topicLock()
    foreign static topicUnlock()
}

class Chat {
    // send message to all clients but the sender
    static sendMessage(s, uid) {
        Mutex.clientsLock()
        for (i in 0...Clients.max) {
            if (Clients.isActive(i) && Clients.uid(i) != uid) {
                if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
                    System.print("Write to descriptor %(Clients.connfd(i)) failed.")
                    break
                }
            }
        }
        Mutex.clientsUnlock()
    }

    // send message to all clients
    static sendMessageAll(s) {
        Mutex.clientsLock()
        for (i in 0...Clients.max) {
            if (Clients.isActive(i)) {
                if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
                    System.print("Write to descriptor %(Clients.connfd(i)) failed.")
                    break
                }
            }
        }
        Mutex.clientsUnlock()
    }

    // send message to sender
    static sendMessageSelf(s, connfd) {
        if (write(connfd, s, s.bytes.count) < 0) {
            Fiber.abort("Write to descriptor %(connfd) failed.")
        }
    }

    // send message to client
    static sendMessageClient(s, uid) {
        Mutex.clientsLock()
        for (i in 0...Clients.max) {
            if (Clients.isActive(i) && Clients.uid(i) == uid) {
                if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
                    System.print("Write to descriptor %(Clients.connfd(i)) failed.")
                    break
                }
            }
        }
        Mutex.clientsUnlock()
    }

    // send list of active clients
    static sendActiveClients(connfd) {
        Mutex.clientsLock()
        for (i in 0...Clients.max) {
            if (Clients.isActive(i)) {
                var s = "<< [%(Clients.uid(i))] %(Clients.name(i))\r\n"
                sendMessageSelf(s, connfd)
            }
        }
        Mutex.clientsUnlock()
    }

    // handle all communication with the client
    static handleClient(vmi) {
        if (!Clients.isActive(vmi)) {
            Fiber.abort("The client handled by VM[%(vmi)] is inactive.")
        }
        var connfd = Clients.connfd(vmi)
        var uid    = Clients.uid(vmi)
        var name   = Clients.name(vmi)
        System.write("<< accept ")
        Clients.printAddr(vmi)
        System.print(" referenced by %(uid)")
        var buffOut = "<< %(name) has joined\r\n"
        sendMessageAll(buffOut)
        Mutex.topicLock()
        if (topic != "") {
            buffOut = "<< topic: %(topic)\r\n"
            sendMessageSelf(buffOut, connfd)
        }
        Mutex.topicUnlock()
        sendMessageSelf("<< see /help for assistance\r\n", connfd)

        /* receive input from client */
        var buffIn = ""
        while ((buffIn = read(connfd, bufferSize/2 - 1)) && buffIn.bytes.count > 0) {
            buffOut = ""
            buffIn = buffIn.trimEnd("\r\n")

            /* ignore empty buffer */
            if (buffIn == "") continue

            /* special options */
            if (buffIn[0] == "/") {
                var split = buffIn.split(" ")
                var command = split[0]
                if (command == "/quit") {
                    break
                } else if (command == "/ping") {
                    sendMessageSelf("<< pong\r\n", connfd)
                } else if (command == "/topic") {
                    if (split.count > 0) {
                        Mutex.topicLock()
                        topic = split[1..-1].join(" ")
                        Mutex.topicUnlock()
                        buffOut = "<< topic changed to: %(topic)\r\n"
                        sendMessageAll(buffOut)
                    } else {
                        sendMessageSelf("<< message cannot be null\r\n", connfd)
                    }
                } else if (command == "/nick") {
                    if (split.count > 0) {
                        var newName = split[1..-1].join(" ")
                        buffOut = "<< %(name) is now known as %(newName)\r\n"
                        Clients.setName(vmi, newName)
                        name = newName
                        sendMessageAll(buffOut)
                    } else {
                        sendMessageSelf("<< name cannot be null\r\n", connfd)
                    }
                } else if (command == "/msg") {
                    if (split.count > 0) {
                        var toUid = Num.fromString(split[1])
                        if (split.count > 1) {
                            buffOut = "[PM][%(name)] "
                            buffOut = buffOut + split[2..-1].join(" ") + "\r\n"
                            sendMessageClient(buffOut, toUid)
                        } else {
                            sendMessageSelf("<< message cannot be null\r\n", connfd)
                        }
                    } else {
                        sendMessageSelf("<< reference cannot be null\r\n", connfd)
                    }
                } else if (command == "/list") {
                    buffOut = "<< clients %(Clients.count)\r\n"
                    sendMessageSelf(buffOut, connfd)
                    sendActiveClients(connfd)
                } else if (command == "/help") {
                    buffOut = ""
                    buffOut = buffOut + "<< /quit      Quit chatroom\r\n"
                    buffOut = buffOut + "<< /ping      Server test\r\n"
                    buffOut = buffOut + "<< /topic     <message> Set chat topic\r\n"
                    buffOut = buffOut + "<< /nick      <name> Change nickname\r\n"
                    buffOut = buffOut + "<< /msg       <reference> <message> Send private message\r\n"
                    buffOut = buffOut + "<< /list      Show active clients\r\n"
                    buffOut = buffOut + "<< /help      Show help\r\n"
                    sendMessageSelf(buffOut, connfd)
                } else {
                    sendMessageSelf("<< unknown command\r\n", connfd)
                }
            } else {
                /* send message */
                buffOut = "[%(name)] %(buffIn)\r\n"
                sendMessage(buffOut, uid)
            }
         }

         /* close connection */
         buffOut = "<< [%(name)] has left\r\n"
         sendMessageAll(buffOut)
         close(connfd)

         /* delete client from queue and yield thread (from C side) */
         System.write("<< quit ")
         Clients.printAddr(vmi)
         System.print(" referenced by %(uid)")
         Clients.delete(vmi)
     }

     foreign static topic
     foreign static topic=(s)

     foreign static bufferSize
     foreign static write(connfd, buf, count)
     foreign static read(connfd, count)
     foreign static close(connfd)
}


' Chaos game
Const ancho = 320, alto = 240
Dim As Integer x, y, iteracion, vertice
x = Int(Rnd * ancho)
y = Int(Rnd * alto)

Screenres ancho, alto, 8
Cls

For iteracion = 1 To 30000
	vertice = Int(Rnd * 3) + 1
	Select Case vertice
    Case 1
        x = x / 2
        y = y / 2
        vertice = 4 'red
    Case 2
        x = (ancho/2) + ((ancho/2)-x) / 2
        y = alto - (alto-y) / 2
        vertice = 2 'green
    Case 3
        x = ancho - (ancho-x) / 2
        y = y / 2
        vertice = 1 'blue
    End Select
	Pset (x,y),vertice
Next iteracion
Sleep
End


offset = 32; //Distance from triangle vertices to edges of window

//triangle vertex coordinates
x1 = room_width / 2;
y1 = offset;
x2 = room_width - offset;
y2 = room_height - offset;
x3 = offset;
y3 = room_height - offset;

//Coords of randomly chosen vertex (set to 0 to start, will automatically be set in step event)
vx = 0;
vy = 0;

//Coords of current point
px = random(room_width);
py = random(room_height);

//Make sure the point is within the triangle
while(!point_in_triangle(px, py, x1, y1, x2, y2, x3, y3))
{
	px = random(room_width);
	py = random(room_height);
}

vertex = 0; //This determines which vertex coords are chosen
max_iterations = 8000;
step = true; //Used with the interval alarm to change the step speed
step_count = 0;
interval = 1; //Number of frames between each step. 1 = no delay
alarm[0] = interval;


;;A macro was used to ensure that the filter is inlined.
;;Larry Hignight.  Last updated on 7/3/2012.
(defmacro kaprekar-number-filter (n &optional (base 10))
  `(= (mod ,n (1- ,base)) (mod (* ,n ,n) (1- ,base))))

(defun test (&key (start 1) (stop 10000) (base 10) (collect t))
  (let ((count 0)
	(nums))
    (loop for i from start to stop do
	  (when (kaprekar-number-filter i base)
	    (if collect (push i nums))
	    (incf count)))
    (format t "~d potential Kaprekar numbers remain (~~~$% filtered out).~%"
	    count (* (/ (- stop count) stop) 100))
    (if collect (reverse nums))))


import std.stdio, std.algorithm, std.range;

uint[] castOut(in uint base=10, in uint start=1, in uint end=999999) {
    auto ran = iota(base - 1)
               .filter!(x => x % (base - 1) == (x * x) % (base - 1));
    auto x = start / (base - 1);
    immutable y = start % (base - 1);

    typeof(return) result;
    while (true) {
        foreach (immutable n; ran) {
            immutable k = (base - 1) * x + n;
            if (k < start)
                continue;
            if (k > end)
                return result;
            result ~= k;
        }
        x++;
    }
}

void main() {
    castOut(16, 1, 255).writeln;
    castOut(10, 1, 99).writeln;
    castOut(17, 1, 288).writeln;
}


const PORT=23;

var users=Dictionary(); // ( handle:socket, ...)
pipe:=Thread.Pipe(); // how server tells thread to connect to user

fcn accept(pipe){ // a thread waiting for the server to send a socket
   while(socket:=pipe.read()){
      println("Somebody is connecting ...");
      socket.read();  // telnet stuff
      while(True){    // get credentials
	 reg name;
	 socket.write("Your handle: ");  // bottle neck
	 try{ name = socket.read().text.strip() } catch(IOError){ continue }
	 if(users.holds(name)) socket.write("Handle is already in use.\n");
	 else if(name){
	    users[name] = socket;
	    chat.launch(name,socket);	// thread
	    broadcast(name, "+++ %s arrived +++".fmt(name));
	    break;	// wait for next connection
	 }
      }//while
   }//while
}.launch(pipe); // thread

fcn chat(name,socket){		// a thread, one per user
   try{
      socket.write("^D to disconnect\n");
      while(True){
	 message:=socket.read().text.strip();
	 if(message=="\xff\xec") break; // ^D to disconnect.
	 broadcast(name, "%s> %s".fmt(name,message));
      }
   }catch{}  // eg socket pukes
   users.del(name); socket.close();
   broadcast(name, "--- %s leaves ---".fmt(name));
}

    // Send a message to all users from the given name.
fcn broadcast(name, message){ // called from user thread
   println(message);  // log message to server console
   users.pump(Void,'wrap([(toName,socket)]){
      if(toName != name) try{ socket.write(message + "\n") } catch(IOError){}
   });
}

   // Set up the server socket.
server:=Network.TCPServerSocket.open(PORT);
println("Listening on %s:%s".fmt(server.hostname,server.port));
server.listen(pipe);  // Main event loop


## Chaos Game  (Sierpinski triangle) 2/16/17 aev
reset
fn="ChGS3Gnu1"; clr='"red"';
ttl="Chaos Game  (Sierpinski triangle)"
sz=600; sz1=sz/2; sz2=sz1*sqrt(3);
x=y=xf=yf=v=0;
dfn=fn.".dat"; ofn=fn.".png";
set terminal png font arial 12 size 640,640
set print dfn append
set output ofn
unset border; unset xtics; unset ytics; unset key;
set size square
set title ttl font "Arial:Bold,12"
lim=30000; max=100; x=y=xw=yw=p=0;
randgp(top) = floor(rand(0)*top)
x=randgp(sz); y=randgp(sz2);
do for [i=1:lim] {
  v=randgp(3);
  if (v==0) {x=x/2; y=y/2}
  if (v==1) {x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2}
  if (v==2) {x=sz-(sz-x)/2; y=y/2}
  xf=floor(x); yf=floor(y);
  if(!(xf<1||xf>sz||yf<1||yf>sz)) {print xf," ",yf};
}
plot dfn using 1:2 with points  pt 7 ps 0.5 lc @clr
set output
unset print


Const base10 = 10
Dim As Integer c1 = 0, c2 = 0, k = 1

For k = 1 To base10^2
    c1 += 1
    If (k Mod (base10-1) = (k*k) Mod (base10-1)) Then c2 += 1: Print k;" ";
Next k

Print
Print Using "Intentar ## numeros en lugar de ### numeros ahorra un ##.##%"; c2; c1; 100-(100*c2/c1)
Sleep


program castout9;
{$ifdef fpc}{$mode delphi}{$endif}
uses generics.collections;
type
  TIntegerList = TSortedList<integer>;

procedure co9(const start,base,lim:integer;kaprekars:array of integer);
var
  C1:integer = 0;
  C2:integer = 0;
  S:TIntegerlist;
  k,i:integer;
begin
  S:=TIntegerlist.Create;
  for k := start to lim do
  begin
    inc(C1);
    if k mod (base-1) = (k*k) mod (base-1) then
    begin
      inc(C2);
      S.Add(k);
    end;
  end;
  writeln('Valid subset: ');
  for i in Kaprekars do
    if not s.contains(i) then
      writeln('invalid ',i);

  for i in s do write(i:4);
  writeln;
  write('The Kaprekars in this range [');
  for i in kaprekars do write(i:4);
  writeln('] are included');
  writeln('Trying ',C2, ' numbers instead of ', C1,' saves ',100-(C2 * 100 /C1):3:2,',%.');
  writeln;
  S.Free;
end;

begin
  co9(1, 10, 99, [1,9,45,55,99]);
  co9(1, 10, 1000, [1,9,45,55,99,297,703,999]);
end.


package main

import (
	"fmt"
	"image"
	"image/color"
	"image/draw"
	"image/gif"
	"log"
	"math"
	"math/rand"
	"os"
	"time"
)

var bwPalette = color.Palette{
	color.Transparent,
	color.White,
	color.RGBA{R: 0xff, A: 0xff},
	color.RGBA{G: 0xff, A: 0xff},
	color.RGBA{B: 0xff, A: 0xff},
}

func main() {
	const (
		width          = 160
		frames         = 100
		pointsPerFrame = 50
		delay          = 100 * time.Millisecond
		filename       = "chaos_anim.gif"
	)

	var tan60 = math.Sin(math.Pi / 3)
	height := int(math.Round(float64(width) * tan60))
	b := image.Rect(0, 0, width, height)
	vertices := [...]image.Point{
		{0, height}, {width, height}, {width / 2, 0},
	}

	// Make a filled triangle.
	m := image.NewPaletted(b, bwPalette)
	for y := b.Min.Y; y < b.Max.Y; y++ {
		bg := int(math.Round(float64(b.Max.Y-y) / 2 / tan60))
		for x := b.Min.X + bg; x < b.Max.X-bg; x++ {
			m.SetColorIndex(x, y, 1)
		}
	}

	// Pick starting point
	var p image.Point
	rand.Seed(time.Now().UnixNano())
	p.Y = rand.Intn(height) + b.Min.Y
	p.X = rand.Intn(width) + b.Min.X // TODO: make within triangle

	anim := newAnim(frames, delay)
	addFrame(anim, m)
	for i := 1; i < frames; i++ {
		for j := 0; j < pointsPerFrame; j++ {
			// Pick a random vertex
			vi := rand.Intn(len(vertices))
			v := vertices[vi]
			// Move p halfway there
			p.X = (p.X + v.X) / 2
			p.Y = (p.Y + v.Y) / 2
			m.SetColorIndex(p.X, p.Y, uint8(2+vi))
		}
		addFrame(anim, m)
	}
	if err := writeAnim(anim, filename); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("wrote to %q\n", filename)
}

// Stuff for making a simple GIF animation.

func newAnim(frames int, delay time.Duration) *gif.GIF {
	const gifDelayScale = 10 * time.Millisecond
	g := &gif.GIF{
		Image: make([]*image.Paletted, 0, frames),
		Delay: make([]int, 1, frames),
	}
	g.Delay[0] = int(delay / gifDelayScale)
	return g
}
func addFrame(anim *gif.GIF, m *image.Paletted) {
	b := m.Bounds()
	dst := image.NewPaletted(b, m.Palette)
	draw.Draw(dst, b, m, image.ZP, draw.Src)
	anim.Image = append(anim.Image, dst)
	if len(anim.Delay) < len(anim.Image) {
		anim.Delay = append(anim.Delay, anim.Delay[0])
	}
}
func writeAnim(anim *gif.GIF, filename string) error {
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	err = gif.EncodeAll(f, anim)
	if cerr := f.Close(); err == nil {
		err = cerr
	}
	return err
}


package main

import (
    "fmt"
    "log"
    "strconv"
)

// A casting out nines algorithm.

// Quoting from: http://mathforum.org/library/drmath/view/55926.html
/*
First, for any number we can get a single digit, which I will call the
"check digit," by repeatedly adding the digits. That is, we add the
digits of the number, then if there is more than one digit in the
result we add its digits, and so on until there is only one digit
left.

...

You may notice that when you add the digits of 6395, if you just
ignore the 9, and the 6+3 = 9, you still end up with 5 as your check
digit. This is because any 9's make no difference in the result.
That's why the process is called "casting out" nines. Also, at any
step in the process, you can add digits, not just at the end: to do
8051647, I can say 8 + 5 = 13, which gives 4; plus 1 is 5, plus 6 is
11, which gives 2, plus 4 is 6, plus 7 is 13 which gives 4. I never
have to work with numbers bigger than 18.
*/
// The twist is that co9Peterson returns a function to do casting out nines
// in any specified base from 2 to 36.
func co9Peterson(base int) (cob func(string) (byte, error), err error) {
    if base < 2 || base > 36 {
        return nil, fmt.Errorf("co9Peterson: %d invalid base", base)
    }
    // addDigits adds two digits in the specified base.
    // People perfoming casting out nines by hand would usually have their
    // addition facts memorized.  In a program, a lookup table might be
    // analogous, but we expediently use features of the programming language
    // to add digits in the specified base.
    addDigits := func(a, b byte) (string, error) {
        ai, err := strconv.ParseInt(string(a), base, 64)
        if err != nil {
            return "", err
        }
        bi, err := strconv.ParseInt(string(b), base, 64)
        if err != nil {
            return "", err
        }
        return strconv.FormatInt(ai+bi, base), nil
    }
    // a '9' in the specified base.  that is, the greatest digit.
    s9 := strconv.FormatInt(int64(base-1), base)
    b9 := s9[0]
    // define result function.  The result function may return an error
    // if n is not a valid number in the specified base.
    cob = func(n string) (r byte, err error) {
        r = '0'
        for i := 0; i < len(n); i++ { // for each digit of the number
            d := n[i]
            switch {
            case d == b9: // if the digit is '9' of the base, cast it out
                continue
            // if the result so far is 0, the digit becomes the result
            case r == '0':
                r = d
                continue
            }
            // otherwise, add the new digit to the result digit
            s, err := addDigits(r, d)
            if err != nil {
                return 0, err
            }
            switch {
            case s == s9: // if the sum is "9" of the base, cast it out
                r = '0'
                continue
            // if the sum is a single digit, it becomes the result
            case len(s) == 1:
                r = s[0]
                continue
            }
            // otherwise, reduce this two digit intermediate result before
            // continuing.
            r, err = cob(s)
            if err != nil {
                return 0, err
            }
        }
        return
    }
    return
}

// Subset code required by task.  Given a base and a range specified with
// beginning and ending number in that base, return candidate Kaprekar numbers
// based on the observation that k%(base-1) must equal (k*k)%(base-1).
// For the % operation, rather than the language built-in operator, use
// the method of casting out nines, which in fact implements %(base-1).
func subset(base int, begin, end string) (s []string, err error) {
    // convert begin, end to native integer types for easier iteration
    begin64, err := strconv.ParseInt(begin, base, 64)
    if err != nil {
        return nil, fmt.Errorf("subset begin: %v", err)
    }
    end64, err := strconv.ParseInt(end, base, 64)
    if err != nil {
        return nil, fmt.Errorf("subset end: %v", err)
    }
    // generate casting out nines function for specified base
    cob, err := co9Peterson(base)
    if err != nil {
        return
    }
    for k := begin64; k <= end64; k++ {
        ks := strconv.FormatInt(k, base)
        rk, err := cob(ks)
        if err != nil { // assertion
            panic(err) // this would indicate a bug in subset
        }
        rk2, err := cob(strconv.FormatInt(k*k, base))
        if err != nil { // assertion
            panic(err) // this would indicate a bug in subset
        }
        // test for candidate Kaprekar number
        if rk == rk2 {
            s = append(s, ks)
        }
    }
    return
}

var testCases = []struct {
    base       int
    begin, end string
    kaprekar   []string
}{
    {10, "1", "100", []string{"1", "9", "45", "55", "99"}},
    {17, "10", "gg", []string{"3d", "d4", "gg"}},
}

func main() {
    for _, tc := range testCases {
        fmt.Printf("\nTest case base = %d, begin = %s, end = %s:\n",
            tc.base, tc.begin, tc.end)
        s, err := subset(tc.base, tc.begin, tc.end)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Subset:  ", s)
        fmt.Println("Kaprekar:", tc.kaprekar)
        sx := 0
        for _, k := range tc.kaprekar {
            for {
                if sx == len(s) {
                    fmt.Printf("Fail:", k, "not in subset")
                    return
                }
                if s[sx] == k {
                    sx++
                    break
                }
                sx++
            }
        }
        fmt.Println("Valid subset.")
    }
}


import javafx.animation.AnimationTimer
import javafx.application.Application
import javafx.scene.Scene
import javafx.scene.layout.Pane
import javafx.scene.paint.Color
import javafx.scene.shape.Circle
import javafx.stage.Stage

class ChaosGame extends Application {

    final randomNumberGenerator = new Random()

    @Override
    void start(Stage primaryStage) {
        primaryStage.title = 'Chaos Game'
        primaryStage.scene = getScene()
        primaryStage.show()
    }

    def getScene() {
        def colors = [Color.RED, Color.GREEN, Color.BLUE]

        final width = 640, height = 640, margin = 60
        final size = width - 2 * margin

        def points = [
                new Circle(width / 2, margin, 1, colors[0]),
                new Circle(margin, size, 1, colors[1]),
                new Circle(margin + size, size, 1, colors[2])
        ]

        def pane = new Pane()
        pane.style = '-fx-background-color: black;'
        points.each {
            pane.children.add it
        }

        def currentPoint = new Circle().with {
            centerX = randomNumberGenerator.nextInt(size - margin) + margin
            centerY =  randomNumberGenerator.nextInt(size - margin) + margin
            it
        }

        ({

            def newPoint = generatePoint(currentPoint, points, colors)
            pane.children.add newPoint
            currentPoint = newPoint

        } as AnimationTimer).start()

        new Scene(pane, width, height)
    }

    def generatePoint(currentPoint, points, colors) {
        def selection = randomNumberGenerator.nextInt 3
        new Circle().with {
            centerX = (currentPoint.centerX + points[selection].centerX) / 2
            centerY = (currentPoint.centerY + points[selection].centerY) / 2
            radius = 1
            fill = colors[selection]
            it
        }
    }

    static main(args) {
        launch(ChaosGame)
    }
}


co9 n
  | n <= 8 = n
  | otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n

task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100]

task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100]


import java.util.*;
import java.util.stream.IntStream;

public class CastingOutNines {

    public static void main(String[] args) {
        System.out.println(castOut(16, 1, 255));
        System.out.println(castOut(10, 1, 99));
        System.out.println(castOut(17, 1, 288));
    }

    static List<Integer> castOut(int base, int start, int end) {
        int[] ran = IntStream
                .range(0, base - 1)
                .filter(x -> x % (base - 1) == (x * x) % (base - 1))
                .toArray();

        int x = start / (base - 1);

        List<Integer> result = new ArrayList<>();
        while (true) {
            for (int n : ran) {
                int k = (base - 1) * x + n;
                if (k < start)
                    continue;
                if (k > end)
                    return result;
                result.add(k);
            }
            x++;
        }
    }
}


import Control.Monad (replicateM)
import Control.Monad.Random (fromList)

type Point = (Float,Float)
type Transformations = [(Point -> Point, Float)] -- weighted transformations

-- realization of the game for given transformations
gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point]
gameOfChaos n transformations x = iterateA (fromList transformations) x
  where iterateA f x = scanr ($) x <$> replicateM n f


Note 'plan, Working in complex plane'
  Make an equilateral triangle.
  Make a list of N targets
  Starting with a random point near the triangle,
    iteratively generate new points.
  plot the new points.

  j has a particularly rich notation for numbers.

    1ad_90 specifies a complex number with radius 1
    at an angle of negative 90 degrees.

    2p1 is 2 times (pi raised to the first power).
)

N=: 3000

require'plot'
TAU=: 2p1 NB. tauday.com
mean=: +/ % #

NB. equilateral triangle with vertices on unit circle
NB. rotated for fun.
TRIANGLE=: *(j./2 1 o.(TAU%6)*?0)*1ad_90 1ad150 1ad30

TARGETS=: (N [email protected]:# 3) { TRIANGLE

NB. start on unit circle
START=: j./2 1 o.TAU*?0

NEW_POINTS=: ([email protected]:(, {.) , ])/ TARGETS , START

'marker'plot NEW_POINTS


function main(s, e, bs, pbs) {
    bs = bs || 10;
    pbs = pbs || 10
    document.write('start:', toString(s), ' end:', toString(e),
        ' base:', bs, ' printBase:', pbs)
    document.write('
castOutNine: ');
    castOutNine()
    document.write('
kaprekar: ');
    kaprekar()
    document.write('

')

    function castOutNine() {
        for (var n = s, k = 0, bsm1 = bs - 1; n <= e; n += 1)
            if (n % bsm1 == (n * n) % bsm1) k += 1,
                document.write(toString(n), ' ')
        document.write('
trying ', k, ' numbers instead of ', n = e - s + 1,
            ' numbers saves ', (100 - k / n * 100)
            .toFixed(3), '%')
    }

    function kaprekar() {
        for (var n = s; n <= e; n += 1)
            if (isKaprekar(n)) document.write(toString(n), ' ')

        function isKaprekar(n) {
            if (n < 1) return false
            if (n == 1) return true
            var s = (n * n)
                .toString(bs)
            for (var i = 1, e = s.length; i < e; i += 1) {
                var a = parseInt(s.substr(0, i), bs)
                var b = parseInt(s.substr(i), bs)
                if (b && a + b == n) return true
            }
            return false
        }
    }

    function toString(n) {
        return n.toString(pbs)
            .toUpperCase()
    }
}
main(1, 10 * 10 - 1)
main(1, 16 * 16 - 1, 16)
main(1, 17 * 17 - 1, 17)
main(parseInt('10', 17), parseInt('gg', 17), 17, 17)


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class ChaosGame extends JPanel {
    static class ColoredPoint extends Point {
        int colorIndex;

        ColoredPoint(int x, int y, int idx) {
            super(x, y);
            colorIndex = idx;
        }
    }

    Stack<ColoredPoint> stack = new Stack<>();
    Point[] points = new Point[3];
    Color[] colors = {Color.red, Color.green, Color.blue};
    Random r = new Random();

    public ChaosGame() {
        Dimension dim = new Dimension(640, 640);
        setPreferredSize(dim);
        setBackground(Color.white);

        int margin = 60;
        int size = dim.width - 2 * margin;

        points[0] = new Point(dim.width / 2, margin);
        points[1] = new Point(margin, size);
        points[2] = new Point(margin + size, size);

        stack.push(new ColoredPoint(-1, -1, 0));

        new Timer(10, (ActionEvent e) -> {
            if (stack.size() < 50_000) {
                for (int i = 0; i < 1000; i++)
                    addPoint();
                repaint();
            }
        }).start();
    }

    private void addPoint() {
        try {
            int colorIndex = r.nextInt(3);
            Point p1 = stack.peek();
            Point p2 = points[colorIndex];
            stack.add(halfwayPoint(p1, p2, colorIndex));
        } catch (EmptyStackException e) {
            e.printStackTrace();
        }
    }

    void drawPoints(Graphics2D g) {
        for (ColoredPoint p : stack) {
            g.setColor(colors[p.colorIndex]);
            g.fillOval(p.x, p.y, 1, 1);
        }
    }

    ColoredPoint halfwayPoint(Point a, Point b, int idx) {
        return new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx);
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawPoints(g);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Chaos Game");
            f.setResizable(false);
            f.add(new ChaosGame(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}


def co9:
  def digits: tostring | explode | map(. - 48);  # "0" is 48
  if . == 9 then 0
  elif 0 <= . and . <= 8 then .
  else digits | add | co9
  end;


// version 1.1.3

fun castOut(base: Int, start: Int, end: Int): List<Int> {
    val b = base - 1
    val ran = (0 until b).filter { it % b == (it * it) % b }
    var x = start / b
    val result = mutableListOf<Int>()
    while (true) {
        for (n in ran) {
            val k = b * x + n
            if (k < start) continue
            if (k > end) return result
            result.add(k)
        }
        x++
    }
}

fun main(args: Array<String>) {
    println(castOut(16, 1, 255))
    println()
    println(castOut(10, 1, 99))
    println()
    println(castOut(17, 1, 288))
}


local N = 2
local base = 10
local c1 = 0
local c2 = 0

for k = 1, math.pow(base, N) - 1 do
    c1 = c1 + 1
    if k % (base - 1) == (k * k) % (base - 1) then
        c2 = c2 + 1
        io.write(k .. ' ')
    end
end

print()
print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 100.0 * c2 / c1))


<meta charset="UTF-8">

<title>Chaos Game</title>

<canvas id="sierpinski" width=400 height=346></canvas>

<button onclick="chaosGame()">Click here to see a Sierpiński triangle</button>


Co9[n_, b_: 10] :=
  With[{ans = FixedPoint[[email protected][#, b] &, n]},
   If[ans == b - 1, 0, ans]];


import sequtils

iterator castOut(base = 10, start = 1, ending = 999_999): int =
  var ran: seq[int] = @[]
  for y in 0 ..< base-1:
    if y mod (base - 1) == (y*y) mod (base - 1):
      ran.add(y)

  var x = start div (base - 1)
  var y = start mod (base - 1)

  block outer:
    while true:
      for n in ran:
        let k = (base - 1) * x + n
        if k < start:
          continue
        if k > ending:
          break outer
        yield k
      inc x

echo toSeq(castOut(base=16, start=1, ending=255))


class CastingNines {
  function : Main(args : String[]) ~ Nil {
    base := 10;
    N := 2;
    c1 := 0;
    c2 := 0;

    for (k:=1; k<base->As(Float)->Power(N->As(Float)); k+=1;){
      c1+=1;
      if (k%(base-1) = (k*k)%(base-1)){
        c2+=1;
        IO.Console->Print(k)->Print(" ");
      };
    };

    IO.Console->Print("\nTrying ")->Print(c2)->Print(" numbers instead of ")
      ->Print(c1)->Print(" numbers saves ")->Print(100 - (c2->As(Float)/c1
      ->As(Float)*100))->PrintLine("%");
  }
}


using Luxor

function chaos()
    width  = 1000
    height = 1000
    Drawing(width, height, "./chaos.png")
    t = Turtle(0, 0, true, 0, (0., 0., 0.))
    x = rand(1:width)
    y = rand(1:height)

    for l in 1:30_000
        v = rand(1:3)
        if v == 1
            x /= 2
            y /= 2
        elseif v == 2
            x = width/2 + (width/2 - x)/2
            y = height - (height - y)/2
        else
            x = width - (width - x)/2
            y = y / 2
        end
        Reposition(t, x, height-y)
        Circle(t, 3)
    end
end

chaos()
finish()
preview()


//Version 1.1.51

import java.awt.*
import java.util.Stack
import java.util.Random
import javax.swing.JPanel
import javax.swing.JFrame
import javax.swing.Timer
import javax.swing.SwingUtilities

class ChaosGame : JPanel() {

    class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y)

    val stack = Stack<ColoredPoint>()
    val points: List<Point>
    val colors = listOf(Color.red, Color.green, Color.blue)
    val r = Random()

    init {
        val dim = Dimension(640, 640)
        preferredSize = dim
        background = Color.white
        val margin = 60
        val size = dim.width - 2 * margin
        points = listOf(
            Point(dim.width / 2, margin),
            Point(margin, size),
            Point(margin + size, size)
        )
        stack.push(ColoredPoint(-1, -1, 0))

        Timer(10) {
            if (stack.size < 50_000) {
                for (i in 0 until 1000) addPoint()
                repaint()
            }
        }.start()
    }

    private fun addPoint() {
        val colorIndex = r.nextInt(3)
        val p1 = stack.peek()
        val p2 = points[colorIndex]
        stack.add(halfwayPoint(p1, p2, colorIndex))
    }

    fun drawPoints(g: Graphics2D) {
        for (cp in stack) {
            g.color = colors[cp.colorIndex]
            g.fillOval(cp.x, cp.y, 1, 1)
        }
    }

    fun halfwayPoint(a: Point, b: Point, idx: Int) =
        ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx)

    override fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON)
        drawPoints(g)
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = JFrame()
        with (f) {
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
            title = "Chaos Game"
            isResizable = false
            add(ChaosGame(), BorderLayout.CENTER)
            pack()
            setLocationRelativeTo(null)
            isVisible = true
        }
    }
}


sub co9 {  # Follows the simple procedure asked for in Part 1
  my $n = shift;
  return $n if $n < 10;
  my $sum = 0; $sum += $_ for split(//,$n);
  co9($sum);
}

sub showadd {
  my($n,$m) = @_;
  print "( $n [",co9($n),"] + $m [",co9($m),"] ) [",co9(co9($n)+co9($m)),"]",
        "   =   ", $n+$m," [",co9($n+$m),"]\n";
}

sub co9filter {
  my $base = shift;
  die unless $base >= 2;
  my($beg, $end, $basem1) = (1, $base*$base-1, $base-1);
  my @list = grep { $_ % $basem1 == $_*$_ % $basem1 } $beg .. $end;
  ($end, scalar(@list), @list);
}

print "Part 1: Create a simple filter and demonstrate using simple example.\n";
showadd(6395, 1259);

print "\nPart 2: Use this to filter a range with co9(k) == co9(k^2).\n";
print join(" ", grep { co9($_) == co9($_*$_) } 1..99), "\n";

print "\nPart 3: Use efficient method on range.\n";
for my $base (10, 17) {
  my($N, $n, @l) = co9filter($base);
  printf "[@l]\nIn base %d, trying %d numbers instead of %d saves %.4f%%\n\n",
         $base, $n, $N, 100-($n/$N)*100;
}


with javascript_semantics
procedure co9(integer start, integer base, integer lim, sequence kaprekars)
    integer c1=0,
            c2=0
    sequence s = {}
    for k=start to lim do
        c1 += 1
        if mod(k,base-1)=mod(k*k,base-1) then
            c2 += 1
            s &= k
        end if
    end for
    string msg = "valid subset"
    for i=1 to length(kaprekars) do
        if not find(kaprekars[i],s) then
            msg = "***INVALID***"
            exit
        end if
    end for
    if length(s)>25 then s[10..-10] = {"..."} end if
    printf(1,"%V\nKaprekar numbers: %V - %s\n",{s,kaprekars,msg})
    printf(1,"Trying %d numbers instead of %d saves %3.2f%%\n\n",{c2,c1,100-(c2/c1)*100})
end procedure

co9(1, 10, 99, {1,9,45,55,99})
co9(0(17)10, 17, 17*17, {0(17)3d,0(17)d4,0(17)gg})
co9(1, 10, 1000, {1,9,45,55,99,297,703,999})


V dog = ‘Benjamin’
V Dog = ‘Samba’
V DOG = ‘Bernie’
print(‘The three dogs are named ’dog‘, ’Dog‘ and ’DOG‘.’)


to chaosgame :sidelength :iterations
    make "width :sidelength
    make "height (:sidelength/2 * sqrt 3)
    make "x (random :width)
    make "y (random :height)
    repeat :iterations [
        make "vertex (random 3)
        if :vertex = 0 [
            make "x (:x / 2)
            make "y (:y / 2)
            setpencolor "green
        ]
        if :vertex = 1 [
            make "x (:width / 2 + ((:width / 2 - :x) / 2))
            make "y (:height - ((:height - :y) / 2))
            setpencolor "red
        ]
        if :vertex = 2 [
            make "x (:width - ((:width - :x) / 2))
            make "y (:y / 2)
            setpencolor "blue
        ]
        penup
        setxy (:x - :width / 2) (:y - :height / 2)
        pendown
        forward 1
    ]
    hideturtle
end


math.randomseed( os.time() )
colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {}

function love.load()
    wid, hei = love.graphics.getWidth(), love.graphics.getHeight()

    orig[1] = { wid / 2, 3 }
    orig[2] = { 3, hei - 3 }
    orig[3] = { wid - 3, hei - 3 }
    local w, h = math.random( 10, 40 ), math.random( 10, 40 )
    if math.random() < .5 then w = -w end
    if math.random() < .5 then h = -h end
    orig[4] = { wid / 2 + w, hei / 2 + h }

    canvas = love.graphics.newCanvas( wid, hei )
    love.graphics.setCanvas( canvas ); love.graphics.clear()
    love.graphics.setColor( 255, 255, 255 )
    love.graphics.points( orig )
    love.graphics.setCanvas()
end
function love.draw()
    local iter = 100 --> make this number bigger to speed up rendering
    for rp = 1, iter do
        local r, pts = math.random( 6 ), {}
        if r == 1 or r == 4 then
            pt = 1
        elseif r == 2 or r == 5 then
            pt = 2
        else
            pt = 3
        end
        local x, y = ( orig[4][1] + orig[pt][1] ) / 2, ( orig[4][2] + orig[pt][2] ) / 2
        orig[4][1] = x; orig[4][2] = y
        pts[1] = { x, y, colors[pt][1], colors[pt][2], colors[pt][3], 255 }
        love.graphics.setCanvas( canvas )
        love.graphics.points( pts )
    end
    love.graphics.setCanvas()
    love.graphics.draw( canvas )
end


go =>
  Base10 = 10,
  foreach(N in [2,6])
    casting_out_nines(Base10,N)
  end,
  nl,
  Base16 = 16,
  foreach(N in [2,6])
    casting_out_nines(Base16,N)
  end,
  nl.

casting_out_nines(Base,N) =>
  println([base=Base,n=N]),
  C1 = 0,
  C2 = 0,
  Ks = [],
  LimitN = 3,
  foreach(K in 1..Base**N-1)
    C1 := C1 + 1,
    if K mod (Base-1) == (K*K) mod (Base-1) then
      C2 := C2+1,
      if N <= LimitN then
         Ks := Ks ++ [K]
      end
    end
  end,
  if C2 <= 100 then
    println(ks=Ks)
  end,
  printf("Trying %d numbers instead of %d numbers saves %2.3f%%\n", C2, C1, 100 - ((C2/C1)*100)),
  nl.


(de kaprekar (N)
   (let L (cons 0 (chop (* N N)))
      (for ((I . R) (cdr L) R (cdr R))
         (NIL (gt0 (format R)))
         (T (= N (+ @ (format (head I L)))) N) ) ) )

(de co9 (N)
   (until
      (> 9
         (setq N
            (sum
               '((N) (unless (= "9" N) (format N)))
               (chop N) ) ) ) )
   N )

(println 'Part1:)
(println
   (=
      (co9 (+ 6395 1259))
      (co9 (+ (co9 6395) (co9 1259))) ) )

(println 'Part2:)
(println
   (filter
      '((N) (= (co9 N) (co9 (* N N))))
      (range 1 100) ) )
(println
   (filter kaprekar (range 1 100)) )

(println 'Part3 '- 'base17:)
(println
   (filter
      '((N) (= (% N 16) (% (* N N) 16)))
      (range 1 100) ) )

(bye)