require 'set'

class Sokoban
  def initialize(level)
    board = level.each_line.map(&:rstrip)
    @nrows = board.map(&:size).max
    board.map!{|line| line.ljust(@nrows)}
    board.each_with_index do |row, r|
      row.each_char.with_index do |ch, c|
        @px, @py = c, r  if ch == '@' or ch == '+'
      end
    end
    @goal = board.join.tr(' [email protected]#$+*', ' .   ..')
                 .each_char.with_index.select{|ch, c| ch == '.'}
                 .map(&:last)
    @board = board.join.tr(' [email protected]#$+*', '  @#$ $')
  end

  def pos(x, y)
    y * @nrows + x
  end

  def push(x, y, dx, dy, board)         # modify board
    return  if board[pos(x+2*dx, y+2*dy)] != ' '
    board[pos(x     , y     )] = ' '
    board[pos(x + dx, y + dy)] = '@'
    board[pos(x+2*dx, y+2*dy)] = '$'
  end

  def solved?(board)
    @goal.all?{|i| board[i] == '$'}
  end

  DIRS = [[0, -1, 'u', 'U'], [ 1, 0, 'r', 'R'], [0,  1, 'd', 'D'], [-1, 0, 'l', 'L']]
  def solve
    queue = [[@board, "", @px, @py]]
    visited = Set[@board]

    until queue.empty?
      current, csol, x, y = queue.shift

      for dx, dy, cmove, cpush in DIRS
        work = current.dup
        case work[pos(x+dx, y+dy)]      # next character
        when '$'
          next  unless push(x, y, dx, dy, work)
          next  unless visited.add?(work)
          return csol+cpush  if solved?(work)
          queue << [work, csol+cpush, x+dx, y+dy]
        when ' '
          work[pos(x, y)]       = ' '
          work[pos(x+dx, y+dy)] = '@'
          queue << [work, csol+cmove, x+dx, y+dy]  if visited.add?(work)
        end
      end
    end
    "No solution"
  end
end


import java.util.*;

public class HolyKnightsTour {

    final static String[] board = {
        " xxx    ",
        " x xx   ",
        " xxxxxxx",
        "xxx  x x",
        "x x  xxx",
        "1xxxxxx ",
        "  xx x  ",
        "   xxx  "};

    private final static int base = 12;
    private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2},
    {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}};
    private static int[][] grid;
    private static int total = 2;

    public static void main(String[] args) {
        int row = 0, col = 0;

        grid = new int[base][base];

        for (int r = 0; r < base; r++) {
            Arrays.fill(grid[r], -1);
            for (int c = 2; c < base - 2; c++) {
                if (r >= 2 && r < base - 2) {
                    if (board[r - 2].charAt(c - 2) == 'x') {
                        grid[r][c] = 0;
                        total++;
                    }
                    if (board[r - 2].charAt(c - 2) == '1') {
                        row = r;
                        col = c;
                    }
                }
            }
        }

        grid[row][col] = 1;

        if (solve(row, col, 2))
            printResult();
    }

    private static boolean solve(int r, int c, int count) {
        if (count == total)
            return true;

        List<int[]> nbrs = neighbors(r, c);

        if (nbrs.isEmpty() && count != total)
            return false;

        Collections.sort(nbrs, (a, b) -> a[2] - b[2]);

        for (int[] nb : nbrs) {
            r = nb[0];
            c = nb[1];
            grid[r][c] = count;
            if (solve(r, c, count + 1))
                return true;
            grid[r][c] = 0;
        }

        return false;
    }

    private static List<int[]> neighbors(int r, int c) {
        List<int[]> nbrs = new ArrayList<>();

        for (int[] m : moves) {
            int x = m[0];
            int y = m[1];
            if (grid[r + y][c + x] == 0) {
                int num = countNeighbors(r + y, c + x) - 1;
                nbrs.add(new int[]{r + y, c + x, num});
            }
        }
        return nbrs;
    }

    private static int countNeighbors(int r, int c) {
        int num = 0;
        for (int[] m : moves)
            if (grid[r + m[1]][c + m[0]] == 0)
                num++;
        return num;
    }

    private static void printResult() {
        for (int[] row : grid) {
            for (int i : row) {
                if (i == -1)
                    System.out.printf("%2s ", ' ');
                else
                    System.out.printf("%2d ", i);
            }
            System.out.println();
        }
    }
}


(ns socket-example
  (:import (java.net Socket)
           (java.io PrintWriter)))

(defn send-data [host msg]
  (with-open [sock (Socket. host 256)
              printer (PrintWriter. (.getOutputStream sock))]
    (.println printer msg)))

(send-data "localhost" "hello socket world")


CL-USER> (usocket:with-client-socket (socket stream "localhost" 256)
           (write-line "hello socket world" stream)
           (values))
; No value


module socket ;
import std.stdio ;
import std.socket ;
version(Win32) {
  // For Win32 systems, need to link with ws2_32.lib.
  pragma(lib, "ws2_32.lib") ;
}
void main() {
  long res;
  auto socket = new Socket(AddressFamily.INET, SocketType.STREAM) ;
  socket.connect(new InternetAddress("localhost",256)) ;
  res = socket.send(cast(void[])"hello socket world") ;
  writefln("Socket %d bytes sent.", res) ;
  socket.close() ;
}


package require Tcl 8.5

proc solveSokoban b {
    set cols [string length [lindex $b 0]]
    set dxes [list [expr {-$cols}] $cols -1 1]
    set i 0
    foreach c [split [join $b ""] ""] {
	switch $c {
	    " " {lappend bdc " "}
	    "#" {lappend bdc "#"}
	    "@" {lappend bdc " ";set startplayer $i }
	    "$" {lappend bdc " ";lappend startbox $i}
	    "." {lappend bdc " ";                    lappend targets $i}
	    "+" {lappend bdc " ";set startplayer $i; lappend targets $i}
	    "*" {lappend bdc " ";lappend startbox $i;lappend targets $i}
	}
	incr i
    }
    set q [list [list $startplayer $startbox] {}]
    set store([lindex $q 0]) {}
    for {set idx 0} {$idx < [llength $q]} {incr idx 2} {
	lassign [lindex $q $idx] x boxes
	foreach dir {U D L R} dx $dxes {
	    if {[set x1 [expr {$x + $dx}]] in $boxes} {
		if {[lindex $bdc [incr x1 $dx]] ne " " || $x1 in $boxes} {
		    continue
		}
		set tmpboxes $boxes
		set x1 [expr {$x + $dx}]
		for {set i 0} {$i < [llength $boxes]} {incr i} {
		    if {[lindex $boxes $i] == $x1} {
			lset tmpboxes $i [expr {$x1 + $dx}]
			break
		    }
		}
		if {$dx == 1 || $dx == -1} {
		    set next [list $x1 $tmpboxes]
		} else {
		    set next [list $x1 [lsort -integer $tmpboxes]]
		}
		if {![info exists store($next)]} {
		    if {$targets eq [lindex $next 1]} {
			foreach c [lindex $q [expr {$idx + 1}]] {
			    lassign $c ispush olddir
			    if {$ispush} {
				append solution $olddir
			    } else {
				append solution [string tolower $olddir]
			    }
			}
			return [append solution $dir]
		    }
		    set store($next) {}
		    set nm [lindex $q [expr {$idx + 1}]]
		    lappend q $next
		    lappend q [lappend nm [list 1 $dir]]
		}
	    } elseif {[lindex $bdc $x1] eq " "} {
		set next [list [expr {$x + $dx}] $boxes]
		if {![info exists store($next)]} {
		    set store($next) {}
		    set nm [lindex $q [expr {$idx + 1}]]
		    lappend q $next
		    lappend q [lappend nm [list 0 $dir]]
		}
	    }
	}
    }
    error "no solution"
}


program Sockets;

{$APPTYPE CONSOLE}

uses IdTCPClient;

var
  lTCPClient: TIdTCPClient;
begin
  lTCPClient := TIdTCPClient.Create(nil);
  try
    lTCPClient.Host := '127.0.0.1';
    lTCPClient.Port := 256;
    lTCPClient.Connect;
    lTCPClient.IOHandler.WriteLn('hello socket world');
  finally
    lTCPClient.Free;
  end;
end.


import system'net;
import system'text;
import extensions'text;
import system'io;

public program()
{
    var socket := new Socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    socket.connect("127.0.0.1",256);
    var s := "hello socket world";
    socket.write(AnsiEncoder.toByteArray(0, s.Length, s));
    socket.close()
}


defmodule Sockets do
  require Logger

  def send_message(port, message) do
    {:ok, socket} = :gen_tcp.connect('localhost', port, [])
    :gen_tcp.send(socket, message)
  end
end

Sockets.send_message(256, "hello socket world")


import "/dynamic" for Tuple
import "/llist" for DLinkedList
import "/set" for Set

var Board = Tuple.create("Board", ["cur", "sol", "x", "y"])

class Sokoban {
    construct new(board) {
        _destBoard = ""
        _currBoard = ""
        _nCols = board[0].count
        _playerX = 0
        _playerY = 0
        for (r in 0...board.count) {
            for (c in 0..._nCols) {
                var ch = board[r][c]
                _destBoard = _destBoard + ((ch != "$" && ch != "@") ? ch : " ")
                _currBoard = _currBoard + ((ch != ".") ? ch : " ")
                if (ch == "@") {
                    _playerX = c
                    _playerY = r
                }
            }
        }
    }

    move(x, y, dx, dy, trialBoard) {
        var newPlayerPos = (y + dy) * _nCols  + x + dx
        if (trialBoard[newPlayerPos] != " ") return ""
        var trial = trialBoard.toList
        trial[y * _nCols + x] = " "
        trial[newPlayerPos] = "@"
        return trial.join()
    }

    push(x, y, dx, dy, trialBoard) {
        var newBoxPos = (y + 2 * dy) * _nCols + x + 2 * dx
        if (trialBoard[newBoxPos] != " ") return ""
        var trial = trialBoard.toList
        trial[y * _nCols + x] = " "
        trial[(y + dy) * _nCols + x + dx] = "@"
        trial[newBoxPos] = "$"
        return trial.join("")
    }

    isSolved(trialBoard) {
        for (i in 0...trialBoard.count) {
            if ((_destBoard[i] == ".") != (trialBoard[i] == "$")) return false
        }
        return true
    }

    solve() {
        var dirLabels = [ ["u", "U"], ["r", "R"], ["d", "D"], ["l", "L"] ]
        var dirs = [ [0, -1], [1, 0], [0, 1], [-1, 0] ]
        var history = Set.new()
        history.add(_currBoard)
        var open = DLinkedList.new()
        open.add(Board.new(_currBoard, "", _playerX, _playerY))

        while (!open.isEmpty) {
            var b = open.removeAt(0)
            for (i in 0...dirs.count) {
                var trial = b.cur
                var dx = dirs[i][0]
                var dy = dirs[i][1]

                // are we standing next to a box ?
                if (trial[(b.y + dy) * _nCols + b.x + dx] == "$") {
                    // can we push it ?
                    trial = push(b.x, b.y, dx, dy, trial)
                    if (!trial.isEmpty) {
                        // or did we already try this one ?
                        if (!history.contains(trial)) {
                            var newSol = b.sol + dirLabels[i][1]
                            if (isSolved(trial)) return newSol
                            open.add(Board.new(trial, newSol, b.x + dx, b.y + dy))
                            history.add(trial)
                        }
                    }
                } else { // otherwise try changing position
                    trial = move(b.x, b.y, dx, dy, trial)
                    if (!trial.isEmpty && !history.contains(trial)) {
                        var newSol = b.sol + dirLabels[i][0]
                        open.add(Board.new(trial, newSol, b.x + dx, b.y + dy))
                        history.add(trial)
                    }
                }
            }
        }
        return "No solution"
    }
}

var level = [
    "#######",
    "#     #",
    "#     #",
    "#. #  #",
    "#. $$ #",
    "#.$$  #",
    "#.#  @#",
    "#######"
]
System.print(level.join("\n"))
System.print()
System.print(Sokoban.new(level).solve())


using .Hidato       # Note that the . here means to look locally for the module rather than in the libraries

const holyknight = """
 . 0 0 0 . . . .
 . 0 . 0 0 . . .
 . 0 0 0 0 0 0 0
 0 0 0 . . 0 . 0
 0 . 0 . . 0 0 0
 1 0 0 0 0 0 0 .
 . . 0 0 . 0 . .
 . . . 0 0 0 . . """

const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]

board, maxmoves, fixed, starts = hidatoconfigure(holyknight)
printboard(board, " 0", "  ")
hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1)
printboard(board)


// version 1.1.3

val moves = arrayOf(
    intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1,  2), intArrayOf(1, 2),
    intArrayOf(-2, -1), intArrayOf(-2,  1), intArrayOf( 2, -1), intArrayOf(2, 1)
)

val board1 =
    " xxx    " +
    " x xx   " +
    " xxxxxxx" +
    "xxx  x x" +
    "x x  xxx" +
    "sxxxxxx " +
    "  xx x  " +
    "   xxx  "

val board2 =
    ".....s.x....." +
    ".....x.x....." +
    "....xxxxx...." +
    ".....xxx....." +
    "..x..x.x..x.." +
    "xxxxx...xxxxx" +
    "..xx.....xx.." +
    "xxxxx...xxxxx" +
    "..x..x.x..x.." +
    ".....xxx....." +
    "....xxxxx...." +
    ".....x.x....." +
    ".....x.x....."

fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean {
    if (idx > cnt) return true
    for (i in 0 until moves.size) {
        val x = sx + moves[i][0]
        val y = sy + moves[i][1]
        if ((x in 0 until sz) && (y in 0 until sz) && pz[x][y] == 0) {
            pz[x][y] = idx
            if (solve(pz, sz, x, y, idx + 1, cnt)) return true
            pz[x][y] = 0
        }
    }
    return false
}

fun findSolution(b: String, sz: Int) {
    val pz = Array(sz) { IntArray(sz) { -1 } }
    var x = 0
    var y = 0
    var idx = 0
    var cnt = 0
    for (j in 0 until sz) {
        for (i in 0 until sz) {
            if (b[idx] == 'x') {
                pz[i][j] = 0
                cnt++
            }
            else if (b[idx] == 's') {
                pz[i][j] = 1
                cnt++
                x = i
                y = j
            }
            idx++
        }
    }

    if (solve(pz, sz, x, y, 2, cnt)) {
        for (j in 0 until sz) {
            for (i in 0 until sz) {
                if (pz[i][j] != -1)
                    print("%02d  ".format(pz[i][j]))
                else
                    print("--  ")
            }
            println()
        }
    }
    else println("Cannot solve this puzzle!")
}

fun main(args: Array<String>) {
    findSolution(board1,  8)
    println()
    findSolution(board2, 13)
}


(let ((proc (make-network-process :name "my sock"
                                  :host 'local    ;; or hostname string
                                  :service 256)))
  (process-send-string proc "hello socket world")
  (delete-process proc))


-module(socket).
-export([start/0]).

start() ->
    {ok, Sock} = gen_tcp:connect("localhost", 256,
                                 [binary, {packet, 0}]),
    ok = gen_tcp:send(Sock, "hello socket world"),
    ok = gen_tcp:close(Sock).


"localhost" 256 <inet> utf8 [ "hello socket world" print ] with-client


local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8
local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13
local puzzle, movesCnt, wid = {}, 0, 0
local moves = { { -1, -2 }, {  1, -2 }, { -1,  2 }, {  1,  2 },
                { -2, -1 }, { -2,  1 }, {  2, -1 }, {  2,  1 } }

function isValid( x, y )
    return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 )
end
function solve( x, y, s )
    if s > movesCnt then return true end
    local test, a, b
    for i = 1, #moves do
        test = false
        a = x + moves[i][1]; b = y + moves[i][2]
        if isValid( a, b ) then
            puzzle[a + b * wid - wid] = s
            if solve( a, b, s + 1 ) then return true end
            puzzle[a + b * wid - wid] = 0
        end
    end
    return false
end
function printSolution()
    local lp
    for j = 1, wid do
        for i = 1, wid do
            lp = puzzle[i + j * wid - wid]
            if lp == -1 then io.write( "   " )
            else io.write( string.format( " %.2d", lp ) )
            end
        end
        print()
    end
    print( "\n" )
end
local sx, sy
function fill( pz, w )
    puzzle = {}; wid = w; movesCnt = #pz
    local lp
    for i = 1, #pz do
        lp = pz:sub( i, i )
        if lp == "x" then
            table.insert( puzzle, 0 )
        elseif lp == "." then
            table.insert( puzzle, -1 ); movesCnt = movesCnt - 1
        else
            table.insert( puzzle, 1 )
            sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid )
        end
    end
end
-- [[ entry point ]] --
print( "\n\n" ); fill( p1, p1W );
if solve( sx, sy, 2 ) then printSolution() end
print( "\n\n" ); fill( p2, p2W );
if solve( sx, sy, 2 ) then printSolution() end


using inet

class Socket
{
  public static Void main ()
  {
    sock := TcpSocket()
    sock.connect(IpAddr("localhost"), 256)

    sock.out.printLine("hello socket world")
    sock.out.flush
    sock.close
  }
}


include unix/socket.fs

s" localhost" 256 open-socket

dup s" hello socket world" rot write-socket

close-socket


package main

import (
    "fmt"
    "net"
)

func main() {
    conn, err := net.Dial("tcp", "localhost:256")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer conn.Close()
    _, err = conn.Write([]byte("hello socket world"))
    if err != nil {
        fmt.Println(err)
    }
}


puzzle = "  0 0 0
  0   0 0
  0 0 0 0 0 0 0
0 0 0     0   0
0   0     0 0 0
1 0 0 0 0 0 0
    0 0   0
      0 0 0";
puzzle = StringSplit[puzzle, "\n"];
puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle;
pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, [email protected]}];
pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, [email protected]}];

allpoints = Join[pos1, pos0];
validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]];
g = Graph[UndirectedEdge @@@ validmoves];
e = VertexList[g];
order = FindShortestTour[g][[2]]
Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}]


import sequtils, strformat

const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]]

proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool =

  if idx > count: return true

  var x, y: int
  for move in Moves:
    x = sx + move[0]
    y = sy + move[1]
    if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0:
      pz[x][y] = idx
      if pz.solve(x, y, idx + 1, count): return true
      pz[x][y] = 0

proc findSolution(board: openArray[string]) =
  let sz = board.len
  var pz = newSeqWith(sz, repeat(-1, sz))

  var count = 0
  var x, y: int
  for i in 0..<sz:
    for j in 0..<sz:
      case board[i][j]
      of 'x':
        pz[i][j] = 0
        inc count
      of 's':
        pz[i][j] = 1
        inc count
        (x, y) = (i, j)
      else:
        discard

  if pz.solve(x, y, 2, count):
    for i in 0..<sz:
      for j in 0..<sz:
        if pz[i][j] != -1:
          stdout.write &"{pz[i][j]:02}  "
        else:
          stdout.write "--  "
      stdout.write '\n'

when isMainModule:

  const

    Board1 = [" xxx    ",
              " x xx   ",
              " xxxxxxx",
              "xxx  x x",
              "x x  xxx",
              "sxxxxxx ",
              "  xx x  ",
              "   xxx  "]

    Board2 = [".....s.x.....",
              ".....x.x.....",
              "....xxxxx....",
              ".....xxx.....",
              "..x..x.x..x..",
              "xxxxx...xxxxx",
              "..xx.....xx..",
              "xxxxx...xxxxx",
              "..x..x.x..x..",
              ".....xxx.....",
              "....xxxxx....",
              ".....x.x.....",
              ".....x.x....."]

  Board1.findSolution()
  echo()
  Board2.findSolution()


package KT_Locations;
# A sequence of locations on a 2-D board whose order might or might not
# matter. Suitable for representing a partial tour, a complete tour, or the
# required locations to visit.
use strict;
use overload '""' => "as_string";
use English;
# 'locations' must be a reference to an array of 2-element array references,
# where the first element is the rank index and the second is the file index.
use Class::Tiny qw(N locations);
use List::Util qw(all);

sub BUILD {
    my $self = shift;
    $self->{N} //= 8;
    $self->{N} >= 3 or die "N must be at least 3";
    all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{locations}}
        or die "At least one element of 'locations' is invalid";
    return;
}

sub as_string {
    my $self = shift;
    my %idxs;
    my $idx = 1;
    foreach my $loc (@{$self->locations}) {
        $idxs{join(q{K},@{$loc})} = $idx++;
    }
    my $str;
    {
        my $w = int(log(scalar(@{$self->locations}))/log(10.)) + 2;
        my $fmt = "%${w}d";
        my $N = $self->N;
        my $non_tour = q{ } x ($w-1) . q{-};
        for (my $r=0; $r<$N; $r++) {
            for (my $f=0; $f<$N; $f++) {
                my $k = join(q{K}, $r, $f);
                $str .= exists($idxs{$k}) ? sprintf($fmt, $idxs{$k}) : $non_tour;
            }
            $str .= "\n";
        }
    }
    return $str;
}

sub as_idx_hash {
    my $self = shift;
    my $N = $self->N;
    my $result;
    foreach my $pair (@{$self->locations}) {
        my ($r, $f) = @{$pair};
        $result->{$r * $N + $f}++;
    }
    return $result;
}

package KnightsTour;
use strict;
# If supplied, 'str' is parsed to set 'N', 'start_location', and
# 'locations_to_visit'.  'legal_move_idxs' is for improving performance.
use Class::Tiny qw( N start_location locations_to_visit str legal_move_idxs );
use English;
use Parallel::ForkManager;
use Time::HiRes qw( gettimeofday tv_interval );

sub BUILD {
    my $self = shift;
    if ($self->{str}) {
        my ($n, $sl, $ltv) = _parse_input_string($self->{str});
        $self->{N} = $n;
        $self->{start_location} = $sl;
        $self->{locations_to_visit} = $ltv;
    }
    $self->{N} //= 8;
    $self->{N} >= 3 or die "N must be at least 3";
    exists($self->{start_location}) or die "Must supply start_location";
    die "start_location is invalid"
        if ref($self->{start_location}) ne 'ARRAY' ||
           scalar(@{$self->{start_location}}) != 2;
    exists($self->{locations_to_visit}) or die "Must supply locations_to_visit";
    ref($self->{locations_to_visit}) eq 'KT_Locations'
        or die "locations_to_visit must be a KT_Locations instance";
    $self->{N} == $self->{locations_to_visit}->N
        or die "locations_to_visit has mismatched board size";
    $self->precompute_legal_moves();
    return;
}

sub _parse_input_string {
    my @rows = split(/[\r\n]+/s, shift);
    my $N = scalar(@rows);
    my ($start_location, @to_visit);
    for (my $r=0; $r<$N; $r++) {
        my $row_r = $rows[$r];
        for (my $f=0; $f<$N; $f++) {
            my $c = substr($row_r, $f, 1);
            if ($c eq '1') { $start_location = [$r, $f]; }
            elsif ($c eq '0') { push @to_visit, [$r, $f]; }
        }
    }
    $start_location or die "No starting location provided";
    return ($N,
            $start_location,
            KT_Locations->new(N => $N, locations => \@to_visit));
}

sub precompute_legal_moves {
    my $self = shift;
    my $N = $self->{N};
    my $ktl_ixs = $self->{locations_to_visit}->as_idx_hash();
    for (my $r=0; $r<$N; $r++) {
        for (my $f=0; $f<$N; $f++) {
            my $k = $r * $N + $f;
            $self->{legal_move_idxs}->{$k} =
                _precompute_legal_move_idxs($r, $f, $N, $ktl_ixs);
        }
    }
    return;
}

sub _precompute_legal_move_idxs {
    my ($r, $f, $N, $ktl_ixs) = @ARG;
    my $r_plus_1  = $r + 1;  my $r_plus_2 = $r + 2;
    my $r_minus_1 = $r - 1;  my $r_minus_2 = $r - 2;
    my $f_plus_1  = $f + 1;  my $f_plus_2 = $f + 2;
    my $f_minus_1 = $f - 1;  my $f_minus_2 = $f - 2;
    my @result = grep { exists($ktl_ixs->{$ARG}) }
                 map { $ARG->[0] * $N + $ARG->[1] }
                 grep {$ARG->[0] >= 0 && $ARG->[0] < $N &&
                       $ARG->[1] >= 0 && $ARG->[1] < $N}
                      ([$r_plus_2,  $f_minus_1], [$r_plus_2,  $f_plus_1],
                       [$r_minus_2, $f_minus_1], [$r_minus_2, $f_plus_1],
                       [$r_plus_1,  $f_plus_2],  [$r_plus_1,  $f_minus_2],
                       [$r_minus_1, $f_plus_2],  [$r_minus_1, $f_minus_2]);
    return \@result;
}

sub find_tour {
    my $self = shift;
    my $num_to_visit = scalar(@{$self->locations_to_visit->locations});
    my $N = $self->N;
    my $start_loc_idx =
        $self->start_location->[0] * $N + $self->start_location->[1];
    my $visited;  for (my $i=0; $i<$N*$N; $i++) { vec($visited, $i, 1) = 0; }
    vec($visited, $start_loc_idx, 1) = 1;
    # We unwind the search by one level and use Parallel::ForkManager to search
    # the top-level sub-trees concurrently, assuming there are enough cores.
    my @next_loc_idxs = @{$self->legal_move_idxs->{$start_loc_idx}};
    my $pm = new Parallel::ForkManager(scalar(@next_loc_idxs));
    foreach my $next_loc_idx (@next_loc_idxs) {
        $pm->start and next;  # Do the fork
        my $t0 = [gettimeofday];
        vec($visited, $next_loc_idx, 1) = 1;  # (The fork cloned $visited.)
        my $tour = _find_tour_helper($N,
                                     $num_to_visit - 1,
                                     $next_loc_idx,
                                     $visited,
                                     $self->legal_move_idxs);
        my $elapsed = tv_interval($t0);
        my ($r, $f) = _idx_to_rank_and_file($next_loc_idx, $N);
        if (defined $tour) {
            my @tour_locs =
                map { [_idx_to_rank_and_file($ARG, $N)] }
                    ($start_loc_idx, $next_loc_idx, split(/\s+/s, $tour));
            my $kt_locs = KT_Locations->new(N => $N, locations => \@tour_locs);
            print "Found a tour after first move ($r, $f) ",
                  "in $elapsed seconds:\n", $kt_locs, "\n";
        }
        else {
            print "No tour found after first move ($r, $f). ",
                  "Took $elapsed seconds.\n";
        }
        $pm->finish; # Do the exit in the child process
    }
    $pm->wait_all_children;
    return;
}

sub _idx_to_rank_and_file {
    my ($idx, $N) = @ARG;
    my $f = $idx % $N;
    my $r = ($idx - $f) / $N;
    return ($r, $f);
}

sub _find_tour_helper {
    my ($N, $num_to_visit, $current_loc_idx, $visited, $legal_move_idxs) = @ARG;

    # The performance hot spot.
    local *inner_helper = sub {
        my ($num_to_visit, $current_loc_idx, $visited) = @ARG;
        if ($num_to_visit == 0) {
            return q{ };  # Solution found.
        }
        my @next_loc_idxs = @{$legal_move_idxs->{$current_loc_idx}};
        my $num_to_visit2 = $num_to_visit - 1;
        foreach my $loc_idx2 (@next_loc_idxs) {
            next if vec($visited, $loc_idx2, 1);
            my $visited2 = $visited;
            vec($visited2, $loc_idx2, 1) = 1;
            my $recursion = inner_helper($num_to_visit2, $loc_idx2, $visited2);
            return $loc_idx2 . q{ } . $recursion if defined $recursion;
        }
        return;
    };

    return inner_helper($num_to_visit, $current_loc_idx, $visited);
}

package main;
use strict;

solve_size_8_problem();
solve_size_13_problem();
exit 0;

sub solve_size_8_problem {
    my $problem = <<"END_SIZE_8_PROBLEM";
--000---
--0-00--
-0000000
000--0-0
0-0--000
1000000-
--00-0--
---000--
END_SIZE_8_PROBLEM
    my $kt = KnightsTour->new(str => $problem);
    print "Finding a tour for an 8x8 problem...\n";
    $kt->find_tour();
    return;
}

sub solve_size_13_problem {
    my $problem = <<"END_SIZE_13_PROBLEM";
-----1-0-----
-----0-0-----
----00000----
-----000-----
--0--0-0--0--
00000---00000
--00-----00--
00000---00000
--0--0-0--0--
-----000-----
----00000----
-----0-0-----
-----0-0-----
END_SIZE_13_PROBLEM
    my $kt = KnightsTour->new(str => $problem);
    print "Finding a tour for a 13x13 problem...\n";
    $kt->find_tour();
    return;
}


s = new java.net.Socket("localhost", 256)
s << "hello socket world"
s.close()


import Network

main = withSocketsDo $ sendTo "localhost" (PortNumber $ toEnum 256) "hello socket world"


link cfunc
procedure main ()
   hello("localhost", 1024)
end

procedure hello (host, port)
   write(tconnect(host, port) | stop("unable to connect to", host, ":", port) ,  "hello socket world")
end


socket, unit, 'localhost',256,/get_lun
printf,unit,"hello socket world"
close, unit


with javascript_semantics
sequence board, warnsdorffs

integer size, limit, nchars
string fmt, blank

constant ROW = 1, COL = 2,
         moves = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}}

function onboard(integer row, integer col)
    return row>=1 and row<=size and col>=nchars and col<=nchars*size
end function

procedure init_warnsdorffs()
    for row=1 to size do
        for col=nchars to nchars*size by nchars do
            for move=1 to length(moves) do
                integer nrow = row+moves[move][ROW],
                        ncol = col+moves[move][COL]*nchars
                if onboard(nrow,ncol) then
                    warnsdorffs[nrow][ncol] += 1
                end if
            end for
        end for
    end for
end procedure

atom t0 = time(),
     t1 = time()+1
integer tries = 0, backtracks = 0
function solve(integer row, integer col, integer n)
    if time()>t1 and platform()!=JS then
        ?{row,floor(col/nchars),n,tries}
        puts(1,join(board,"\n")&"\n")
        t1 = time()+1
    end if
    tries+= 1
    if n>limit then return 1 end if
    sequence wmoves = {}
    integer nrow, ncol
    for move=1 to length(moves) do
        nrow = row+moves[move][ROW]
        ncol = col+moves[move][COL]*nchars
        if onboard(nrow,ncol)
        and board[nrow][ncol]=' ' then
            wmoves = append(wmoves,{warnsdorffs[nrow][ncol],nrow,ncol})
        end if
    end for
    wmoves = sort(wmoves)
    -- avoid creating orphans
    if length(wmoves)<2 or wmoves[2][1]>1 then
        for m=1 to length(wmoves) do
            {?,nrow,ncol} = wmoves[m]
            warnsdorffs[nrow][ncol] -= 1
        end for
        for m=1 to length(wmoves) do
            {?,nrow,ncol} = wmoves[m]
            integer scol = ncol-nchars+1
            board[nrow][scol..ncol] = sprintf(fmt,n)
            if solve(nrow,ncol,n+1) then return 1 end if
            backtracks += 1
            board[nrow][scol..ncol] = blank
        end for
        for m=1 to length(wmoves) do
            {?,nrow,ncol} = wmoves[m]
            warnsdorffs[nrow][ncol] += 1
        end for
    end if
    return 0
end function

procedure holyknight(sequence s)
    s = split(s,'\n')
    size = length(s)
    nchars = length(sprintf(" %d",size*size))
    fmt = sprintf(" %%%dd",nchars-1)
    blank = repeat(' ',nchars)
    board = repeat(repeat(' ',size*nchars),size)
    limit = 1
    integer sx, sy
    for x=1 to size do
        integer y = nchars
        for j=1 to size do
            integer ch = iff(j>length(s[x])?'-':s[x][j])
            if ch=' ' then
                ch = '-'
            elsif ch='0' then
                ch = ' '
                limit += 1
            elsif ch='1' then
                sx = x
                sy = y
            end if
            board[x][y] = ch
            y += nchars
        end for
    end for
    warnsdorffs = repeat(repeat(0,size*nchars),size)
    init_warnsdorffs()
    t0 = time()
    tries = 0
    backtracks = 0
    t1 = time()+1
    if solve(sx,sy,2) then
        puts(1,join(board,"\n"))
        printf(1,"\nsolution found in %d tries, %d backtracks (%3.2fs)\n",{tries,backtracks,time()-t0})
    else
        puts(1,"no solutions found\n")
    end if
end procedure

constant board1 = """
 000
 0 00
 0000000
000  0 0
0 0  000
1000000
  00 0
   000"""

holyknight(board1)

constant board2 = """
-----1-0-----
-----0-0-----
----00000----
-----000-----
--0--0-0--0--
00000---00000
--00-----00--
00000---00000
--0--0-0--0--
-----000-----
----00000----
-----0-0-----
-----0-0-----"""

if platform()!=JS then
    holyknight(board2)
end if

{} = wait_key()


   coinsert'jsocket' [ require 'socket'             NB.  Sockets library
   socket =.  >{.sdcheck sdsocket''                 NB.  Open a socket
   host   =. sdcheck sdgethostbyname 'localhost'    NB.  Resolve host
   sdcheck sdconnect socket ; host ,< 256           NB.  Create connection to port 256
   sdcheck 'hello socket world' sdsend socket , 0   NB.  Send msg


import java.io.IOException;
import java.net.*;
public class SocketSend {
  public static void main(String args[]) throws IOException {
    sendData("localhost", "hello socket world");
  }

  public static void sendData(String host, String msg) throws IOException {
    Socket sock = new Socket( host, 256 );
    sock.getOutputStream().write(msg.getBytes());
    sock.getOutputStream().flush();
    sock.close();
  }
}


#!/usr/bin/env jsish
function sockets() {
    var sock = new Socket({client:true, port:256, noAsync:true, udp:true});
    sock.send(-1, 'hello socket world');
    sock.close();
}

;sockets();

/*
=!EXPECTSTART!=
sockets() ==> undefined
=!EXPECTEND!=
*/


import sat.

main =>
    S = {".000....",
         ".0.00...",
         ".0000000",
         "000..0.0",
         "0.0..000",
         "1000000.",
         "..00.0..",
         "...000.."},
    MaxR = len(S),
    MaxC = len(S[1]),
    M = new_array(MaxR,MaxC),
    StartR = _,    % make StartR and StartC global
    StartC = _,
    foreach (R in 1..MaxR)
        fill_row(R, S[R], M[R], 1, StartR, StartC)
    end,
    NZeros = len([1 : R in 1..MaxR, C in 1..MaxC, M[R,C] == 0]),
    M :: 0..MaxR*MaxC-NZeros,
    Vs = [{(R,C),1} : R in 1..MaxR, C in 1..MaxC, M[R,C] !== 0],
    Es = [{(R,C),(R1,C1),_} : R in 1..MaxR, C in 1..MaxC, M[R,C] !== 0,
                              neibs(M,MaxR,MaxC,R,C,Neibs),
                              (R1,C1) in Neibs, M[R1,C1] !== 0],
    hcp(Vs,Es),
    foreach ({(R,C),(R1,C1),B} in Es)
        B #/\ (R1 #!= StartR #\/ C1 #!= StartC) #=> M[R1,C1] #= M[R,C]+1
    end,
    solve(M),
    foreach (R in 1..MaxR)
        foreach (C in 1..MaxC)
            if M[R,C] == 0 then
                printf("%4c", '.')
            else
                printf("%4d", M[R,C])
            end
        end,
        nl
    end.

neibs(M,MaxR,MaxC,R,C,Neibs) =>
    Connected = [(R+1, C+2),
                 (R+1, C-2),
                 (R-1, C+2),
                 (R-1, C-2),
                 (R+2, C+1),
                 (R+2, C-1),
                 (R-2, C+1),
                 (R-2, C-1)],
    Neibs = [(R1,C1) : (R1,C1) in Connected,
                       R1 >= 1, R1 =< MaxR, C1 >= 1, C1 =< MaxC,
                       M[R1,C1] !== 0].

fill_row(_R, [], _Row, _C, _StartR, _StartC) => true.
fill_row(R, ['.'|Str], Row, C, StartR, StartC) =>
    Row[C] = 0,
    fill_row(R,Str, Row, C+1, StartR, StartC).
fill_row(R, ['0'|Str], Row, C, StartR, StartC) =>
    fill_row(R, Str, Row, C+1, StartR, StartC).
fill_row(R, ['1'|Str], Row, C, StartR, StartC) =>
    Row[C] = 1,
    StartR = R,
    StartC = C,
    fill_row(R, Str, Row, C+1, StartR, StartC).


from sys import stdout
moves = [
    [-1, -2], [1, -2], [-1, 2], [1, 2],
    [-2, -1], [-2, 1], [2, -1], [2, 1]
]

def solve(pz, sz, sx, sy, idx, cnt):
    if idx > cnt:
        return 1

    for i in range(len(moves)):
        x = sx + moves[i][0]
        y = sy + moves[i][1]
        if sz > x > -1 and sz > y > -1 and pz[x][y] == 0:
            pz[x][y] = idx
            if 1 == solve(pz, sz, x, y, idx + 1, cnt):
                return 1
            pz[x][y] = 0

    return 0

def find_solution(pz, sz):
    p = [[-1 for j in range(sz)] for i in range(sz)]
    idx = x = y = cnt = 0
    for j in range(sz):
        for i in range(sz):
            if pz[idx] == "x":
                p[i][j] = 0
                cnt += 1
            elif pz[idx] == "s":
                p[i][j] = 1
                cnt += 1
                x = i
                y = j
            idx += 1

    if 1 == solve(p, sz, x, y, 2, cnt):
        for j in range(sz):
            for i in range(sz):
                if p[i][j] != -1:
                    stdout.write(" {:0{}d}".format(p[i][j], 2))
                else:
                    stdout.write("   ")
            print()
    else:
        print("Cannot solve this puzzle!")

# entry point
find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8)
print()
find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)


F divisors(n)
   V divs = [1]
   L(ii) 2 .< Int(n ^ 0.5) + 3
      I n % ii == 0
         divs.append(ii)
         divs.append(Int(n / ii))
   divs.append(n)
   R Array(Set(divs))

F is_prime(n)
   R divisors(n).len == 2

F digit_check(n)
   I String(n).len < 2
      R 1B
   E
      L(digit) String(n)
         I !is_prime(Int(digit))
            R 0B
      R 1B

F sequence(max_n)
   V ii = 0
   V n = 0
   [Int] r
   L
      ii++
      I is_prime(ii)
         I n > max_n
            L.break
         I digit_check(ii)
            n++
            r.append(ii)
   R r

V seq = sequence(100)
print(‘First 25 SPDS primes:’)
L(item) seq[0.<25]
   print(item, end' ‘ ’)
print()
print(‘Hundredth SPDS prime: ’seq[99])


socket = connect("localhost",256)
write(socket, "hello socket world")
close(socket)


// version 1.2.21

import java.net.Socket

fun main(args: Array<String>) {
    val sock = Socket("localhost", 256)
    sock.use {
        it.outputStream.write("hello socket world".toByteArray())
    }
}


local(net) = net_tcp
#net->connect('127.0.0.1',256)
#net->dowithclose => {
    #net->writestring('Hello World')
}


socket = require "socket"
host, port = "127.0.0.1", 256

sid = socket.udp()
sid:sendto( "hello socket world", host, port )
sid:close()


my @adjacent =
               [ -2, -1],  [ -2, 1],
      [-1,-2],                       [-1,+2],
      [+1,-2],                       [+1,+2],
               [ +2, -1],  [ +2, 1];

put "\n" xx 60;

solveboard q:to/END/;
    . 0 0 0
    . 0 . 0 0
    . 0 0 0 0 0 0 0
    0 0 0 . . 0 . 0
    0 . 0 . . 0 0 0
    1 0 0 0 0 0 0
    . . 0 0 . 0
    . . . 0 0 0
    END

sub solveboard($board) {
    my $max = +$board.comb(/\w+/);
    my $width = $max.chars;

    my @grid;
    my @known;
    my @neigh;
    my @degree;

    @grid = $board.lines.map: -> $line {
        [ $line.words.map: { /^_/ ?? 0 !! /^\./ ?? Rat !! $_ } ]
    }

    sub neighbors($y,$x --> List) {
        eager gather for @adjacent {
            my $y1 = $y + .[0];
            my $x1 = $x + .[1];
            take [$y1,$x1] if defined @grid[$y1][$x1];
        }
    }

    for ^@grid -> $y {
        for ^@grid[$y] -> $x {
            if @grid[$y][$x] -> $v {
                @known[$v] = [$y,$x];
            }
            if @grid[$y][$x].defined {
                @neigh[$y][$x] = neighbors($y,$x);
                @degree[$y][$x] = +@neigh[$y][$x];
            }
        }
    }
    print "\e[0H\e[0J";

    my $tries = 0;

    try_fill 1, @known[1];

    sub try_fill($v, $coord [$y,$x] --> Bool) {
        return True if $v > $max;
        $tries++;

        my $old = @grid[$y][$x];

        return False if +$old and $old != $v;
        return False if @known[$v] and @known[$v] !eqv $coord;

        @grid[$y][$x] = $v;               # conjecture grid value

        print "\e[0H";                    # show conjectured board
        for @grid -> $r {
            say do for @$r {
                when Rat { ' ' x $width }
                when 0   { '_' x $width }
                default  { .fmt("%{$width}d") }
            }
        }

        my @neighbors = @neigh[$y][$x][];

        my @degrees;
        for @neighbors -> \n [$yy,$xx] {
            my $d = --@degree[$yy][$xx];  # conjecture new degrees
            push @degrees[$d], n;         # and categorize by degree
        }

        for @degrees.grep(*.defined) -> @ties {
            for @ties.reverse {           # reverse works better for this hidato anyway
                return True if try_fill $v + 1, $_;
            }
        }

        for @neighbors -> [$yy,$xx] {
            ++@degree[$yy][$xx];          # undo degree conjectures
        }

        @grid[$y][$x] = $old;             # undo grid value conjecture
        return False;
    }

    say "$tries tries";
}


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

BYTE FUNC IsZero(REAL POINTER a)
  CHAR ARRAY s(10)

  StrR(a,s)
  IF s(0)=1 AND s(1)='0 THEN
    RETURN (1)
  FI
RETURN (0)

CARD FUNC MyMod(CARD a,b)
  REAL ar,br,dr
  CARD d,m

  IF a>32767 THEN
    ;Built-in DIV and MOD
    ;do not work properly
    ;for numbers greater than 32767
    IntToReal(a,ar)
    IntToReal(b,br)
    RealDiv(ar,br,dr)
    d=RealToInt(dr)
    m=a-d*b
  ELSE
    m=a MOD b
  FI
RETURN (m)

BYTE FUNC IsPrime(CARD a)
  CARD i

  IF a<=1 THEN
    RETURN (0)
  FI

  i=2
  WHILE i*i<=a
  DO
    IF MyMod(a,i)=0 THEN
      RETURN (0)
    FI
    i==+1
  OD
RETURN (1)

BYTE FUNC AllDigitsArePrime(CARD a)
  BYTE i
  CHAR ARRAY s
  CHAR c

  StrC(a,s)
  FOR i=1 TO s(0)
  DO
    c=s(i)
    IF c#'2 AND c#'3 AND c#'5 AND c#'7 THEN
      RETURN (0)
    FI
  OD
RETURN (1)

PROC Main()
  BYTE count
  CARD a

  Put(125) PutE() ;clear screen
  PrintE("Sequence from 1st to 25th:")
  count=0 a=1
  DO
    IF AllDigitsArePrime(a)=1 AND IsPrime(a)=1 THEN
      count==+1
      IF count<=25 THEN
        PrintC(a) Put(32)
      ELSEIF count=100 THEN
        PrintF("%E%E100th: %U%E",a)
        EXIT
      FI
    FI
    a==+1
  OD
RETURN


# find elements of the Smarandache prime-digital sequence - primes whose    #
# digits are all primes                                                     #
# Uses the observations that the final digit of 2 or more digit Smarandache #
# primes must be 3 or 7 and the only prime digits are 2, 3, 5 and 7         #
# Needs --heap 256m for Algol 68G                                           #
BEGIN
    # construct a sieve of primes up to 10 000 000                          #
    INT prime max = 10 000 000;
    [ prime max ]BOOL prime; FOR i TO UPB prime DO prime[ i ] := TRUE OD;
    FOR s FROM 2 TO ENTIER sqrt( prime max ) DO
        IF prime[ s ] THEN
            FOR p FROM s * s BY s TO prime max DO prime[ p ] := FALSE OD
        FI
    OD;
    # consruct the Smarandache primes up to 10 000 000                      #
    [ prime max ]BOOL smarandache; FOR i TO UPB prime DO smarandache[ i ] := FALSE OD;
    [   ]INT prime digits = ( 2, 3, 5, 7 );
    [ 7 ]INT digits      := ( 0, 0, 0, 0, 0, 0, 0 );
    # tests whether the current digits form a Smarandache prime             #
    PROC try smarandache = VOID:
         BEGIN
            INT possible prime := 0;
            FOR i TO UPB digits DO
                possible prime *:= 10 +:= digits[ i ]
            OD;
            smarandache[ possible prime ] := prime[ possible prime ]
         END # try smarandache # ;
    # tests whether the current digits plus 3 or 7 form a Smarandache prime #
    PROC try smarandache 3 or 7 = VOID:
         BEGIN
            digits[ UPB digits ] := 3;
            try smarandache;
            digits[ UPB digits ] := 7;
            try smarandache
         END # try smarandache 3 or 7 # ;
    # the 1 digit primes are all Smarandache primes                         #
    FOR d7 TO UPB prime digits DO smarandache[ prime digits[ d7 ] ] := TRUE OD;
    # try the possible 2, 3, etc. digit numbers composed of prime digits    #
    FOR d6 TO UPB prime digits DO
        digits[ 6 ] := prime digits[ d6 ];
        try smarandache 3 or 7;
        FOR d5 TO UPB prime digits DO
            digits[ 5 ] := prime digits[ d5 ];
            try smarandache 3 or 7;
            FOR d4 TO UPB prime digits DO
                digits[ 4 ] := prime digits[ d4 ];
                try smarandache 3 or 7;
                FOR d3 TO UPB prime digits DO
                    digits[ 3 ] := prime digits[ d3 ];
                    try smarandache 3 or 7;
                    FOR d2 TO UPB prime digits DO
                        digits[ 2 ] := prime digits[ d2 ];
                        try smarandache 3 or 7;
                        FOR d1 TO UPB prime digits DO
                            digits[ 1 ] := prime digits[ d1 ];
                            try smarandache 3 or 7
                        OD;
                        digits[ 1 ] := 0
                    OD;
                    digits[ 2 ] := 0
                OD;
                digits[ 3 ] := 0
            OD;
            digits[ 4 ] := 0
        OD;
        digits[ 5 ] := 0
    OD;
    # print some Smarandache primes                                           #
    INT count  := 0;
    INT s100   := 0;
    INT s1000  := 0;
    INT s last := 0;
    INT p last := 0;
    print( ( "First 25 Smarandache primes:", newline ) );
    FOR i TO UPB smarandache DO
        IF smarandache[ i ] THEN
            count +:= 1;
            s last := i;
            p last := count;
            IF count <= 25 THEN
                print( ( " ", whole( i, 0 ) ) )
            ELIF count = 100 THEN
                s100  := i
            ELIF count = 1000 THEN
                s1000 := i
            FI
        FI
    OD;
    print( ( newline ) );
    print( ( "100th Smarandache prime: ", whole( s100, 0 ), newline ) );
    print( ( "1000th Smarandache prime: ", whole( s1000, 0 ), newline ) );
    print( ( "Largest Smarandache prime under "
           , whole( prime max, 0 )
           , ": "
           , whole( s last, 0 )
           , " (Smarandache prime "
           , whole( p last, 0 )
           , ")"
           , newline
           )
         )
END


        TITLE SOCKET

COMMENT !

    Socket Example ** PDP-10 Assembly Language (KJX 2022)
     Assembler: MACRO-10    Operating System: TOPS-20 V7

  On TOPS-20, TCP-connections are made by opening a special
  file on the "TCP:" device (in this case "TCP:256"). Apart
  from the funky filename, there is virtually no difference
  between opening files on disk and creating TCP-connections
  or endpoints, so we go through the usual sequence of GTJFN
  (= get file-handle), OPENF (open file), finally followed
  by CLOSF (close file).

!

        SEARCH MONSYM,MACSYM            ;Load symbolic names for syscalls.
        .REQUIRE SYS:MACREL

        STDAC.                          ;Define standard register names.

JFN:    BLOCK 1                         ;File handle for TCP connection.
TCPFN:  ASCIZ /TCP:256/                 ;TCP "filename"
STR:    ASCIZ /Hello World!/            ;String to send.
STRLEN= <.-STR>*5                       ;Length of string.

GO::    RESET%                          ;Initialize process.

        ;; Get a file-handle (JFN) for the TCP-connection:

        MOVX  T1,GJ%SHT                 ;Do "short" GTJFN% call.
        HRROI T2,TCPFN                  ;TCP "filename" into T2.
        GTJFN%                          ;Get file-handle.
          ERJMPS ERROR                  ;  Handle errors.
        MOVEM T1,JFN                    ;Store JFN we got.

        ;; Open the "file":

        HRRZ  T1,JFN                    ;File-handle without flags into T1.
        MOVX  T2,FLD(8,OF%BSZ)!OF%RD!OF%WR  ;8bit bytes, read+write.
        OPENF%                          ;Open file.
          ERJMPS ERROR                  ;  Handle errors.

        ;; Write the string.

        MOVE  T1,JFN                    ;File-handle into T1.
        HRROI T2,STR                    ;String-pointer into T2.
        MOVEI T3,STRLEN                 ;Length of string into T3.
        SOUT%                           ;Write string.
          ERJMPS ERROR                  ;  Handle errors.

        ;; Close file.

        HRRZ  T1,JFN                    ;Get file-handle into T1.
        CLOSF%                          ;Close file.
          ERJMPS ERROR                  ;  Handle errors.

        ;; End program.

        RESET%                          ;Reset, to release JFN.
        HALTF%                          ;Halt program.
        JRST  GO                        ;Allow for continue-command.

        ;;
        ;; ERROR: Print standardized error-message by means of ERSTR.
        ;;        This is similar to perror() in C.
        ;;

ERROR:  MOVEI T1,.PRIOU                 ;Print on standard output.
        MOVE  T2,[.FHSLF,,-1]           ;Own process, last error.
        SETZ  T3                        ;No length-limit on error msg.
        ERSTR%                          ;Print error-message.
          JFCL                          ;  Ignore errors from ERSTR%.
          JFCL                          ;  Dito.
        RESET%                          ;Reset, to release JFN.
        HALTF%                          ;Halt program.
        JRST  GO                        ;Allow for continue-command.

        END GO


socket = SocketConnect["localhost:256", "TCP"];
WriteString[socket, "hello socket world"];
Close[socket];


use std

const main = {
	match std.dial("tcp!localhost!256")
	| `std.Ok fd:
		std.write(fd, "hello socket world")
		std.close(fd)
	| `std.Err err:
		std.fatal("could not open fd: {}\n", err)
	;;
}


import Nanoquery.Net

p = new(Port)
p.connect("localhost", 256)
p.write("hello socket world")
p.close()


/**
 Sockets in Neko
 Tectonics:
   nekoc sockets.neko
   sudo nc -vulp 256 & sudo neko sockets
*/

var socket_init = $loader.loadprim("[email protected]_init", 0);
var socket_new = $loader.loadprim("[email protected]_new", 1);
var host_resolve = $loader.loadprim("[email protected]_resolve", 1);
var socket_connect = $loader.loadprim("[email protected]_connect", 3);
var socket_write = $loader.loadprim("[email protected]_write", 2);
var socket_close = $loader.loadprim("[email protected]_close", 1);

/* Initialize Neko socket API */
socket_init();

/* true; UDP, false; TCP */
var socket = socket_new(true);

var c = socket_connect(socket, host_resolve("localhost"), 256);
socket_write(socket, "hello socket world");

socket_close(socket);


/*REXX program solves the  holy knight's tour  problem for a (general)  NxN  chessboard.*/
blank=pos('//', space(arg(1), 0))\==0            /*see if the pennies are to be shown.  */
parse arg  ops   '/'   cent                      /*obtain the options and the pennies.  */
parse var  ops  N  sRank  sFile .                /*boardsize, starting position, pennys.*/
if     N=='' |     N==","  then     N=8          /*no boardsize specified?  Use default.*/
if sRank=='' | sRank==","  then sRank=N          /*starting rank given?      "      "   */
if sFile=='' | sFile==","  then sFile=1          /*    "    file   "         "      "   */
NN=N**2;  NxN='a ' N"x"N ' chessboard'           /*file  [↓]          [↓]   r=rank      */
@.=;              do r=1  for N;  do f=1  for N;   @.r.f=.;    end /*f*/;        end /*r*/
                                                 /*[↑]  create an empty  NxN chessboard.*/
cent=space( translate( cent, , ',') )            /*allow use of comma (,) for separater.*/
cents=0                                          /*number of pennies on the chessboard. */
       do  while  cent\=''                       /* [↓]  possibly place the pennies.    */
       parse var  cent   cr  cf  x  '/'  cent    /*extract where to place the pennies.  */
       if x=''   then x=1                        /*if number not specified, use 1 penny.*/
       if cr=''  then iterate                    /*support the  "blanking"  option.     */
                               do cf=cf  for x   /*now, place  X  pennies on chessboard.*/
                               @.cr.cf= '¢'      /*mark chessboard position with a penny*/
                               end   /*cf*/      /* [↑]  places X pennies on chessboard.*/
       end   /*while*/                           /* [↑]  allows of the placing of  X  ¢s*/
                                                 /* [↓]  traipse through the chessboard.*/
    do r=1  for N;  do f=1  for N;  cents=cents + (@.r.f=='¢');   end /*f*/;     end /*r*/
                                                 /* [↑]  count the number of pennies.   */
if cents\==0  then say cents   'pennies placed on chessboard.'
target=NN - cents                                /*use this as the number of moves left.*/
                   Kr = '2 1 -1 -2 -2 -1  1  2'  /*the legal "rank"  moves for a knight.*/
                   Kf = '1 2  2  1 -1 -2 -2 -1'  /* "    "   "file"    "    "  "    "   */
kr.M=words(Kr)                                   /*number of possible moves for a Knight*/
parse var Kr  Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8   /*parse the legal moves by hand.*/
parse var Kf  Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8   /*  "    "    "     "    "   "  */
beg= '-1-'                                       /* [↑]   create the  NxN  chessboard.  */
if @.sRank.sFile ==.    then @.sRank.sFile=beg   /*the knight's starting position.      */
if @.sRank.sFile\==beg  then do    sRank=1  for N   /*find starting rank for the knight.*/
                                do sFile=1  for N   /*  "     "     file  "   "     "   */
                                if @.sRank.sFile\==.  then iterate
                                @.sRank.sFile=beg   /*the knight's starting position.   */
                                leave sRank         /*we have a spot, so leave all this.*/
                                end   /*sFile*/
                             end      /*sRank*/
@hkt= "holy knight's tour"                       /*a handy─dandy literal for the  SAYs. */
if \move(2,sRank,sFile)  &  \(N==1)  then say 'No'    @hkt    "solution for"        NxN'.'
                                     else say 'A solution for the'   @hkt   "on"    NxN':'

                                                 /*show chessboard with moves and coins.*/
!=left('', 9 * (n<18) );           say           /*used for indentation of chessboard.  */
_=substr( copies("┼───", N), 2);   say  ! translate('┌'_"┐", '┬', "┼")
     do   r=N  for N  by -1;       if r\==N      then say ! '├'_"┤";     [email protected].
       do f=1  for N; [email protected].r.f;     if ?==target  then ?='end';           L=L'│'center(?,3)
       end      /*f*/
     if blank then L=translate(L,,'¢')           /*blank out the pennies on chessboard ?*/
     say !  translate(L'│', , .)                 /*display  a  rank of the  chessboard. */
     end        /*r*/                            /*19x19 chessboard can be shown 80 cols*/
say  !  translate('└'_"┘", '┴', "┼")             /*display the last rank of chessboard. */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
move: procedure expose @. Kr. Kf. target; parse arg #,rank,file /*obtain move,rank,file.*/
        do t=1  for Kr.M;   nr=rank+Kr.t;         nf=file+Kf.t  /*position of the knight*/
        if @.nr.nf==.  then do;                   @.nr.nf=#     /*Empty? Knight can move*/
                               if #==target       then return 1 /*is this the last move?*/
                               if move(#+1,nr,nf) then return 1 /* "   "   "    "    "  */
                               @.nr.nf=.                        /*undo the above move.  */
                            end                                 /*try a different move. */
        end   /*t*/                                             /* [↑]  all moves tried.*/
     return 0                                                   /*tour isn't possible.  */


# syntax: GAWK -f SMARANDACHE_PRIME-DIGITAL_SEQUENCE.AWK
BEGIN {
    limit = 25
    printf("1-%d:",limit)
    while (1) {
      if (is_prime(++n)) {
        if (all_digits_prime(n) == 1) {
          if (++count <= limit) {
            printf(" %d",n)
          }
          if (count == 100) {
            printf("\n%d: %d\n",count,n)
            break
          }
        }
      }
    }
    exit(0)
}
function all_digits_prime(n, i) {
    for (i=1; i<=length(n); i++) {
      if (!is_prime(substr(n,i,1))) {
        return(0)
      }
    }
    return(1)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}


arraybase 1
dim smar(100)
smar[1] = 2

cont = 1
i = 1

print 1, 2
while cont < 100
	i += 2
	if not isPrime(i) then continue while
	for j = 1 to length(string(i))
		digit = int(mid(string(i),j,1))
		if not isPrime(digit) then continue while
	next j
	cont += 1
	smar[cont] = i
	if cont = 100 or cont <= 25 then print cont, smar[cont]
end while
end

function isPrime(v)
	if v < 2 then return False
	if v mod 2 = 0 then return v = 2
	if v mod 3 = 0 then return v = 3
	d = 5
	while d * d <= v
		if v mod d = 0 then return False else d += 2
	end while
	return True
end function


using System.Text;
using System.Net.Sockets;

module Program
{
    Main() : void
    {
        def sock = Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sock.Connect("127.0.0.1", 1000);
        _ = sock.Send(Encoding.ASCII.GetBytes("Hell, world!"));
        sock.Close();
    }
}


/* NetRexx */
options replace format comments java crossref symbols nobinary
import java.net.

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg host':'port':'message
  if host    = '' then host    = 'localhost'
  if port    = '' then port    = 256
  if message = '' then message = 'hello socket world'
  sendToSocket(host, port, message)
  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sendToSocket(host, port, message) public static
  do
    sokt = Socket(host, port)
    soks = sokt.getOutputStream()
    soks.write((String message).getBytes())
    soks.flush()
    sokt.close()
  catch ix = IOException
    ix.printStackTrace()
  end
  return


(set 'socket (net-connect "localhost" 256))
(net-send socket "hello socket world")
(net-close socket)
(exit)


package require Tcl 8.6

oo::class create HKTSolver {
    variable grid start limit
    constructor {puzzle} {
	set grid $puzzle
	for {set y 0} {$y < [llength $grid]} {incr y} {
	    for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} {
		if {[set cell [lindex $grid $y $x]] == 1} {
		    set start [list $y $x]
		}
		incr limit [expr {$cell>=0}]
	    }
	}
	if {![info exist start]} {
	    return -code error "no starting position found"
	}
    }
    method moves {} {
	return {
	        -1 -2   1 -2
	    -2 -1          2 -1
	    -2  1          2 1
	        -1 2    1 2
	}
    }
    method Moves {g r c} {
	set valid {}
	foreach {dr dc} [my moves] {
	    set R [expr {$r + $dr}]
	    set C [expr {$c + $dc}]
	    if {[lindex $g $R $C] == 0} {
		lappend valid $R $C
	    }
	}
	return $valid
    }

    method Solve {g r c v} {
	lset g $r $c [incr v]
	if {$v >= $limit} {return $g}
	foreach {r c} [my Moves $g $r $c] {
	    return [my Solve $g $r $c $v]
	}
	return -code continue
    }

    method solve {} {
	while {[incr i]==1} {
	    set grid [my Solve $grid {*}$start 0]
	    return
	}
	return -code error "solution not possible"
    }
    method solution {} {return $grid}
}

proc parsePuzzle {str} {
    foreach line [split $str "\n"] {
	if {[string trim $line] eq ""} continue
	lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] {
	    string map {" " -1} $c
	}]
    }
    set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]]
    for {set i 0} {$i < [llength $rows]} {incr i} {
	while {[llength [lindex $rows $i]] < $len} {
	    lset rows $i end+1 -1
	}
    }
    return $rows
}
proc showPuzzle {grid name} {
    foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}}
    set len [string length $c]
    set u [string repeat "_" $len]
    puts "$name with $c cells"
    foreach row $grid {
	puts [format "  %s" [join [lmap c $row {
	    format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}]
	}]]]
    }
}

set puzzle [parsePuzzle {
  0 0 0
  0   0 0
  0 0 0 0 0 0 0
0 0 0     0   0
0   0     0 0 0
1 0 0 0 0 0 0
    0 0   0
      0 0 0
}]
showPuzzle $puzzle "Input"
HKTSolver create hkt $puzzle
hkt solve
showPuzzle [hkt solution] "Output"


#include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

typedef uint32_t integer;

integer next_prime_digit_number(integer n) {
    if (n == 0)
        return 2;
    switch (n % 10) {
    case 2:
        return n + 1;
    case 3:
    case 5:
        return n + 2;
    default:
        return 2 + next_prime_digit_number(n/10) * 10;
    }
}

bool is_prime(integer n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    if (n % 5 == 0)
        return n == 5;
    static const integer wheel[] = { 4,2,4,2,4,6,2,6 };
    integer p = 7;
    for (;;) {
        for (int i = 0; i < 8; ++i) {
            if (p * p > n)
                return true;
            if (n % p == 0)
                return false;
            p += wheel[i];
        }
    }
}

int main() {
    setlocale(LC_ALL, "");
    const integer limit = 1000000000;
    integer n = 0, max = 0;
    printf("First 25 SPDS primes:\n");
    for (int i = 0; n < limit; ) {
        n = next_prime_digit_number(n);
        if (!is_prime(n))
            continue;
        if (i < 25) {
            if (i > 0)
                printf(" ");
            printf("%'u", n);
        }
        else if (i == 25)
            printf("\n");
        ++i;
        if (i == 100)
            printf("Hundredth SPDS prime: %'u\n", n);
        else if (i == 1000)
            printf("Thousandth SPDS prime: %'u\n", n);
        else if (i == 10000)
            printf("Ten thousandth SPDS prime: %'u\n", n);
        max = n;
    }
    printf("Largest SPDS prime less than %'u: %'u\n", limit, max);
    return 0;
}


import net

var s = newSocket()
s.connect("localhost", Port(256))
s.send("Hello Socket World")
s.close()


use Net;

bundle Default {
  class Socket {
    function : Main(args : String[]) ~ Nil {
      socket := TCPSocket->New("localhost", 256);
      if(socket->IsOpen()) {
        socket->WriteString("hello socket world");
        socket->Close();
      }
    }
  }
}


// declare the class to conform to NSStreamDelegate protocol

// in some method
NSOutputStream *oStream;
[NSStream getStreamsToHost:[NSHost hostWithName:@"localhost"] port:256 inputStream:NULL outputStream:&oStream];
[oStream setDelegate:self];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream open];

// later, in the same class:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent {
    NSOutputStream *oStream = (NSOutputStream *)aStream;
    if (streamEvent == NSStreamEventHasBytesAvailable) {
        NSString *str = @"hello socket world";
        const char *rawstring = [str UTF8String];
        [oStream write:rawstring maxLength:strlen(rawstring)];
        [oStream close];
    }
}


import "/fmt" for Fmt

var moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ]

var board1 =
    " xxx    " +
    " x xx   " +
    " xxxxxxx" +
    "xxx  x x" +
    "x x  xxx" +
    "sxxxxxx " +
    "  xx x  " +
    "   xxx  "

var board2 =
    ".....s.x....." +
    ".....x.x....." +
    "....xxxxx...." +
    ".....xxx....." +
    "..x..x.x..x.." +
    "xxxxx...xxxxx" +
    "..xx.....xx.." +
    "xxxxx...xxxxx" +
    "..x..x.x..x.." +
    ".....xxx....." +
    "....xxxxx...." +
    ".....x.x....." +
    ".....x.x....."

var solve // recursive
solve = Fn.new { |pz, sz, sx, sy, idx, cnt|
    if (idx > cnt) return true
    for (i in 0...moves.count) {
        var x = sx + moves[i][0]
        var y = sy + moves[i][1]
        if ((x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0) {
            pz[x][y] = idx
            if (solve.call(pz, sz, x, y, idx + 1, cnt)) return true
            pz[x][y] = 0
        }
    }
    return false
}

var findSolution = Fn.new { |b, sz|
    var pz = List.filled(sz, null)
    for (i in 0...sz) pz[i] = List.filled(sz, -1)
    var x = 0
    var y = 0
    var idx = 0
    var cnt = 0
    for (j in 0...sz) {
        for (i in 0...sz) {
            if (b[idx] == "x") {
                pz[i][j] = 0
                cnt = cnt + 1
            } else if (b[idx] == "s") {
                pz[i][j] = 1
                cnt = cnt + 1
                x = i
                y = j
            }
            idx = idx + 1
        }
    }

    if (solve.call(pz, sz, x, y, 2, cnt)) {
        for (j in 0...sz) {
            for (i in 0...sz) {
                if (pz[i][j] != -1) {
                    Fmt.write("$02d  ", pz[i][j])
                } else {
                    System.write("--  ")
                }
            }
            System.print()
        }
    } else {
        System.print("Cannot solve this puzzle!")
   }
}

findSolution.call(board1,  8)
System.print()
findSolution.call(board2, 13)


#include <iostream>
#include <cstdint>

using integer = uint32_t;

integer next_prime_digit_number(integer n) {
    if (n == 0)
        return 2;
    switch (n % 10) {
    case 2:
        return n + 1;
    case 3:
    case 5:
        return n + 2;
    default:
        return 2 + next_prime_digit_number(n/10) * 10;
    }
}

bool is_prime(integer n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    if (n % 5 == 0)
        return n == 5;
    constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };
    integer p = 7;
    for (;;) {
        for (integer w : wheel) {
            if (p * p > n)
                return true;
            if (n % p == 0)
                return false;
            p += w;
        }
    }
}

int main() {
    std::cout.imbue(std::locale(""));
    const integer limit = 1000000000;
    integer n = 0, max = 0;
    std::cout << "First 25 SPDS primes:\n";
    for (int i = 0; n < limit; ) {
        n = next_prime_digit_number(n);
        if (!is_prime(n))
            continue;
        if (i < 25) {
            if (i > 0)
                std::cout << ' ';
            std::cout << n;
        }
        else if (i == 25)
            std::cout << '\n';
        ++i;
        if (i == 100)
            std::cout << "Hundredth SPDS prime: " << n << '\n';
        else if (i == 1000)
            std::cout << "Thousandth SPDS prime: " << n << '\n';
        else if (i == 10000)
            std::cout << "Ten thousandth SPDS prime: " << n << '\n';
        max = n;
    }
    std::cout << "Largest SPDS prime less than " << limit << ": " << max << '\n';
    return 0;
}


open Unix

let init_socket addr port =
  let inet_addr = (gethostbyname addr).h_addr_list.(0) in
  let sockaddr = ADDR_INET (inet_addr, port) in
  let sock = socket PF_INET SOCK_STREAM 0 in
  connect sock sockaddr;
  (* convert the file descriptor into high-level channels: *)
  let outchan = out_channel_of_descr sock in
  let inchan = in_channel_of_descr sock in
  (inchan, outchan)


declare
  Socket = {New Open.socket init}
in
  {Socket connect(port:256)}
  {Socket write(vs:"hello socket world")}
  {Socket close}


Program Sockets_ExampleA;

Uses
  { Free Pascal RTL sockets unit }
  sockets;

Var
  TCP_Sock:    integer;
  Remote_Addr: TSockAddr;

  Message:     string;
  PMessage:    Pchar;
  Message_Len: integer;

Begin
  { Fill the record (struct) with the server's address information }
  With Remote_Addr do
  begin
    Sin_family := AF_INET;
    Sin_addr   := StrToNetAddr('127.0.0.1');
    Sin_port   := HtoNs(256);
  end;

  { Returns an IPv4 TCP socket descriptor }
  TCP_Sock := fpSocket(AF_INET, SOCK_STREAM, IPPROTO_IP);

  { Most routines in this unit return -1 on failure }
  If TCP_Sock = -1 then
  begin
    WriteLn('Failed to create new socket descriptor');
    Halt(1);
  end;

  { Attempt to connect to the address supplied above }
  If fpConnect(TCP_Sock, @Remote_Addr, SizeOf(Remote_Addr)) = -1 then
  begin
    { Specifc error codes can be retrieved by calling the SocketError function }
    WriteLn('Failed to contact server');
    Halt(1);
  end;

  { Finally, send the message to the server and disconnect }
  Message     := 'Hello socket world';
  PMessage    := @Message;
  Message_Len := StrLen(PMessage);

  If fpSend(TCP_Sock, PMessage, Message_Len, 0) <> Message_Len then
  begin
    WriteLn('An error occurred while sending data to the server');
    Halt(1);
  end;

  CloseSocket(TCP_Sock);
End.


// Generate Smarandache prime-digital sequence. Nigel Galloway: May 31st., 2019
let rec spds g=seq{yield! g; yield! (spds (Seq.collect(fun g->[g*10+2;g*10+3;g*10+5;g*10+7]) g))}|>Seq.filter(isPrime)
spds [2;3;5;7] |> Seq.take 25 |> Seq.iter(printfn "%d")
printfn "\n\n100th item of this sequence is %d" (spds [2;3;5;7] |> Seq.item 99)
printfn "1000th item of this sequence is %d" (spds [2;3;5;7] |> Seq.item 999)


USING: combinators.short-circuit io lists lists.lazy math
math.parser math.primes prettyprint sequences ;
IN: rosetta-code.smarandache-naive

: smarandache? ( n -- ? )
    {
        [ number>string string>digits [ prime? ] all? ]
        [ prime? ]
    } 1&& ;

: smarandache ( -- list ) 1 lfrom [ smarandache? ] lfilter ;

: smarandache-demo ( -- )
    "First 25 members of the Smarandache prime-digital sequence:"
    print 25 smarandache ltake list>array .
    "100th member: " write smarandache 99 [ cdr ] times car . ;

MAIN: smarandache-demo


: is_prime? ( n -- flag )
  dup 2 < if drop false exit then
  dup 2 mod 0= if 2 = exit then
  dup 3 mod 0= if 3 = exit then
  5
  begin
    2dup dup * >=
  while
    2dup mod 0= if 2drop false exit then
    2 +
    2dup mod 0= if 2drop false exit then
    4 +
  repeat
  2drop true ;

: next_prime_digit_number ( n -- n )
  dup 0= if drop 2 exit then
  dup 10 mod
  dup 2 = if drop 1+ exit then
  dup 3 = if drop 2 + exit then
  5 = if 2 + exit then
  10 / recurse 10 * 2 + ;

: spds_next ( n -- n )
  begin
    next_prime_digit_number
    dup is_prime?
  until ;

: spds_print ( n -- )
  0 swap 0 do
    spds_next dup .
  loop
  drop cr ;

: spds_nth ( n -- n )
  0 swap 0 do spds_next loop ;

." First 25 SPDS primes:" cr
25 spds_print

." 100th SPDS prime: "
100 spds_nth . cr

." 1000th SPDS prime: "
1000 spds_nth . cr

bye


function isprime( n as ulongint ) as boolean
    if n < 2 then return false
    if n = 2 then return true
    if n mod 2 = 0 then return false
    for i as uinteger = 3 to int(sqr(n))+1 step 2
        if n mod i = 0 then return false
    next i
    return true
end function

dim as integer smar(1 to 100), count = 1, i = 1, digit, j
smar(1) = 2
print 1, 2
while count < 100
    i += 2
    if not isprime(i) then continue while
    for j = 1 to len(str(i))
        digit = val(mid(str(i),j,1))
        if not isprime(digit) then continue while
    next j
    count += 1
    smar(count) = i
    if count = 100 orelse count <=25 then
        print count, smar(count)
    end if
wend


use Socket;

$host = gethostbyname('localhost');
$in = sockaddr_in(256, $host);
$proto = getprotobyname('tcp');
socket(Socket_Handle, AF_INET, SOCK_STREAM, $proto);
connect(Socket_Handle, $in);
send(Socket_Handle, 'hello socket world', 0, $in);
close(Socket_Handle);


without js -- (sockets)
include builtins\sockets.e
constant msg = "hello socket world"
atom sock = socket(AF_INET, SOCK_STREAM)
if sock>=0 then
    atom pSockAddr = sockaddr_in(AF_INET, "localhost", 256)
    integer res = connect(sock, pSockAddr)
    if res=SOCKET_ERROR then
        crash("connect (%v)",{get_socket_error()})
    end if
    string pm = msg
    while true do
        integer len = length(pm),
                slen = send(sock, pm)
        if slen<0 or slen=len then exit end if
        pm = pm[slen+1..$]
    end while
    closesocket(sock)
end if
WSACleanup()


$socket = fsockopen('localhost', 256);
fputs($socket, 'hello socket world');
fclose($socket);


package main

import (
    "fmt"
    "math/big"
)

var b = new(big.Int)

func isSPDSPrime(n uint64) bool {
    nn := n
    for nn > 0 {
        r := nn % 10
        if r != 2 && r != 3 && r != 5 && r != 7 {
            return false
        }
        nn /= 10
    }
    b.SetUint64(n)
    if b.ProbablyPrime(0) { // 100% accurate up to 2 ^ 64
        return true
    }
    return false
}

func listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {
    count := countFrom
    for n := startFrom; ; n += 2 {
        if isSPDSPrime(n) {
            count++
            if !printOne {
                fmt.Printf("%2d. %d\n", count, n)
            }
            if count == countTo {
                if printOne {
                    fmt.Println(n)
                }
                return n
            }
        }
    }
}

func main() {
    fmt.Println("The first 25 terms of the Smarandache prime-digital sequence are:")
    fmt.Println(" 1. 2")
    n := listSPDSPrimes(3, 1, 25, false)
    fmt.Println("\nHigher terms:")
    indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}
    for i := 1; i < len(indices); i++ {
        fmt.Printf("%6d. ", indices[i])
        n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)
    }
}


(when (connect "localhost" 256)
   (out @ (prinl "hello socket world"))
   (close @) )


import Stdio;

int main(){
   object con = File();
   con->connect("127.0.0.1",256);
   con->write("hello socket world");
   con->close();
}


start(Port) :- socket('AF_INET',Socket),
               socket_connect(Socket, 'AF_INET'(localhost,Port), Input, Output),
               write(Output, 'hello socket world'),
               flush_output(Output),
               close(Output),
               close(Input).


InitNetwork()
ConnectionID = OpenNetworkConnection("localhost", 256)
SendNetworkString(ConnectionID, "hello socket world")
CloseNetworkConnection(ConnectionID)


{-# LANGUAGE NumericUnderscores #-}
import Control.Monad (guard)
import Math.NumberTheory.Primes.Testing (isPrime)
import Data.List.Split (chunksOf)
import Data.List (intercalate)
import Text.Printf (printf)

smarandache :: [Integer]
smarandache = [2,3,5,7] <> s [2,3,5,7] >>= \x -> guard (isPrime x) >> [x]
 where s xs = r <> s r where r = xs >>= \x -> [x*10+2, x*10+3, x*10+5, x*10+7]

nextSPDSTerms :: [Int] -> [(String, String)]
nextSPDSTerms = go 1 smarandache
 where
  go _ _ [] = []
  go c (x:xs) terms
   | c `elem` terms = (commas c, commas x) : go nextCount xs (tail terms)
   | otherwise      = go nextCount xs terms
   where nextCount = succ c

commas :: Show a => a -> String
commas = reverse . intercalate "," . chunksOf 3 . reverse . show

main :: IO ()
main = do
  printf "The first 25 SPDS:\n%s\n\n" $ f smarandache
  mapM_ (uncurry (printf "The %9sth SPDS: %15s\n")) $
    nextSPDSTerms [100, 1_000, 10_000, 100_000, 1_000_000]
 where f = show . take 25


   Filter=: (#~`)(`:6)

   NB. given a prime y, smarandache y is 1 iff it's a smarandache prime
   smarandache=: [: -. (0 e. (p:i.4) e.~ 10 #.inv ])&>

   SP=: smarandache Filter p: i. 1000000

   SP {~ i. 25   NB. first 25 Smarandache primes
2 3 5 7 23 37 53 73 223 227 233 257 277 337 353 373 523 557 577 727 733 757 773 2237 2273

   99 _1 { SP    NB. 100th and largest Smarandache prime of the first million primes
33223 7777753

   # SP          NB. Tally of Smarandache primes in the first million primes
1903


public class SmarandachePrimeDigitalSequence {

    public static void main(String[] args) {
        long s = getNextSmarandache(7);
        System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 ");
        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {
            if ( isPrime(s) ) {
                System.out.printf("%d ", s);
                count++;
            }
        }
        System.out.printf("%n%n");
        for (int i = 2 ; i <=5 ; i++ ) {
            long n = (long) Math.pow(10, i);
            System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n));
        }
    }

    private static final long getSmarandachePrime(long n) {
        if ( n < 10 ) {
            switch ((int) n) {
            case 1:  return 2;
            case 2:  return 3;
            case 3:  return 5;
            case 4:  return 7;
            }
        }
        long s = getNextSmarandache(7);
        long result = 0;
        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {
            if ( isPrime(s) ) {
                count++;
                result = s;
            }
        }
        return result;
    }

    private static final boolean isPrime(long test) {
        if ( test % 2 == 0 ) return false;
        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
            if ( test % i == 0 ) {
                return false;
            }
        }
        return true;
    }

    private static long getNextSmarandache(long n) {
        //  If 3, next is 7
        if ( n % 10 == 3 ) {
            return n+4;
        }
        long retVal = n-4;

        //  Last digit 7.  k = largest position from right where we have a 7.
        int k = 0;
        while ( n % 10 == 7 ) {
            k++;
            n /= 10;
        }

        //  Determine first digit from right where digit != 7.
        long digit = n % 10;

        //  Digit is 2, 3, or 5.  3-2 = 1, 5-3 = 2, 7-5 = 2, so digit = 2, coefficient = 1, otherwise 2.
        long coeff = (digit == 2 ? 1 : 2);

        //  Compute next value
        retVal += coeff * Math.pow(10, k);

        //  Subtract values for digit = 7.
        while ( k > 1 ) {
            retVal -= 5 * Math.pow(10, k-1);
            k--;
        }

        //  Even works for 777..777 --> 2222...223
        return retVal;
    }

}


import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 256))
sock.sendall("hello socket world")
sock.close()


s <- make.socket(port = 256)
write.socket(s, "hello socket world")
close.socket(s)


#lang racket
(let-values ([(in out) (tcp-connect "localhost" 256)])
  (display "hello socket world\n" out)
  (close-output-port out))


my $host = '127.0.0.1';
my $port = 256;

my $client = IO::Socket::INET.new(:$host, :$port);
$client.print( 'hello socket world' );
$client.close;


def Smarandache_primes:
  # Output: a naively constructed stream of candidate strings of length >= 1
  def Smarandache_candidates:
    def unconstrained($length):
      if $length==1 then "2", "3", "5", "7"
      else ("2", "3", "5", "7") as $n
      | $n + unconstrained($length -1 )
      end;
    unconstrained(. - 1) as $u
    |  ("3", "7") as $tail
    | $u + $tail ;

  2,3,5,7,
  (range(2; infinite) | Smarandache_candidates | tonumber | select(is_prime));

# Override jq's incorrect definition of nth/2
# Emit the $n-th value of the stream, counting from 0; or emit nothing
def nth($n; s):
 if $n < 0 then error("nth/2 doesn't support negative indices")
 else label $out
 | foreach s as $x (-1; .+1; select(. >= $n) | $x, break $out)
 end;

"First 25:",
[limit(25; Smarandache_primes)],

# jq counts from 0 so:
"\nThe hundredth: \(nth(99; Smarandache_primes))"


using Combinatorics, Primes

combodigits(len) = sort!(unique(map(y -> join(y, ""), with_replacement_combinations("2357", len))))

function getprimes(N, maxdigits=9)
    ret = [2, 3, 5, 7]
    perms = Int[]
    for i in 1:maxdigits-1, combo in combodigits(i), perm in permutations(combo)
        n = parse(Int64, String(perm)) * 10
        push!(perms, n + 3, n + 7)
    end
        for perm in sort!(perms)
        if isprime(perm) && !(perm in ret)
            push!(ret, perm)
            if length(ret) >= N
                return ret
            end
        end
    end
end

const v = getprimes(10000)
println("The first 25 Smarandache primes are: ", v[1:25])
println("The 100th Smarandache prime is: ", v[100])
println("The 10000th Smarandache prime is: ", v[10000])


-- FUNCS:
local function T(t) return setmetatable(t, {__index=table}) end
table.firstn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end

-- SIEVE:
local sieve, S = {}, 50000
for i = 2,S do sieve[i]=true end
for i = 2,S do if sieve[i] then for j=i*i,S,i do sieve[j]=nil end end end

-- TASKS:
local digs, cans, spds, N = {2,3,5,7}, T{0}, T{}, 100
while #spds < N do
  local c = cans:remove(1)
  for _,d in ipairs(digs) do cans:insert(c*10+d) end
  if sieve[c] then spds:insert(c) end
end
print("1-25 :  " .. spds:firstn(25):concat(" "))
print("100th:  " .. spds[100])


ClearAll[SmarandachePrimeQ]
SmarandachePrimeQ[n_Integer] := MatchQ[IntegerDigits[n], {(2 | 3 | 5 | 7) ..}] \[And] PrimeQ[n]
s = Select[Range[10^5], SmarandachePrimeQ];
Take[s, UpTo[25]]
s[[100]]


Socket Send(0,0)
|:
    [[email protected] Client["localhost",256]]Put String["hello socket world"]
:|


Load "guilib.ring"

new qApp {
        oClient = new Client { client() }
        exec()
}

Class Client

        win1 oTcpSocket

        func client

                win1 = new qwidget()

                new qpushbutton(win1) {
                        setgeometry(50,50,100,30)
                        settext("connect")
                        setclickevent("oClient.Connect()")
                }

                win1 {
                        setwindowtitle("client")
                        setgeometry(10,100,400,400)
                        show()
                }

        func connect
                oTcpSocket = new qTcpSocket(win1) {
                        setconnectedevent("oClient.pConnected()")
                        connecttohost("127.0.0.1",256,3,0)
                        waitforconnected(5000)
                }

        func pConnected
                cStr = "hello socket world"
                write(cStr,len(cStr))
                flush()
                waitforbyteswritten(300000)
                close()


require 'socket'
sock = TCPSocket.open("localhost", 256)
sock.write("hello socket world")
sock.close


use std::io::prelude::*;
use std::net::TcpStream;

fn main() {
    // Open a tcp socket connecting to 127.0.0.1:256, no error handling (unwrap)
    let mut my_stream = TcpStream::connect("127.0.0.1:256").unwrap();

    // Write 'hello socket world' to the stream, ignoring the result of write
    let _ = my_stream.write(b"hello socket world");

} // <- my_stream's drop function gets called, which closes the socket


import java.net.Socket

object sendSocketData {

  def sendData(host: String, msg: String) {
    val sock = new Socket(host, 256)
    sock.getOutputStream().write(msg.getBytes())
    sock.getOutputStream().flush()
    sock.close()
  }

  sendData("localhost", "hello socket world")
}


import math, strformat, strutils

const N = 35_000

# Sieve.
var composite: array[0..N, bool]  # Default is false and means prime.
composite[0] = true
composite[1] = true
for n in 2..sqrt(N.toFloat).int:
  if not composite[n]:
    for k in countup(n * n, N, n):
      composite[k] = true

func digits(n: Positive): seq[0..9] =
  var n = n.int
  while n != 0:
    result.add n mod 10
    n = n div 10

proc isSPDS(n: int): bool =
  if composite[n]: return false
  result = true
  for d in n.digits:
    if composite[d]: return false

iterator spds(maxCount: Positive): int {.closure.} =
  yield 2
  var count = 1
  var n = 3
  while count != maxCount and n <= N:
    if n.isSPDS:
      inc count
      yield n
    inc n, 2
  if count != maxCount:
    quit &"Too few values ({count}). Please, increase value of N.", QuitFailure

stdout.write "The first 25 SPDS are:"
for n in spds(25):
  stdout.write ' ', n
echo()

var count = 0
for n in spds(100):
  inc count
  if count == 100:
    echo "The 100th SPDS is: ", n


program Smarandache;

uses
  sysutils,primsieve;// http://rosettacode.org/wiki/Extensible_prime_generator#Pascal
const
  Digits : array[0..3] of Uint32 = (2,3,5,7);
var
  i,j,pot10,DgtLimit,n,DgtCnt,v,cnt,LastPrime,Limit : NativeUint;

procedure Check(n:NativeUint);
var
  p : NativeUint;
Begin
  p := LastPrime;
  while p< n do
    p := nextprime;
  if p = n then
  begin
    inc(cnt);
    IF (cnt <= 25) then
    Begin
      IF cnt = 25 then
      Begin
        writeln(n);
        Limit := 100;
      end
      else
        Write(n,',');
    end
    else
      IF cnt = Limit then
      Begin
        Writeln(cnt:9,n:16);
        Limit *=10;
        if Limit > 10000 then
          HALT;
      end;
   end;
   LastPrime := p;
end;

Begin
  Limit := 25;
  LastPrime:=1;

//Creating the numbers not the best way but all upto 11 digits take 0.05s
//here only 9 digits
  i := 0;
  pot10 := 1;
  DgtLimit := 1;
  v := 4;
  repeat
    repeat
     j := i;
     DgtCnt := 0;
     pot10 := 1;
     n := 0;
     repeat
       n += pot10*Digits[j MOD 4];
       j := j DIV 4;
       pot10 *=10;
       inc(DgtCnt);
     until DgtCnt = DgtLimit;
     Check(n);
     inc(i);
   until i=v;
   //one more digit
   v *=4;
   i :=0;
   inc(DgtLimit);
 until DgtLimit= 12;
end.


(let ((s (socket PF_INET SOCK_STREAM 0)))
    (connect s AF_INET (inet-pton AF_INET "127.0.0.1") 256)
    (display "hello socket world" s))


$ include "seed7_05.s7i";
  include "socket.s7i";

const proc: main is func
  local
    var file: sock is STD_NULL;
  begin
    sock := openInetSocket(256);
    writeln(sock, "hello socket world");
    close(sock);
  end func;


set SocketID to "localhost:256"
open socket SocketID
write "Hello socket world!" to socket SocketID
close socket SocketID


var host = Socket.gethostbyname('localhost');
var in = Socket.sockaddr_in(256, host);
var proto = Socket.getprotobyname('tcp');

var sock = Socket.open(Socket.AF_INET, Socket.SOCK_STREAM, proto);
sock.connect(in);
sock.send('hello socket world', 0, in);
sock.close;


use strict;
use warnings;
use feature 'say';
use feature 'state';
use ntheory qw<is_prime>;
use Lingua::EN::Numbers qw(num2en_ordinal);

my @prime_digits = <2 3 5 7>;
my @spds = grep { is_prime($_) && /^[@{[join '',@prime_digits]}]+$/ } 1..100;
my @p    = map { $_+3, $_+7 } map { 10*$_ } @prime_digits;

while ($#spds < 100_000) {
    state $o++;
    my $oom = 10**(1+$o);
    my @q;
    for my $l (@prime_digits) {
        push @q, map { $l*$oom + $_ } @p;
    }
    push @spds, grep { is_prime($_) } @p = @q;
}

say 'Smarandache prime-digitals:';
printf "%22s: %s\n", ucfirst(num2en_ordinal($_)), $spds[$_-1] for 1..25, 100, 1000, 10_000, 100_000;


with javascript_semantics
atom t0 = time()
sequence spds = {2,3,5,7}
atom nxt_candidate = 23
sequence adj = {{4,-4},sq_mul({1,2,2,-5},10)},
         adjn = {1,1}

include mpfr.e
mpz zprime = mpz_init()

procedure populate_spds(integer n)
    while length(spds)<n do
        mpz_set_d(zprime,nxt_candidate)
        if mpz_prime(zprime) then
            spds &= nxt_candidate
        end if
        for i=1 to length(adjn) do
            sequence adjs = adj[i]
            integer adx = adjn[i]
            nxt_candidate += adjs[adx]
            adx += 1
            if adx<=length(adjs) then
                adjn[i] = adx
                exit
            end if
            adjn[i] = 1
            if i=length(adjn) then
                -- (this is eg 777, by now 223 carry 1, -> 2223)
                adj = append(adj,sq_mul(adj[$],10))
                adjn = append(adjn, 1)
                nxt_candidate += adj[$][2]
                exit
            end if
        end for
    end while
end procedure

populate_spds(25)
printf(1,"spds[1..25]:%v\n",{spds[1..25]})
for n=2 to 5 do
    integer p = power(10,n)
    populate_spds(p)
    printf(1,"spds[%,d]:%,d\n",{p,spds[p]})
end for
for n=7 to 10 do
    atom p = power(10,n),
        dx = abs(binary_search(p,spds))-1
    printf(1,"largest spds prime less than %,15d:%,14d\n",{p,spds[dx]})
end for
?elapsed(time()-t0)


[ | socket |
  [ | addr stream |
    addr: (Net SocketAddress newOn: '127.0.0.1:256').
    socket: (Net Socket newFor: addr domain type: Net Socket Types Stream protocol: Net Socket Protocols Default).
    socket connectTo: addr.
    stream: (Net SocketStream newOn: socket).
    stream nextPutAll: ('hello socket world' as: ByteArray).
    stream flush
  ] ensure: [socket close]
] do.


PackageLoader fileInPackage: 'TCP'!

Object subclass: #HelloSocket
  instanceVariableNames: 'ss'
  classVariableNames: ''
  poolDictionaries: ''
  category: 'SimpleEcho'!

!HelloSocket class methodsFor: 'instance creation'!

port: anInteger
  | ses |
  ses := super new.
  ses init: anInteger.
  ^ses
!!

!HelloSocket methodsFor: 'instance initialization'!

init: anInteger
  ss := (TCP.ServerSocket port: anInteger).
  ^self
!!

!HelloSocket methodsFor: 'running'!

run
  | s |
  [
    ss waitForConnection.
    s := (ss accept).
    [self handleSocket: s] fork
  ] repeat
!!

!HelloSocket methodsFor: 'handling'!

handleSocket: s
    | msg |
    msg := 'hello socket world'.
    msg displayOn: s.
    (String with: (Character value: 10)) displayOn: s.
    s flush
!!

Smalltalk at: #helloServer put: (HelloSocket port: 2560).

helloServer run.


 '127.0.0.1' $addr
 connect $addr 256 sok
 'hello socket world' [sok]
 close sok


val txt = Word8VectorSlice.full (Byte.stringToBytes  "hello world"   ) ;
val set = fn socket => fn ipnr => fn portnr => fn text =>
 (
  Socket.connect (socket, INetSock.toAddr ( Option.valOf (NetHostDB.fromString(ipnr) ) , portnr )) ;
  Socket.sendVec(socket, text)  before Socket.close socket
 )
;


def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))

def is_prime(n):
    return len(divisors(n)) == 2

def digit_check(n):
    if len(str(n))<2:
        return True
    else:
        for digit in str(n):
            if not is_prime(int(digit)):
                return False
        return True

def sequence(max_n=None):
    ii = 0
    n = 0
    while True:
        ii += 1
        if is_prime(ii):
            if max_n is not None:
                if n>max_n:
                    break
            if digit_check(ii):
                n += 1
                yield ii

if __name__ == '__main__':
    generator = sequence(100)
    for index, item in zip(range(1, 16), generator):
        print(index, item)
    for index, item in zip(range(16, 100), generator):
        pass
    print(100, generator.__next__())


  [ true swap
    [ 10 /mod
      [ table 1 1 0 0 1 0 1 0 1 1 ]
      iff [ dip not ] done
      dup 0 = until ]
    drop ]                           is digitsprime ( n --> b )

  [ temp put [] 0
    [ dup digitsprime if
        [ dup isprime if
            [ dup dip join ] ]
      1+
      over size temp share = until ]
    drop ]                           is spds        ( n --> [ )

  100 spds
  25 split swap echo
  cr cr
  -1 peek echo


use Lingua::EN::Numbers;
use ntheory:from<Perl5> <:all>;

# Implemented as a lazy, extendable list
my $spds = grep { .&is_prime }, flat [2,3,5,7], [23,27,33,37,53,57,73,77], -> $p
  { state $o++; my $oom = 10**(1+$o); [ flat (2,3,5,7).map: -> $l { (|$p).map: $l×$oom + * } ] } … *;

say 'Smarandache prime-digitals:';
printf "%22s: %s\n", ordinal(1+$_).tclc, comma $spds[$_] for flat ^25, 99, 999, 9999, 99999;


F sleeping_beauty_experiment(repetitions)
   ‘
    Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
    how often we had heads on waking Sleeping Beauty.
   ’
   V gotheadsonwaking = 0
   V wakenings = 0
   L 0 .< repetitions
      V coin_result = random:choice([‘heads’, ‘tails’])

      // On Monday, we check if we got heads.
      wakenings++
      I coin_result == ‘heads’
         gotheadsonwaking++

      // If tails, we do this again, but of course we will not add as if it was heads..
      I coin_result == ‘tails’
         wakenings++
         I coin_result == ‘heads’
            gotheadsonwaking++ // never done

   print(‘Wakenings over ’repetitions‘ experiments: ’wakenings)

   R Float(gotheadsonwaking) / wakenings

V CREDENCE = sleeping_beauty_experiment(1'000'000)
print(‘Results of experiment:  Sleeping Beauty should estimate a credence of: ’CREDENCE)


sleepingBeauty: function [reps][
    wakings: 0
    heads: 0
    do.times: reps [
        coin: random 0 1
        wakings: wakings + 1
        if? coin = 0 -> heads: heads + 1
        else -> wakings: wakings + 1
    ]
    print ["Wakings over" reps "repetitions =" wakings]
    return 100.0 * heads//wakings
]

pc: sleepingBeauty 100000
print ["Percentage probability of heads on waking =" pc "%"]


iteraciones = 1000000
cara = 0
dormir = 0

for i = 1 to iteraciones
	lanza_moneda = int(rand * 2)
	dormir = dormir + 1
	if lanza_moneda = 1 then
		cara = cara + 1
	else
		dormir = dormir + 1
	end if
next i

print "Wakings over "; iteraciones; " repetitions = "; dormir
print "Percentage probability of heads on waking = "; (cara/dormir*100); "%"
end


set io [socket localhost 256]
puts -nonewline $io "hello socket world"
close $io


needs sockets

#! A simple abstraction layer that makes writing trivial servers easy
value| server.socket server.connection server.action |
[ ( n- )   pBind to server.socket ] is server.setSocket
[ ( - )    server.socket pAccept to server.connection ] is server.acceptConnection
[ ( - )    server.connection pClose drop ] is server.closeConnection
[ ( $- )   >r server.connection r> string.getLength pWrite drop ] is server.send
[ ( an- )  server.connection -rot pRead drop ] is server.recieve
[ ( qn- )  swap to server.action server.setSocket
  [ server.acceptConnection server.action invoke server.closeConnection TRUE ] whileTrue ] is server.start

#! The actual server
[ " hello socket world" server.send ] 256 server.start


(let* ((server (first (getaddrinfo "localhost" 256)))
       (sock (open-socket server.family sock-stream)))
  (sock-connect sock server)
  (put-string "hello socket world"))


echo "hello socket world" | nc localhost 256


decl port p
p.connect "localhost" 256
out "hello socket world" endl p
p.close


/*REXX program lists a  sequence of  SPDS  (Smarandache prime-digital sequence)  primes.*/
parse arg n q                                    /*get optional number of primes to find*/
if n=='' | n==","  then n=  25                   /*Not specified?  Then use the default.*/
if q=''            then q= 100  1000             /* "      "         "   "   "     "    */
say '═══listing the first'     n     "SPDS primes═══"
call spds n
             do i=1  for words(q)+1;     y=word(q, i);    if y=='' | y==","   then iterate
             say
             say '═══listing the last of '    y     "SPDS primes═══"
             call spds -y
             end   /*i*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
spds: parse arg x 1 ox;  x= abs(x)               /*obtain the limit to be used for list.*/
      c= 0                                       /*C  number of SPDS primes found so far*/
      #= 0                                       /*#  number of      primes found so far*/
            do j=1  by 2  while  c<x;    z= j    /*start: 1st even prime, then use odd. */
            if z==1  then z= 2                   /*handle the even prime (special case) */
                                                 /* [↓]  divide by the primes.   ___    */
                    do k=2  to #  while  k*k<=z  /*divide  Z  with all primes ≤ √ Z     */
                    if z//@.k==0  then iterate j /*÷ by prev. prime?  ¬prime     ___    */
                    end   /*j*/                  /* [↑]   only divide up to     √ Z     */
            #= # + 1;             @.#= z         /*bump the prime count;  assign prime #*/
            if verify(z, 2357)>0  then iterate j /*Digits ¬prime?  Then skip this prime.*/
            c= c + 1                             /*bump the number of SPDS primes found.*/
            if ox<0  then iterate                /*don't display it, display the last #.*/
            say right(z, 21)                     /*maybe display this prime ──► terminal*/
            end   /*j*/                          /* [↑]  only display N number of primes*/
      if ox<0  then say right(z, 21)             /*display one  (the last)  SPDS prime. */
      return


load "stdlib.ring"

see "First 25 Smarandache primes:" + nl + nl

num = 0
limit = 26
limit100 = 100
for n = 1 to 34000
    flag = 0
    nStr = string(n)
    for x = 1 to len(nStr)
        nx = number(nStr[x])
        if isprime(n) and isprime(nx)
           flag = flag + 1
        else
           exit
        ok
     next
     if flag = len(nStr)
        num = num + 1
        if num < limit
           see "" + n + " "
        ok
        if num = limit100
           see nl + nl + "100th Smarandache prime: " + n + nl
        ok
     ok
next


fn is_prime(n: u32) -> bool {
    if n < 2 {
        return false;
    }
    if n % 2 == 0 {
        return n == 2;
    }
    if n % 3 == 0 {
        return n == 3;
    }
    if n % 5 == 0 {
        return n == 5;
    }
    let mut p = 7;
    const WHEEL: [u32; 8] = [4, 2, 4, 2, 4, 6, 2, 6];
    loop {
        for w in &WHEEL {
            if p * p > n {
                return true;
            }
            if n % p == 0 {
                return false;
            }
            p += w;
        }
    }
}

fn next_prime_digit_number(n: u32) -> u32 {
    if n == 0 {
        return 2;
    }
    match n % 10 {
        2 => n + 1,
        3 | 5 => n + 2,
        _ => 2 + next_prime_digit_number(n / 10) * 10,
    }
}

fn smarandache_prime_digital_sequence() -> impl std::iter::Iterator<Item = u32> {
    let mut n = 0;
    std::iter::from_fn(move || {
        loop {
            n = next_prime_digit_number(n);
            if is_prime(n) {
                break;
            }
        }
        Some(n)
    })
}

fn main() {
    let limit = 1000000000;
    let mut seq = smarandache_prime_digital_sequence().take_while(|x| *x < limit);
    println!("First 25 SPDS primes:");
    for i in seq.by_ref().take(25) {
        print!("{} ", i);
    }
    println!();
    if let Some(p) = seq.by_ref().nth(99 - 25) {
        println!("100th SPDS prime: {}", p);
    }
    if let Some(p) = seq.by_ref().nth(999 - 100) {
        println!("1000th SPDS prime: {}", p);
    }
    if let Some(p) = seq.by_ref().nth(9999 - 1000) {
        println!("10,000th SPDS prime: {}", p);
    }
    if let Some(p) = seq.last() {
        println!("Largest SPDS prime less than {}: {}", limit, p);
    }
}


#include <iostream>
#include <random>

int main() {
    std::cout.imbue(std::locale(""));
    const int experiments = 1000000;
    std::random_device dev;
    std::default_random_engine engine(dev());
    std::uniform_int_distribution<int> distribution(0, 1);
    int heads = 0, wakenings = 0;
    for (int i = 0; i < experiments; ++i) {
        ++wakenings;
        switch (distribution(engine)) {
        case 0: // heads
            ++heads;
            break;
        case 1: // tails
            ++wakenings;
            break;
        }
    }
    std::cout << "Wakenings over " << experiments
              << " experiments: " << wakenings << '\n';
    std::cout << "Sleeping Beauty should estimate a credence of: "
              << double(heads) / wakenings << '\n';
}