listOfFiles = {"a.txt", "b.txt", "c.txt"};
Do[
 filename = listOfFiles[[i]];
 filetext = Import[filename, "Text"];
 filetext = StringReplace[filetext, "Goodbye London!" -> "Hello New York!"];
 Export[filename, filetext, "Text"]
 , {i, 1, Length[listOfFiles]}]


(define (replace-in-file filename this bythat)
   (set 'content (read-file filename))
   (when (string? content)
     (replace this content bythat)
     (write-file filename content)
   )
)

(set 'files '("a.txt" "b.txt" "c.txt" "missing"))
(dolist (fname files)
   (replace-in-file fname "Goodbye London!" "Hello New York!")
)

(exit)


import strutils

let fr = "Goodbye London!"
let to = "Hello, New York!"

for fn in ["a.txt", "b.txt", "c.txt"]:
  fn.writeFile fn.readFile.replace(fr, to)


class ReplaceAll {
  function : Main(args : String[]) ~ Nil {
    files := ["text1.txt", "text2.txt"];
    each(f : files) {
      input := System.IO.File.FileReader->ReadFile(files[f]);
      output := input->ReplaceAll("Goodbye London!", "Hello New York!");
      System.IO.File.FileWriter->WriteFile(files[f], output)->PrintLine();
    };
  }
}


FUNCTION replaceText RETURNS LOGICAL (
   i_cfile_list   AS CHAR,
   i_cfrom        AS CHAR,
   i_cto          AS CHAR
):

   DEF VAR ii     AS INT.
   DEF VAR lcfile AS LONGCHAR.

   DO ii = 1 TO NUM-ENTRIES( i_cfile_list ):
      COPY-LOB FROM FILE ENTRY( ii, i_cfile_list ) TO lcfile.
      lcfile = REPLACE( lcfile, i_cfrom, i_cto ).
      COPY-LOB FROM lcfile TO FILE ENTRY( ii, i_cfile_list ).
   END.

END FUNCTION. /* replaceText */

replaceText(
   "a.txt,b.txt,c.txt",
   "Goodbye London!",
   "Hello New York!"
).


Program StringReplace;

uses
  Classes, StrUtils;

const
  fileName: array[1..3] of string = ('a.txt', 'b.txt', 'c.txt');
  matchText = 'Goodbye London!';
  replaceText = 'Hello New York!';

var
  AllText: TStringlist;
  i, j: integer;

begin
  for j := low(fileName) to high(fileName) do
  begin
   AllText := TStringlist.Create;
   AllText.LoadFromFile(fileName[j]);
   for i := 0 to AllText.Count-1 do
     AllText.Strings[i] := AnsiReplaceStr(AllText.Strings[i], matchText, replaceText);
   AllText.SaveToFile(fileName[j]);
   AllText.Destroy;
  end;
end.


perl -pi -e "s/Goodbye London\!/Hello New York\!/g;" a.txt b.txt c.txt


without js -- file i/o
procedure global_replace(string s, string r, sequence file_list)
    for i=1 to length(file_list) do
        string filename = file_list[i]
        integer fn = open(filename,"rb")
        if fn=-1 then ?9/0 end if   -- message/retry?
        string text = get_text(fn)
        close(fn)
        text = substitute(text,s,r)
        fn = open(filename,"wb")
        puts(fn,text)
        close(fn)
    end for
end procedure

sequence file_list = {"ctrace.out"}
global_replace("Goodbye London!", "Hello New York!", file_list)


(for File '(a.txt b.txt c.txt)
   (call 'mv File (tmp File))
   (out File
      (in (tmp File)
         (while (echo "Goodbye London!")
            (prin "Hello New York!") ) ) ) )


$matchtext = "Goodbye London!"
$repltext  = "Hello New York!"

FUNCTION PBMAIN () AS LONG
    DIM L0 AS INTEGER, filespec AS STRING, linein AS STRING

    L0 = 1
    WHILE LEN(COMMAND$(L0))
        filespec = DIR$(COMMAND$(L0))
        WHILE LEN(filespec)
            OPEN filespec FOR BINARY AS 1
                linein = SPACE$(LOF(1))
                GET #1, 1, linein
                ' No need to jump through FB's hoops here...
                REPLACE $matchtext WITH $repltext IN linein
                PUT #1, 1, linein
                SETEOF #1
            CLOSE
            filespec = DIR$
        WEND
        INCR L0
    WEND
END FUNCTION


$listfiles = @('file1.txt','file2.txt')
$old = 'Goodbye London!'
$new = 'Hello New York!'
foreach($file in $listfiles) {
    (Get-Content $file).Replace($old,$new) | Set-Content $file
}


Procedure GRTISF(List File$(), Find$, Replace$)
  Protected Line$, Out$, OutFile$, i
  ForEach File$()
    fsize=FileSize(File$())
    If fsize<=0: Continue: EndIf
    If ReadFile(0, File$())
      i=0
      ;
      ; generate a temporary file in a safe way
      Repeat
        file$=GetTemporaryDirectory()+base$+"_"+Str(i)+".tmp"
        i+1
      Until FileSize(file$)=-1
      i=CreateFile(FileID, file$)
      If i
        ; Copy the infile to the outfile while replacing any needed text
        While Not Eof(0)
          Line$=ReadString(0)
          Out$=ReplaceString(Line$,Find$,Replace$)
          WriteString(1,Out$)
        Wend
        CloseFile(1)
      EndIf
      CloseFile(0)
      If i
        ; If we made a new file, copy it back.
        CopyFile(file$, File$())
        DeleteFile(file$)
      EndIf
    EndIf
  Next
EndProcedure


import fileinput

for line in fileinput.input(inplace=True):
    print(line.replace('Goodbye London!', 'Hello New York!'), end='')


#!/usr/bin/env racket
#lang racket

(define from-string #f)
(define to-string #f)

(command-line
 #:once-each
 [("-f") from "Text to remove" (set! from-string from)]
 [("-t") to "Text to put instead" (set! to-string to)]
 #:args files
 (unless from-string (error "No `from' string specified"))
 (unless to-string   (error "No `to' string specified"))
 (when (null? files) (error "No files given"))
 (define from-rx (regexp (regexp-quote from-string)))
 (for ([file files])
   (printf "Editing ~a..." file) (flush-output)
   (define text1 (file->string file))
   (define text2 (regexp-replace* from-rx text1 to-string))
   (if (equal? text1 text2)
     (printf " no change\n")
     (begin (display-to-file text2 file #:exists 'replace)
            (printf " modified copy saved in place\n")))))


slurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_)
    for <a.txt b.txt c.txt>;


>> f: request-file
>> str: read f
>> replace/all str "Goodbye London!" "Hello New York!"
>> write f str


/*REXX program  reads  the  files specified  and  globally replaces  a string.          */
old= "Goodbye London!"                           /*the  old text     to be replaced.    */
new= "Hello New York!"                           /* "   new   "   used for replacement. */
parse  arg  fileList                             /*obtain required list of files from CL*/
#= words(fileList)                               /*the number of files in the file list.*/

   do f=1  for #;     fn= translate( word(fileList, f), , ',');     say;     say
   say '──────── file is being read: '    fn    " ("f   'out of'     #     "files)."
   call linein fn,1,0                            /*position the file for input.         */
   changes= 0                                    /*the number of changes in file so far.*/
             do rec=0  while lines(fn)\==0       /*read a file   (if it exists).        */
             @.rec= linein(fn)                   /*read a record (line)  from the file. */
             if pos(old, @.rec)==0  then iterate /*Anything to change?   No, then skip. */
             changes= changes + 1                /*flag that file contents have changed.*/
             @.rec= changestr(old, @.rec, new)   /*change the @.rec record, old ──► new.*/
             end   /*rec*/

   say '──────── file has been read: '         fn", with "      rec      'records.'
   if changes==0  then do;  say '──────── file  not  changed: '   fn;   iterate;   end
   call lineout fn,,1                            /*position file for output at 1st line.*/
   say '──────── file being changed: '   fn

       do r=0  for rec;     call lineout fn, @.r /*re─write the contents of the file.   */
       end   /*r*/

   say '──────── file was   changed: '   fn    " with"   changes   'lines changed.'
   end   /*f*/                                   /*stick a fork in it,  we're all done. */


filenames = ["ReadMe.txt", "ReadMe2.txt"]

for fn in filenames
    fp = fopen(fn,"r")
    str = fread(fp,getFileSize(fp))
    str = substr(str, "Greetings", "Hello")
    fclose(fp)

    fp = fopen(fn,"w")
    fwrite(fp, str)
    fclose(fp)
next

func getFileSize fp
     C_FILESTART = 0
     C_FILEEND = 2
     fseek(fp,0,C_FILEEND)
     nFileSize = ftell(fp)
     fseek(fp,0,C_FILESTART)
     return nFileSize


ruby -pi -e "gsub('Goodbye London!', 'Hello New York!')" a.txt b.txt c.txt


file$(1) ="data1.txt"
file$(2) ="data2.txt"
file$(3) ="data3.txt"

for i = 1 to 3
    open file$(i) for input as #in
        fileBefore$ = input$( #in, lof( #in))
    close #in

    fileAfter$ = strRep$(fileBefore$, "Goodbye London!", "Hello New York!")
    open "new_" +  file$(i) for output as #out
        print #out,fileAfter$;
    close #out
next i
end

' --------------------------------
' string replace - rep str with
' --------------------------------
FUNCTION strRep$(str$,rep$,with$)
ln  = len(rep$)
ln1 = ln - 1
i   = 1
while i <= len(str$)
    if mid$(str$,i,ln) = rep$ then
        strRep$ = strRep$ + with$
        i = i + ln1
    else
        strRep$ = strRep$ + mid$(str$,i,1)
    end if
i = i + 1
WEND
END FUNCTION


//! Author: Rahul Sharma
//! Github: <https://github.com/creativcoder>

use std::fs::File;
use std::fs::OpenOptions;
use std::io::BufRead;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::Write;

fn main() {
    // opens file for writing replaced lines
    let out_fd = OpenOptions::new()
        .write(true)
        .create(true)
        .open("resources/output.txt");

    // defining a closure write_line
    let write_line = |line: &str| match out_fd {
        Ok(ref v) => {
            let mut writer = BufWriter::new(v);
            writer.write_all(line.as_bytes()).unwrap();
        }
        Err(ref e) => {
            println!("Error:{}", e);
        }
    };
    // read input file
    match File::open("resources/paragraph.txt") {
        Ok(handle) => {
            let mut reader = BufReader::new(handle);
            let mut line = String::new();
            // read the first line
            reader.read_line(&mut line).unwrap();
            // loop until line end
            while line.trim() != "" {
                let mut replaced_line = line.trim().replace("Goodbye London!", "Hello New York!");
                replaced_line += "\n";
                write_line(&replaced_line[..]);
                line.clear();
                reader.read_line(&mut line).unwrap();
            }
        }
        Err(e) => println!("Error:{}", e),
    }
}


import java.io.{File, PrintWriter}

object GloballyReplaceText extends App {

  val (charsetName, fileNames) = ("UTF8", Seq("file1.txt", "file2.txt"))
  for (fileHandle <- fileNames.map(new File(_)))
    new PrintWriter(fileHandle, charsetName) {
      print(scala.io.Source.fromFile(fileHandle, charsetName).mkString
        .replace("Goodbye London!", "Hello New York!"))
      close()
    }

}


sed -i 's/Goodbye London!/Hello New York!/g' a.txt b.txt c.txt


$ include "seed7_05.s7i";
  include "getf.s7i";

const proc: main is func
  local
    var string: fileName is "";
    var string: content is "";
  begin
    for fileName range [] ("a.txt", "b.txt", "c.txt") do
      content := getf(fileName);
      content := replace(content, "Goodbye London!", "Hello New York!");
      putf(fileName, content);
    end for;
  end func;


var names = %w(
                a.txt
                b.txt
                c.txt
              )

names.map{ File(_) }.each { |file|
    say file.edit { |line|
        line.gsub("Goodbye London!", "Hello New York!")
    }
}


package require Tcl 8.5
package require fileutil

# Parameters to the replacement
set from "Goodbye London!"
set to "Hello New York!"
# Which files to replace
set fileList [list a.txt b.txt c.txt]

# Make a command fragment that performs the replacement on a supplied string
set replacementCmd [list string map [list $from $to]]
# Apply the replacement to the contents of each file
foreach filename $fileList {
    fileutil::updateInPlace $filename $replacementCmd
}


#lang transd

MainModule: {
    _start: (λ
        (with files ["a.txt" "b.txt" "c.txt"] fs FileStream()
            (for f in files do
                (open-r fs f)
                (with s (replace (read-text fs)
                        "Goodbye London!" "Hello New York!")
                    (close fs)
                    (open-w fs f)
                    (write fs (to-bytes s) (size s)))))
    )
}


$$ MODE TUSCRIPT
files="a.txt'b.txt'c.txt"

BUILD S_TABLE search = ":Goodbye London!:"

LOOP file=files
 ERROR/STOP OPEN (file,WRITE,-std-)
 ERROR/STOP CREATE ("scratch",FDF-o,-std-)
  ACCESS q: READ/STREAM/RECORDS/UTF8 $file s,aken+text/search+eken
  ACCESS s: WRITE/ERASE/STREAM/UTF8 "scratch" s,aken+text+eken
   LOOP
    READ/EXIT q
    IF (text.ct.search) SET text="Hello New York!"
    WRITE/ADJUST s
   ENDLOOP
  ENDACCESS/PRINT q
  ENDACCESS/PRINT s
 ERROR/STOP COPY ("scratch",file)
 ERROR/STOP CLOSE (file)
ENDLOOP
ERROR/STOP DELETE ("scratch")


@(next :args)
@(repeat)
@file
@(next `@file`)
@(freeform)
@(coll :gap 0)@[email protected]{match /Goodbye, London!/}@(end)@*[email protected]/\n/
@(output `@file.tmp`)
@(rep)@{notmatch}Hello, New [email protected](end)@tail
@(end)
@(do @(rename-path `@file.tmp` file))
@(end)


replace() {
    local search=$1 replace=$2
    local file lines line
    shift 2
    for file in "[email protected]"; do
        lines=()
        while IFS= read -r line; do
            lines+=( "${line//$search/$replace}" )
        done < "$file"
        printf "%s\n" "${lines[@]}" > "$file"
    done
}
replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt


Const ForReading = 1
Const ForWriting = 2

strFiles = Array("test1.txt", "test2.txt", "test3.txt")

With CreateObject("Scripting.FileSystemObject")
	For i = 0 To UBound(strFiles)
		strText = .OpenTextFile(strFiles(i), ForReading).ReadAll()
		With .OpenTextFile(strFiles(i), ForWriting)
			.Write Replace(strText, "Goodbye London!", "Hello New York!")
			.Close
		End With
	Next
End With


File_Open("files.lst")          // list of files to process
#20 = Reg_Free                  // text register for filename

While(!At_EOF) {
    Reg_Copy_Block(#20, Cur_Pos, EOL_Pos)
    File_Open(@(#20))
    Replace("Goodbye London!", "Hello New York!", BEGIN+ALL+NOERR)
    Buf_Close(NOMSG)
    Line(1, ERRBREAK)
}

Reg_Empty(#20)                  // Cleanup
Buf_Quit(OK)


import "io" for File

var files = ["file1.txt", "file2.txt"]
for (file in files) {
    var text = File.read(file)
    System.print("%(file) contains: %(text)")
    text = text.replace("Goodbye London!", "Hello New York!")
    File.create(file) { |f|  // overwrites existing file
        f.writeBytes(text)
    }
    System.print("%(file) now contains: %(File.read(file))")
}


include c:\cxpl\codes;          \intrinsic 'code' declarations
string 0;                       \use zero-terminated strings

func StrLen(A);                 \Return number of characters in an ASCIIZ string
char A;
int  I;
for I:= 0 to -1>>1-1 do
    if A(I) = 0 then return I;

func StrFind(A, B);             \Search for ASCIIZ string A in string B
\Returns address of first occurrence of string A in B, or zero if A is not found
char A, B;                      \strings to be compared
int  LA, LB, I, J;
[LA:= StrLen(A);
LB:= StrLen(B);
for I:= 0 to LB-LA do
    [for J:= 0 to LA-1 do
        if A(J) # B(J+I) then J:= LA+1;
    if J = LA then return B+I;  \found
    ];
return 0;
];

proc ReplaceText(FileName);     \replace text in specified file
char FileName;
char Str(1_000_000), Hello, Bye, Pointer;
int  Handle, I, C;
[Handle:= FOpen(FileName, 0);   \get handle for input file
FSet(Handle, ^I);               \set device 3 input to file handle
OpenI(3);                       \initialize buffer pointers
I:= 0;
repeat  C:= ChIn(3);            \read file into memory
        Str(I):= C;
        I:= I+1;
until   C = $1A; \EOF
FClose(Handle);                 \release handle

Hello:= "Hello New York!";      \replacement text
Bye:=   "Goodbye London!";
Pointer:= StrFind(Bye, Str);
if Pointer \#0\ then            \overwrite (both strings are same length)
   for I:= 0 to 15-1 do Pointer(I):= Hello(I);

Handle:= FOpen(FileName, 1);    \get handle for output file
FSet(Handle, ^O);               \set device 3 output to file handle
OpenO(3);
I:= 0;
repeat  C:= Str(I);             \write file from memory
        I:= I+1;
        ChOut(3, C);
until   C = $1A; \EOF
Close(3);                       \flush output buffer
FClose(Handle);                 \release handle
];

int File, I;
[File:= ["Alpha.txt", "Beta.txt", "Gamma.txt", "Delta.txt"];
for I:= 0 to 4-1 do ReplaceText(File(I));
]


fcn sed(data,src,dst){
   srcSz:=src.len(); dstSz:=dst.len(); md5:=Utils.MD5.calc(data);
   n:=0; while(Void!=(n:=data.find(src,n)))
           { data.del(n,srcSz); data.insert(n,dst); n+= dstSz; }
   return(md5!=Utils.MD5.calc(data)); // changed?
}
fcn sedFile(fname,src,dst){
   f:=File(fname,"r"); data:=f.read(); f.close();
   if(sed(data,"Goodbye London!", "Hello New York!"))
      { f:=File(fname,"w"); f.write(data); f.close(); }
}


F random960()
   V start = [‘R’, ‘K’, ‘R’]

   L(piece) [‘Q’, ‘N’, ‘N’]
      start.insert(random:(start.len + 1), piece)

   V bishpos = random:(start.len + 1)
   start.insert(bishpos, Char(‘B’))
   start.insert(random:(bishpos + 1), Char(‘B’))
   R start

print(random960())


DEFINE MAX_NUMBERS="200"
DEFINE MAX_LEN="20"
DEFINE MAX_FACTORS="5"
DEFINE PTR="CARD"

PROC PrintResult(BYTE max,n BYTE ARRAY factors PTR ARRAY texts)
  BYTE i,j,t
  BYTE ARRAY values(MAX_FACTORS)

  FOR j=0 TO n-1
  DO
    values(j)=1
  OD

  FOR i=1 TO max
  DO
    t=0
    FOR j=0 TO n-1
    DO
      IF values(j)=0 THEN
        t=1 Print(texts(j))
      FI
      values(j)==+1
      IF values(j)=factors(j) THEN
        values(j)=0
      FI
    OD
    IF t=0 THEN PrintB(i) FI
    Put(32)
  OD
RETURN

BYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err)
  BYTE i

  FOR i=1 TO s(0)
  DO
    IF s(i)=c THEN
      err^=0 RETURN (i)
    FI
  OD
  err^=1
RETURN (0)

PROC Main()
  BYTE max,i,n,pos,err
  BYTE ARRAY factors(MAX_FACTORS)
  PTR ARRAY texts(MAX_FACTORS)
  CHAR ARRAY
    s(100),tmp(100),
    t0(MAX_LEN),t1(MAX_LEN),t2(MAX_LEN),
    t3(MAX_LEN),t4(MAX_LEN)

  texts(0)=t0 texts(1)=t1 texts(2)=t2
  texts(3)=t3 texts(4)=t4

  DO
    PrintF("Max number (1-%B): ",MAX_NUMBERS)
    max=InputB()
  UNTIL max>=1 AND max<=MAX_NUMBERS
  OD

  n=0
  DO
    PrintF("Number of rules (1-%B): ",MAX_FACTORS)
    n=InputB()
  UNTIL n>=1 AND n<=MAX_FACTORS
  OD

  FOR i=0 TO n-1
  DO
    DO
      PrintF("Rule #%B (number space text):",i+1)
      InputS(s)
      pos=Find(s,' ,@err)
      IF pos=1 OR pos=s(0) THEN
        err=1
      FI
      IF err=0 THEN
        SCopyS(tmp,s,1,pos-1)
        factors(i)=ValB(tmp)
        IF factors(i)<2 THEN
          err=1
        FI
        SCopyS(texts(i),s,pos+1,s(0))
      FI
    UNTIL err=0
    OD
  OD

  PutE()
  PrintResult(max,n,factors,texts)
RETURN


Loop, 5
	Out .= Chess960() "`n"
MsgBox, % RTrim(Out, "`n")

Chess960() {
	P := {}
	P[K := Rand(2, 7)] := Chr(0x2654)	; King
	P[Rand(1, K - 1)] := Chr(0x2656)	; Rook 1
	P[Rand(K + 1, 8)] := Chr(0x2656)	; Rook 2
	Loop, 8
		Remaining .= P[A_Index] ? "" : A_Index "`n"
	Sort, Remaining, Random N
	P[Bishop1 := SubStr(Remaining, 1, 1)] := Chr(0x2657)	; Bishop 1
	Remaining := SubStr(Remaining, 3)
	Loop, Parse, Remaining, `n
		if (Mod(Bishop1 - A_LoopField, 2))
			Odd .= A_LoopField "`n"
		else
			Even .= A_LoopField "`n"
	X := StrSplit(Odd Even, "`n")
	P[X.1] := Chr(0x2657)	; Bishop 2
	P[X.2] := Chr(0x2655)	; Queen
	P[X.3] := Chr(0x2658)	; Knight 1
	P[X.4] := Chr(0x2658)	; Knight 2
	for Key, Val in P
		Out .= Val
	return Out
}

Rand(Min, Max) {
	Random, n, Min, Max
	return n
}


for i = 1 to 10
  inicio$ = "RKR"
  pieza$ = "QNN"

  for n = 1 to length(pieza$)
    posic = int(rand*(length(inicio$) + 1)) + 1
    inicio$ = left(inicio$, posic-1) + mid(pieza$, n, 1) + right(inicio$, length(inicio$) - posic + 1)
  next n
  posic = int(rand*(length(inicio$) + 1)) + 1
  inicio$ = left(inicio$, posic-1) + "B" + right(inicio$, length(inicio$) - posic + 1)
  posic += 1 + 2 * int(int(rand*(length(inicio$) - posic)) / 2)
  inicio$ = left(inicio$, posic-1) + "B" + right(inicio$, length(inicio$) - posic + 1)
  print inicio$
next i
end


#include<stdlib.h>
#include<locale.h>
#include<wchar.h>
#include<stdio.h>
#include<time.h>

char rank[9];

int pos[8];

void swap(int i,int j){
	int temp = pos[i];
	pos[i] = pos[j];
	pos[j] = temp;
}

void generateFirstRank(){
	 int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;

	 for(i=0;i<8;i++){
		 rank[i] = 'e';
		 pos[i] = i;
	 }

	 do{
		 kPos = rand()%8;
		 rPos1 = rand()%8;
		 rPos2 = rand()%8;
	 }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));

	 rank[pos[rPos1]] = 'R';
	 rank[pos[kPos]] = 'K';
	 rank[pos[rPos2]] = 'R';

	 swap(rPos1,7);
	 swap(rPos2,6);
	 swap(kPos,5);

	 do{
		 bPos1 = rand()%5;
		 bPos2 = rand()%5;
	 }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));

	 rank[pos[bPos1]] = 'B';
	 rank[pos[bPos2]] = 'B';

	 swap(bPos1,4);
	 swap(bPos2,3);

	 do{
		 qPos = rand()%3;
		 nPos1 = rand()%3;
	 }while(qPos==nPos1);

	 rank[pos[qPos]] = 'Q';
	 rank[pos[nPos1]] = 'N';

	 for(i=0;i<8;i++)
		 if(rank[i]=='e'){
			 rank[i] = 'N';
			 break;
		 }
}

void printRank(){
	int i;

	#ifdef _WIN32
		printf("%s\n",rank);
	#else
	{
		setlocale(LC_ALL,"");
		printf("\n");
		for(i=0;i<8;i++){
			if(rank[i]=='K')
				printf("%lc",(wint_t)9812);
			else if(rank[i]=='Q')
				printf("%lc",(wint_t)9813);
			else if(rank[i]=='R')
				printf("%lc",(wint_t)9814);
			else if(rank[i]=='B')
				printf("%lc",(wint_t)9815);
			if(rank[i]=='N')
				printf("%lc",(wint_t)9816);
		}
	}
	#endif
}

int main()
{
	int i;

	srand((unsigned)time(NULL));

	for(i=0;i<9;i++){
		generateFirstRank();
		printRank();
	}

	return 0;
}


#include <iostream>
#include <string>
#include <time.h>
using namespace std;

namespace
{
    void placeRandomly(char* p, char c)
    {
	int loc = rand() % 8;
	if (!p[loc])
	    p[loc] = c;
	else
	    placeRandomly(p, c);    // try again
    }
    int placeFirst(char* p, char c, int loc = 0)
    {
	while (p[loc]) ++loc;
	p[loc] = c;
        return loc;
    }

    string startPos()
    {
	char p[8]; memset( p, 0, 8 );

	// bishops on opposite color
	p[2 * (rand() % 4)] = 'B';
	p[2 * (rand() % 4) + 1] = 'B';

	// queen knight knight, anywhere
	for (char c : "QNN")
	    placeRandomly(p, c);

	// rook king rook, in that order
	placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));

	return string(p, 8);
    }
}   // leave local

namespace chess960
{
    void generate( int c )
    {
	for( int x = 0; x < c; x++ )
	    cout << startPos() << "\n";
    }
}

int main( int argc, char* argv[] )
{
    srand( time( NULL ) );
    chess960::generate( 10 );
    cout << "\n\n";
    return system( "pause" );
}


(ns c960.core
  (:gen-class)
  (:require [clojure.string :as s]))

;; legal starting rank - unicode chars for rook, knight, bishop, queen, king, bishop, knight, rook
(def starting-rank [\♖ \♘ \♗ \♕ \♔ \♗ \♘ \♖])

(defn bishops-legal?
  "True if Bishops are odd number of indicies apart"
  [rank]
  (odd? (apply - (cons 0 (sort > (keep-indexed #(when (= \♗ %2) %1) rank))))))

(defn king-legal?
  "True if the king is between two rooks"
  [rank]
  (let [king-&-rooks (filter #{\♔ \♖} rank)]
    (and
     (= 3 (count king-&-rooks))
     (= \u2654 (second king-&-rooks)))))

(defn c960
  "Return a legal rank for c960 chess"
  ([] (c960 1))
  ([n]
   (->> #(shuffle starting-rank)
        repeatedly
        (filter #(and (king-legal? %) (bishops-legal? %)))
        (take n)
        (map #(s/join ", " %)))))

(c960)
;; => "♗, ♖, ♔, ♕, ♘, ♘, ♖, ♗"
(c960)
;; => "♖, ♕, ♘, ♔, ♗, ♗, ♘, ♖"
(c960 4)
;; => ("♘, ♖, ♔, ♘, ♗, ♗, ♖, ♕" "♗, ♖, ♔, ♘, ♘, ♕, ♖, ♗" "♘, ♕, ♗, ♖, ♔, ♗, ♘, ♖" "♖, ♔, ♘, ♘, ♕, ♖, ♗, ♗")


(defun chess960-from-sp-id
  (&optional (sp-id (random 360 (make-random-state t))))
    (labels
      ((combinations (lst r)
          (cond
            ((numberp lst)
              (combinations (loop for i from 0 while (< i lst) collect i) r))
            ((= r 1)
              (mapcar #'list lst))
            (t
              (loop for i in lst append
                (let ((left (loop for j in lst if (< i j) collect j)))
                  (mapcar (lambda (c) (cons i c))
                          (combinations left (1- r))))))))

       (enumerate (ary)
          (loop for item across ary for index from 0
                collect (list index item))))

       (let*
         ((first-bishop -1)
          (knight-combo '())
          (placements (list
            ;divisor  function to get position                              piece symbol
            (list  4  (lambda (n) (setq first-bishop n)
                                  (1+ (* 2 n)))                             '♝)
            (list  4  (lambda (n) ( - (* 2 n) (if (> n first-bishop) 1 0))) '♝)
            (list  6  #'identity                                            '♛)
            (list 10  (lambda (n)
                        (setq knight-combo (nth n (combinations 5 2)))
                        (car knight-combo))                                 '♞)
            (list  1  (lambda (n) (1- (cadr knight-combo)))                 '♞)
            (list  1  (lambda (n) 0)                                        '♜)
            (list  1  (lambda (n) 0)                                        '♚)
            (list  1  (lambda (n) 0)                                        '♜)))
          (p sp-id)
          (ary (make-array 8 :initial-element '-)))

         (loop for (divisor func piece) in placements doing
           (let* ((n (mod p divisor))
             (square (funcall func n)))
              (setq p (floor p divisor))
              (setq index
                (car (nth square (remove-if-not (lambda (p) (eq (cadr p) '-))
                                                (enumerate ary)))))
              (setf (aref ary index) piece)))

      (list sp-id ary))))

;; demo

(format t "~a~%" (chess960-from-sp-id 518))
(format t "~a~%" (chess960-from-sp-id))


void main() {
    import std.stdio, std.range, std.algorithm, std.string, permutations2;

    const pieces = "KQRrBbNN";
    alias I = indexOf;
    auto starts = pieces.dup.permutations.filter!(p =>
            I(p, 'B') % 2 != I(p, 'b') % 2 && // Bishop constraint.
            // King constraint.
            ((I(p, 'r') < I(p, 'K') && I(p, 'K') < I(p, 'R')) ||
             (I(p, 'R') < I(p, 'K') && I(p, 'K') < I(p, 'r'))))
        .map!toUpper.array.sort().uniq;
    writeln(starts.walkLength, "\n", starts.front);
}


(define-values (K Q R B N) (iota 5))
(define *pos* (list R N B Q K B N R)) ;; standard starter

;; check opposite color bishops, and King between rooks
(define (legal-pos p)
    (and
            (> (list-index K p) (list-index R p))
            (> (list-index K (reverse p)) (list-index R (reverse p)))
            (even? (+ (list-index B p) (list-index B (reverse p))))))

;; random shuffle current position until a legal one is found
(define (c960)
	(set! *pos* (shuffle *pos*))
	(if (legal-pos *pos*)
		(map unicode-piece *pos*)  (c960)))


defmodule Chess960 do
  @pieces   ~w(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖)             # ~w(K Q N N B B R R)
  @regexes  [~r/♗(..)*♗/, ~r/♖.*♔.*♖/]        # [~r/B(..)*B/, ~r/R.*K.*R/]

  def shuffle do
    row = Enum.shuffle(@pieces) |> Enum.join
    if Enum.all?(@regexes, &Regex.match?(&1, row)), do: row, else: shuffle
  end
end

Enum.each(1..5, fn _ -> IO.puts Chess960.shuffle end)


USING: io kernel math random sequences ;
IN: rosetta-code.chess960

: empty ( seq -- n ) 32 swap indices random ;           ! return a random empty index (i.e. equal to 32) of seq
: next ( seq -- n ) 32 swap index ;                     ! return the leftmost empty index of seq
: place ( seq elt n -- seq' ) rot [ set-nth ] keep ;    ! set nth member of seq to elt, keeping seq on the stack

: white-bishop ( -- elt n ) CHAR: ♗ 4 random 2 * ;
: black-bishop ( -- elt n ) white-bishop 1 + ;
: queen ( seq -- seq elt n ) CHAR: ♕ over empty ;
: knight ( seq -- seq elt n ) CHAR: ♘ over empty ;
: rook ( seq -- seq elt n ) CHAR: ♖ over next ;
: king ( seq -- seq elt n ) CHAR: ♔ over next ;

: chess960 ( -- str )
    "        " clone
    black-bishop place
    white-bishop place
    queen place
    knight place
    knight place
    rook place
    king place
    rook place ;

: chess960-demo ( -- ) 5 [ chess960 print ] times ;

MAIN: chess960-demo


\ make starting position for Chess960, constructive

\             0    1    2    3    4    5    6    7    8    9
create krn S" NNRKRNRNKRNRKNRNRKRNRNNKRRNKNRRNKRNRKNNRRKNRNRKRNN" mem,

create pieces 8 allot

: chess960 ( n -- )
  pieces 8 erase
  4 /mod swap  2* 1+ pieces + 'B swap c!
  4 /mod swap  2*    pieces + 'B swap c!
  6 /mod swap  pieces swap bounds begin dup [email protected] if swap 1+ swap then 2dup > while 1+ repeat drop 'Q swap c!
  5 * krn +  pieces 8 bounds do i [email protected] 0= if dup [email protected] i c! 1+ then loop drop
  cr pieces 8 type ;

0   chess960   \ BBQNNRKR ok
518 chess960   \ RNBQKBNR ok
959 chess960   \ RKRNNQBB ok

960 choose chess960    \ random position


program chess960
    implicit none

    integer, pointer  :: a,b,c,d,e,f,g,h
    integer, target   :: p(8)
    a => p(1)
    b => p(2)
    c => p(3)
    d => p(4)
    e => p(5)
    f => p(6)
    g => p(7)
    h => p(8)

    king: do a=2,7                                        ! King on an internal square
        r1: do b=1,a-1                                    ! R1 left of the King
            r2: do c=a+1,8                                ! R2 right of the King
                b1: do d=1,7,2                            ! B1 on an odd square
                    if (skip_pos(d,4)) cycle
                    b2: do e=2,8,2                        ! B2 on an even square
                        if (skip_pos(e,5)) cycle
                        queen: do f=1,8                   ! Queen anywhere else
                            if (skip_pos(f,6)) cycle
                            n1: do g=1,7                  ! First knight
                                if (skip_pos(g,7)) cycle
                                n2: do h=g+1,8            ! Second knight (indistinguishable from first)
                                    if (skip_pos(h,8)) cycle
                                    if (sum(p) /= 36) stop 'Loop error'  ! Sanity check
                                    call write_position
                                end do n2
                            end do n1
                        end do queen
                    end do b2
                end do b1
            end do r2
        end do r1
    end do king

contains

    logical function skip_pos(i, n)
        integer, intent(in) :: i, n
        skip_pos = any(p(1:n-1) == i)
    end function skip_pos

    subroutine write_position
        integer           :: i, j
        character(len=15) :: position = ' '
        character(len=1), parameter  :: names(8) = ['K','R','R','B','B','Q','N','N']
        do i=1,8
            j = 2*p(i)-1
            position(j:j) = names(i)
        end do
        write(*,'(a)') position
    end subroutine write_position

end program chess960


package main

import (
    "fmt"
    "math/rand"
)

type symbols struct{ k, q, r, b, n rune }

var A = symbols{'K', 'Q', 'R', 'B', 'N'}
var W = symbols{'♔', '♕', '♖', '♗', '♘'}
var B = symbols{'♚', '♛', '♜', '♝', '♞'}

var krn = []string{
    "nnrkr", "nrnkr", "nrknr", "nrkrn",
    "rnnkr", "rnknr", "rnkrn",
    "rknnr", "rknrn",
    "rkrnn"}

func (sym symbols) chess960(id int) string {
    var pos [8]rune
    q, r := id/4, id%4
    pos[r*2+1] = sym.b
    q, r = q/4, q%4
    pos[r*2] = sym.b
    q, r = q/6, q%6
    for i := 0; ; i++ {
        if pos[i] != 0 {
            continue
        }
        if r == 0 {
            pos[i] = sym.q
            break
        }
        r--
    }
    i := 0
    for _, f := range krn[q] {
        for pos[i] != 0 {
            i++
        }
        switch f {
        case 'k':
            pos[i] = sym.k
        case 'r':
            pos[i] = sym.r
        case 'n':
            pos[i] = sym.n
        }
    }
    return string(pos[:])
}

func main() {
    fmt.Println(" ID  Start position")
    for _, id := range []int{0, 518, 959} {
        fmt.Printf("%3d  %s\n", id, A.chess960(id))
    }
    fmt.Println("\nRandom")
    for i := 0; i < 5; i++ {
        fmt.Println(W.chess960(rand.Intn(960)))
    }
}


import Data.List
import qualified Data.Set as Set

data Piece = K | Q | R | B | N deriving (Eq, Ord, Show)

isChess960 :: [Piece] -> Bool
isChess960 rank =
  (odd . sum $ findIndices (== B) rank) && king > rookA && king < rookB
  where
    Just king      = findIndex (== K) rank
    [rookA, rookB] = findIndices (== R) rank

main :: IO ()
main = mapM_ (putStrLn . concatMap show) . Set.toList . Set.fromList
       . filter isChess960 $ permutations [R,N,B,Q,K,B,N,R]


row0=: u: 9812+2}.5|i.10
king=: u:9812
rook=: u:9814
bish=: u:9815
pos=: [email protected]
bishok=: 1=2+/ .| pos&bish
rookok=: pos&rook -: (<./,>./)@pos&(rook,king)
ok=: bishok*rookok
perm=: A.&i.~ !
valid=: (#~ ok"1) ~.row0{"1~perm 8
gen=: valid {~ ? bind 960


import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Chess960{
	private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');

	public static List<Character> generateFirstRank(){
		do{
			Collections.shuffle(pieces);
		}while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", ""))); //List.toString adds some human stuff, remove that

		return pieces;
	}

	private static boolean check(String rank){
		if(!rank.matches(".*R.*K.*R.*")) return false;			//king between rooks
		if(!rank.matches(".*B(..|....|......|)B.*")) return false;	//all possible ways bishops can be placed
		return true;
	}

	public static void main(String[] args){
		for(int i = 0; i < 10; i++){
			System.out.println(generateFirstRank());
		}
	}
}


function ch960startPos() {
  var rank = new Array(8),
      // randomizer (our die)
      d = function(num) { return Math.floor(Math.random() * ++num) },
      emptySquares = function() {
        var arr = [];
        for (var i = 0; i < 8; i++) if (rank[i] == undefined) arr.push(i);
        return arr;
      };
  // place one bishop on any black square
  rank[d(2) * 2] = "♗";
  // place the other bishop on any white square
  rank[d(2) * 2 + 1] = "♗";
  // place the queen on any empty square
  rank[emptySquares()[d(5)]] = "♕";
  // place one knight on any empty square
  rank[emptySquares()[d(4)]] = "♘";
  // place the other knight on any empty square
  rank[emptySquares()[d(3)]] = "♘";
  // place the rooks and the king on the squares left, king in the middle
  for (var x = 1; x <= 3; x++) rank[emptySquares()[0]] = x==2 ? "♔" : "♖";
  return rank;
}

// testing (10 times)
for (var x = 1; x <= 10; x++) console.log(ch960startPos().join(" | "));


function generateposition()
    # Placeholder knights
    rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘']
    lrank = length(rank)

    # Check if a space is available
    isfree(x::Int) = rank[x] == '♘'

    # Place the King
    rank[indking = rand(2:lrank-1)] = '♔'

    # Place rooks
    rank[indrook = rand(filter(isfree, 1:lrank))] = '♖'
    if indrook > indking
        rank[rand(filter(isfree, 1:indking-1))] = '♖'
    else
        rank[rand(filter(isfree, indking+1:lrank))] = '♖'
    end

    # Place bishops
    rank[indbish = rand(filter(isfree, 1:8))] = '♗'
    pbish = filter(iseven(indbish) ? isodd : iseven, 1:lrank)
    rank[rand(filter(isfree, pbish))] = '♗'

    # Place queen
    rank[rand(filter(isfree, 1:lrank))] = '♕'
    return rank
end

@show generateposition()


object Chess960 : Iterable<String> {
    override fun iterator() = patterns.iterator()

    private operator fun invoke(b: String, e: String) {
        if (e.length <= 1) {
            val s = b + e
            if (s.is_valid()) patterns += s
        } else {
            for (i in 0 until e.length) {
                invoke(b + e[i], e.substring(0, i) + e.substring(i + 1))
            }
        }
    }

    private fun String.is_valid(): Boolean {
        val k = indexOf('K')
        return indexOf('R') < k && k < lastIndexOf('R') &&
            indexOf('B') % 2 != lastIndexOf('B') % 2
    }

    private val patterns = sortedSetOf<String>()

    init {
        invoke("", "KQRRNNBB")
    }
}

fun main(args: Array<String>) {
    Chess960.forEachIndexed { i, s -> println("$i: $s") }
}


-- Insert 'str' into 't' at a random position from 'left' to 'right'
function randomInsert (t, str, left, right)
    local pos
    repeat pos = math.random(left, right) until not t[pos]
    t[pos] = str
    return pos
end

-- Generate a random Chess960 start position for white major pieces
function chess960 ()
    local t, b1, b2 = {}
    local kingPos = randomInsert(t, "K", 2, 7)
    randomInsert(t, "R", 1, kingPos - 1)
    randomInsert(t, "R", kingPos + 1, 8)
    b1 = randomInsert(t, "B", 1, 8)
    b2 = randomInsert(t, "B", 1, 8)
    while (b2 - b1) % 2 == 0 do
        t[b2] = false
        b2 = randomInsert(t, "B", 1, 8)
    end
    randomInsert(t, "Q", 1, 8)
    randomInsert(t, "N", 1, 8)
    randomInsert(t, "N", 1, 8)
    return t
end

-- Main procedure
math.randomseed(os.time())
print(table.concat(chess960()))


Print[StringJoin[
   RandomChoice[
    Select[Union[
      Permutations[{"\[WhiteKing]", "\[WhiteQueen]", "\[WhiteRook]",
        "\[WhiteRook]", "\[WhiteBishop]", "\[WhiteBishop]",
        "\[WhiteKnight]", "\[WhiteKnight]"}]],
     MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___,
         "\[WhiteRook]", ___}] &&
       OddQ[Subtract @@ Flatten[Position[#, "\[WhiteBishop]"]]] &]]]];


// placeholder knights
rank = ["♘"] * 8

// function to get a random free space from a to b, inclusive
randFree = function(a, b)
    free = []
    for i in range(a, b)
        if rank[i] == "♘" then free.push i
    end for
    return free[rnd * free.len]
end function

// place the king
kingIdx = randFree(1, 6)
rank[kingIdx] = "♔"

// place rooks
rank[randFree(0, kingIdx - 1)] = "♖"
rank[randFree(kingIdx + 1, 7)] = "♖"

// place bishops
bishIdx = randFree(0, 7)
rank[bishIdx] = "♗"
while true
    i = randFree(0, 7)
    if i % 2 != bishIdx % 2 then break
end while
rank[i] = "♗"

// place queen
rank[randFree(0, 7)] = "♕"

print join(rank, " ")


import random, strutils

type

  # Chess pieces on first row.
  Pieces {.pure.} = enum
    King = "♔",
    Queen = "♕",
    Rook1 = "♖",
    Rook2 = "♖",
    Bishop1 = "♗",
    Bishop2 = "♗",
    Knight1 = "♘",
    Knight2 = "♘"

  # Position counted from 0.
  Position = range[0..7]

  # Position of pieces.
  Positions = array[Pieces, Position]

func pop[T](s: var set[T]): T =
  ## Remove and return the first element of a set.
  for val in s:
    result = val
    break
  s.excl(result)

proc choose[T](s: var set[T]): T =
  ## Choose randomly a value from a set and remove it from the set.
  result = sample(s)
  s.excl(result)

proc positions(): Positions =
  ## Return a randomly chosen list of piece positions for the first row.

  var pos = {Position.low..Position.high}

  # Set bishops.
  result[Bishop1] = sample([0, 2, 4, 6])    # Black squares.
  result[Bishop2] = sample([1, 3, 5, 7])    # White squares.
  pos = pos - {result[Bishop1], result[Bishop2]}

  # Set queen.
  result[Queen] = pos.choose()

  # Set knights.
  result[Knight1] = pos.choose()
  result[Knight2] = pos.choose()

  # In the remaining three pieces, the king must be between the two rooks.
  result[Rook1] = pos.pop()
  result[King] = pos.pop()
  result[Rook2] = pos.pop()

#———————————————————————————————————————————————————————————————————————————————————————————————————

randomize()

for _ in 1..10:
  var row: array[8, string]
  let pos = positions()
  for piece in Pieces:
    row[pos[piece]] = $piece
  echo row.join("  ")


class Chess960 {
  function : Main(args : String[]) ~ Nil {
    Generate(10);
  }

  function : Generate(c : Int) ~ Nil {
    for(x := 0; x < c; x += 1;) {
      StartPos()->PrintLine();
    };
  }

  function : StartPos() ~ String {
    p := Char->New[8];

    # bishops
    b1 : Int; b2 : Int;
    while(true) {
      b1 := GetPosition(); b2 := GetPosition();

      b1c := b1 and 1; b2c := b2 and 1;
      c := b1c = 0 & b2c <> 0;
      if(c) {
        break;
      };
    };
    p[b1] := 0x2657; p[b2] := 0x2657;

    # queen, knight, knight
    q := false;
    for(x := 0; x < 3; x += 1;) {
      do {
        b1 := GetPosition();
      } while( p[b1] <> '\0');

      if(<>q) {
        p[b1] := 0x2655; q := true;
      }
      else {
        p[b1] := 0x2658;
      };
    };

    # rook king rook
    q := false;
    for(x := 0; x < 3; x += 1;) {
      a := 0;
      while(a < 8) {
        if(p[a] = '\0') {
          break;
        };
        a += 1;
      };

      if(<>q) {
        p[a] := 0x2656; q := true;
      }
      else {
        p[a] := 0x2654; q := false;
      };
    };

    s := "";
    for(x := 0; x < 8; x += 1;) { s->Append(p[x]); };
    return s;
  }

  function : GetPosition() ~ Int {
    return (Float->Random() * 1000)->As(Int) % 8;
  }
}


sub rnd($) { int(rand(shift)) }

sub empties { grep !$_[0][$_], 0 .. 7 }

sub chess960 {
	my @s = (undef) x 8;
	@s[2*rnd(4), 1 + 2*rnd(4)] = qw/B B/;

	for (qw/Q N N/) {
		my @idx = empties \@s;
		$s[$idx[rnd(@idx)]] = $_;
	}

	@s[empties \@s] = qw/R K R/;
	@s
}
print "@{[chess960]}\n" for 0 .. 10;


with javascript_semantics
sequence solutions = {}
--integer d = new_dict()

for i=1 to factorial(8) do
    sequence s = permute(i,"RNBQKBNR")
--  sequence s = permute(rand(factorial(8),"RNBQKBNR")
    integer b1 = find('B',s),
            b2 = find('B',s,b1+1)
    if and_bits(b2-b1,1)=1 then
        integer k = find('K',s)
        integer r1 = find('R',s)
        integer r2 = find('R',s,r1+1)
        if r1<k and k<r2 then
            if find(s,solutions)=0 then
--          if getd_index(s,d)=0 then
--              setd(s,0,d)
                solutions = append(solutions,s)
            end if
        end if
    end if
end for
printf(1,"Found %d solutions\n",{length(solutions)})
for i=1 to 5 do
    ?solutions[rand(length(solutions))]
end for


(load "@lib/simul.l")

(seed (in "/dev/urandom" (rd 8)))

(loop
   (match
      '(@A B @B B @C)
      (shuffle '(Q B B N N 0 0 0)) )
   (NIL (bit? 1 (length @B))) )

(let Rkr '(R K R)
   (for I (append @A '(B) @B '(B) @C)
      (prin (if (=0 I) (pop 'Rkr) I)) )
   (prinl) )

(bye)


function Get-RandomChess960Start
    {
    $Starts = @()

    ForEach ( $Q  in       0..3 ) {
    ForEach ( $N1 in       0..4 ) {
    ForEach ( $N2 in ($N1+1)..5 ) {
    ForEach ( $B1 in       0..3 ) {
    ForEach ( $B2 in       0..3 ) {
        $BB = $B1 * 2 + ( $B1 -lt $B2 )
        $BW = $B2 * 2
        $Start = [System.Collections.ArrayList]( '♖', '♔', '♖' )
        $Start.Insert( $Q , '♕' )
        $Start.Insert( $N1, '♘' )
        $Start.Insert( $N2, '♘' )
        $Start.Insert( $BB, '♗' )
        $Start.Insert( $BW, '♗' )
        $Starts += ,$Start
        }}}}}

    $Index = Get-Random 960
    $StartString = $Starts[$Index] -join ''
    return $StartString
    }

Get-RandomChess960Start
Get-RandomChess960Start
Get-RandomChess960Start
Get-RandomChess960Start


>>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
                     if p.index('B') % 2 != p.index('b') % 2 		# Bishop constraint
                     and ( p.index('r') < p.index('K') < p.index('R')	# King constraint
                           or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>


pieces <- c("R","B","N","Q","K","N","B","R")

generateFirstRank <- function() {
  attempt <- paste0(sample(pieces), collapse = "")
  while (!check_position(attempt)) {
    attempt <- paste0(sample(pieces), collapse = "")
  }
  return(attempt)
}

check_position <- function(position) {
  if (regexpr('.*R.*K.*R.*', position) == -1) return(FALSE)
  if (regexpr('.*B(..|....|......|)B.*', position) == -1) return(FALSE)
  TRUE
}

convert_to_unicode <- function(s) {
  s <- sub("K","\u2654", s)
  s <- sub("Q","\u2655", s)
  s <- gsub("R","\u2656", s)
  s <- gsub("B","\u2657", s)
  s <- gsub("N","\u2658", s)
}

cat(convert_to_unicode(generateFirstRank()), "\n")


#lang racket
(define white (match-lambda ['P #\♙] ['R #\♖] ['B #\♗] ['N #\♘] ['Q #\♕] ['K #\♔]))
(define black (match-lambda ['P #\♟] ['R #\♜] ['B #\♝] ['N #\♞] ['Q #\♛] ['K #\♚]))

(define (piece->unicode piece colour)
  (match colour ('w white) ('b black)) piece)

(define (find/set!-random-slot vec val k (f values))
  (define r (f (random k)))
  (cond
    [(vector-ref vec r)
     (find/set!-random-slot vec val k f)]
    [else
     (vector-set! vec r val)
     r]))

(define (chess960-start-position)
  (define v (make-vector 8 #f))
  ;; Kings and Rooks
  (let ((k (find/set!-random-slot v (white 'K) 6 add1)))
    (find/set!-random-slot v (white 'R) k)
    (find/set!-random-slot v (white 'R) (- 7 k) (curry + k 1)))
  ;; Bishops -- so far only three squares allocated, so there is at least one of each colour left
  (find/set!-random-slot v (white 'B) 4 (curry * 2))
  (find/set!-random-slot v (white 'B) 4 (compose add1 (curry * 2)))
  ;; Everyone else
  (find/set!-random-slot v (white 'Q) 8)
  (find/set!-random-slot v (white 'N) 8)
  (find/set!-random-slot v (white 'N) 8)
  (list->string (vector->list v)))

(chess960-start-position)


repeat until m/ '♗' [..]* '♗' / { $_ = < ♖ ♖ ♖ ♕ ♗ ♗ ♘ ♘ >.pick(*).join }
s:2nd['♖'] = '♔';
say .comb;


/*REXX program generates a random starting position  for the  Chess960  game. */
parse arg seed .                       /*allow for (RANDOM BIF) repeatability.*/
if seed\==''  then call random ,,seed  /*if SEED was specified,  use the seed.*/
@.=.                                   /*define the first rank as being empty.*/
r1=random(1,6)                         /*generate the first rook:  rank 1.    */
@.r1='R'                               /*place the  first rook  on  rank1.    */
          do  until  r2\==r1  &  r2\==r1-1  &  r2\==r1+1
          r2=random(1,8)               /*find placement for the 2nd rook.     */
          end   /*forever*/
@.r2='r'                               /*place the second rook  on  rank 1.   */
k=random(min(r1, r2)+1, max(r1, r2)-1) /*find a random position for the king. */
@.k='K'                                /*place king between the two rooks.    */
          do _=0      ; b1=random(1,8);  if @.b1\==.  then iterate;  c=b1//2
            do forever; b2=random(1,8)       /* c=color of bishop ►──┘        */
            if @.b2\==. | b2==b1 | b2//2==c  then iterate /*is a bad position?*/
            leave _                    /*found position for the 2 clergy*/
            end   /*forever*/          /* [↑]  find a place for the 1st bishop*/
          end     /* _ */              /* [↑]    "  "   "    "   "  2nd    "  */
@.b1='B'                               /*place the  1st  bishop on  rank 1.   */
@.b2='b'                               /*  "    "   2nd     "    "    "  "    */
                                       /*place the two knights on rank 1.     */
   do  until @._='N';  _=random(1,8);   if @._\==.  then iterate; @._='N';   end
   do  until @.!='n';  !=random(1,8);   if @.!\==.  then iterate; @.!='n';   end
_=                                     /*only the queen is left to be placed. */
   do i=1  for 8;  _=_ || @.i;   end   /*construct the output: first rank only*/
say translate(translate(_, 'q', .))    /*stick a fork in it,  we're all done. */


pieces = %i(♔ ♕ ♘ ♘ ♗ ♗ ♖ ♖)
regexes = [/♗(..)*♗/, /♖.*♔.*♖/]
row = pieces.shuffle.join until regexes.all?{|re| re.match(row)}
puts row


use std::collections::BTreeSet;

struct Chess960 ( BTreeSet<String> );

impl Chess960 {
    fn invoke(&mut self, b: &str, e: &str) {
        if e.len() <= 1 {
            let s = b.to_string() + e;
            if Chess960::is_valid(&s) { self.0.insert(s); }
        } else {
            for (i, c) in e.char_indices() {
                let mut b = b.to_string();
                b.push(c);
                let mut e = e.to_string();
                e.remove(i);
                self.invoke(&b, &e);
            }
        }
    }

    fn is_valid(s: &str) -> bool {
        let k = s.find('K').unwrap();
        k > s.find('R').unwrap() && k < s.rfind('R').unwrap() && s.find('B').unwrap() % 2 != s.rfind('B').unwrap() % 2
    }
}

// Program entry point.
fn main() {
    let mut chess960 = Chess960(BTreeSet::new());
    chess960.invoke("", "KQRRNNBB");

    for (i, p) in chess960.0.iter().enumerate() {
        println!("{}: {}", i, p);
    }
}


import scala.annotation.tailrec

object Chess960 extends App {

  private val pieces = List('♖', '♗', '♘', '♕', '♔', '♘', '♗', '♖')

  @tailrec
  private def generateFirstRank(pieces: List[Char]): List[Char] = {
    def check(rank: String) =
      rank.matches(".*♖.*♔.*♖.*") && rank.matches(".*♗(..|....|......|)♗.*")

    val p = scala.util.Random.shuffle(pieces)
    if (check(p.toString.replaceAll("[^\\p{Upper}]", "")))
      generateFirstRank(pieces)
    else p
  }

  loop(10)

  @tailrec
  private def loop(n: Int): Unit = {
    println(generateFirstRank(pieces))
    if (n <= 0) () else loop(n - 1)
  }
}


(import (scheme base) (scheme write)
        (srfi 1)    ; list library
        (srfi 27))  ; random numbers

(random-source-randomize! default-random-source)

;; Random integer in [start, end)
(define (random-between start end)
  (let ((len (- end start 1)))
    (if (< len 2)
      start
      (+ start (random-integer len)))))

;; Random item in list
(define (random-pick lst)
  (if (= 1 (length lst))
    (car lst)
    (list-ref lst (random-integer (length lst)))))

;; Construct a random piece placement for Chess960
(define (random-piece-positions)
  (define (free-indices positions) ; return list of empty slot indices
    (let loop ((i 0)
               (free '()))
      (if (= 8 i)
        free
        (loop (+ 1 i)
              (if (string=? "." (vector-ref positions i))
                (cons i free)
                free)))))
  ;
  (define (place-king+rooks positions)
    (let ((king-posn (random-between 1 8)))
      (vector-set! positions king-posn "K")
      ; left-rook is between left-edge and king
      (vector-set! positions (random-between 0 king-posn) "R")
      ; right-rook is between right-edge and king
      (vector-set! positions (random-between (+ 1 king-posn) 8) "R")))
  ;
  (define (place-bishops positions)
    (let-values (((evens odds) (partition even? (free-indices positions))))
                (vector-set! positions (random-pick evens) "B")
                (vector-set! positions (random-pick odds) "B")))
  ;
  (let ((positions (make-vector 8 ".")))
    (place-king+rooks positions)
    (place-bishops positions)
    ;; place the queen in a random remaining slot
    (vector-set! positions (random-pick (free-indices positions)) "Q")
    ;; place the two knights in the remaining slots
    (for-each (lambda (idx) (vector-set! positions idx "N"))
              (free-indices positions))

    positions))

(display "First rank: ") (display (random-piece-positions)) (newline)


$ include "seed7_05.s7i";

const proc: main is func
  local
    var string: start is "RKR";
    var char: piece is ' ';
    var integer: pos is 0;
  begin
    for piece range "QNN" do
      pos := rand(1, succ(length(start)));
      start := start[.. pred(pos)] & str(piece) & start[pos ..];
    end for;
    pos := rand(1, succ(length(start)));
    start := start[.. pred(pos)] & "B" & start[pos ..];
    pos := succ(pos) + 2 * rand(0, (length(start) - pos) div 2);
    start := start[.. pred(pos)] & "B" & start[pos ..];
    writeln(start);
  end func;


func is_valid_960 (backrank) {
    var king = backrank.index('♚')
    var (rook1, rook2) = backrank.indices_of('♜')...
    king.is_between(rook1, rook2) || return false
    var (bishop1, bishop2) = backrank.indices_of('♝')...
    bishop1+bishop2 -> is_odd
}

func random_960_position(pieces = <♛ ♚ ♜ ♜ ♝ ♝ ♞ ♞>) {
    pieces.shuffle.permutations {|*a|
        return a if is_valid_960(a)
    }
}

say random_960_position().join(' ')


func isValid960Position(_ firstRank: String) -> Bool {
  var rooksPlaced = 0
  var bishopColor = -1

  for (i, piece) in firstRank.enumerated() {
    switch piece {
    case "♚" where rooksPlaced != 1:
      return false
    case "♜":
      rooksPlaced += 1
    case "♝" where bishopColor == -1:
      bishopColor = i & 1
    case "♝" where bishopColor == i & 1:
      return false
    case _:
      continue
    }
  }

  return true
}

struct Chess960Counts {
  var king = 0, queen = 0, rook = 0, bishop = 0, knight = 0

  subscript(_ piece: String) -> Int {
    get {
      switch piece {
      case "♚": return king
      case "♛": return queen
      case "♜": return rook
      case "♝": return bishop
      case "♞": return knight
      case _:   fatalError()
      }
    }

    set {
      switch piece {
      case "♚": king = newValue
      case "♛": queen = newValue
      case "♜": rook = newValue
      case "♝": bishop = newValue
      case "♞": knight = newValue
      case _:   fatalError()
      }
    }
  }
}

func get960Position() -> String {
  var counts = Chess960Counts()
  var bishopColor = -1 // 0 - white 1 - black
  var output = ""

  for i in 1...8 {
    let validPieces = [
      counts["♜"] == 1 && counts["♚"] == 0 ? "♚" : nil, // king
      i == 1 || (counts["♛"] == 0) ? "♛" : nil, // queen
      i == 1 || (counts["♜"] == 0 || counts["♜"] < 2 && counts["♚"] == 1) ? "♜" : nil, // rook
      i == 1 || (counts["♝"] < 2 && bishopColor == -1 || bishopColor != i & 1) ? "♝" : nil, // bishop
      i == 1 || (counts["♞"] < 2) ? "♞" : nil // knight
    ].lazy.compactMap({ $0 })

    guard let chosenPiece = validPieces.randomElement() else {
      // Need to swap last piece with a bishop
      output.insert("♝", at: output.index(before: output.endIndex))

      break
    }

    counts[chosenPiece] += 1
    output += chosenPiece

    if bishopColor == -1 && chosenPiece == "♝" {
      bishopColor = i & 1
    }
  }

  assert(isValid960Position(output), "invalid 960 position \(output)")

  return output
}

var positions = Set<String>()

while positions.count != 960 {
  positions.insert(get960Position())
}

print(positions.count, positions.randomElement()!)


package require struct::list

proc chess960 {} {
    while true {
	set pos [join [struct::list shuffle {N N B B R R Q K}] ""]
	if {[regexp {R.*K.*R} $pos] && [regexp {B(..)*B} $pos]} {
	    return $pos
	}
    }
}

# A simple renderer
proc chessRender {position} {
    string map {P ♙ N ♘ B ♗ R ♖ Q ♕ K ♔} $position
}

# Output multiple times just to show scope of positions
foreach - {1 2 3 4 5} {puts [chessRender [chess960]]}


import "random" for Random
import "/dynamic" for Tuple
import "/fmt" for Fmt

var Symbols = Tuple.create("Symbols", ["k", "q", "r", "b", "n"])

var A = Symbols.new("K", "Q", "R", "B", "N")
var W = Symbols.new("♔", "♕", "♖", "♗", "♘")
var B = Symbols.new("♚", "♛", "♜", "♝", "♞")

var krn = [
    "nnrkr", "nrnkr", "nrknr", "nrkrn",
    "rnnkr", "rnknr", "rnkrn",
    "rknnr", "rknrn",
    "rkrnn"
]

var NUL = "\0"

var chess960 = Fn.new { |sym, id|
    var pos = List.filled(8, NUL)
    var q = (id/4).floor
    var r = id % 4
    pos[r*2+1]= sym.b
    var t = q
    q = (q/4).floor
    r = t % 4
    pos[r*2] = sym.b
    t = q
    q = (q/6).floor
    r = t % 6
    var i = 0
    while (true) {
        if (pos[i] == NUL) {
            if (r == 0) {
                pos[i] = sym.q
                break
            }
            r = r - 1
        }
        i = i + 1
    }
    i = 0
    for (f in krn[q]) {
        while (pos[i] != NUL) i = i + 1
        pos[i] = (f == "k") ? sym.k :
                 (f == "r") ? sym.r :
                 (f == "n") ? sym.n : pos[i]
    }
    return pos.join(" ")
}

System.print(" ID  Start position")
for (id in [0, 518, 959]) Fmt.print("$3d  $s", id, chess960.call(A, id))
System.print("\nRandom")
var rand = Random.new()
for (i in 0..4) System.print(chess960.call(W, rand.int(960)))


char Col;

func ColNum(Start, Piece); \Return column number of Piece
int  Start, Piece, I;
[for I:= Start to 7 do
        if Col(I) = Piece then return I;
return -1;
];

proc Shuffle;           \Randomly rearrange pieces in columns
int  I, J, T;
[for I:= 8-1 downto 1 do
    [J:= Ran(I);        \range [0..I-1] (Sattolo cycle)
    T:= Col(I);  Col(I):= Col(J);  Col(J):= T;
    ];
];

int N, B1, B2, BOK, R1, R2, K, KOK;
[for N:= 1 to 5 do
        [Col:= "RNBQKBNR ";
        repeat  Shuffle;
                B1:= ColNum(0, ^B);
                B2:= ColNum(B1+1, ^B);
                BOK:= ((B1 xor B2) and 1) # 0;
                R1:= ColNum(0, ^R);
                R2:= ColNum(R1+1, ^R);
                K:= ColNum(0, ^K);
                KOK:= R1<K and K<R2;
        until   BOK and KOK;
        Text(0, Col);  CrLf(0);
        ];
]


const pieces="KQRrBbNN";
starts:=pieces:Utils.Helpers.permuteW(_).filter(fcn(p){
   I:=p.index;
   I("B") % 2 != I("b") % 2 and // Bishop constraint.
   // King constraint.
   ((I("r") < I("K") and I("K") < I("R")) or
    (I("R") < I("K") and I("K") < I("r")))
}).pump(List,"concat","toUpper"):Utils.Helpers.listUnique(_);


T Generator
   F.virtual.abstract next() -> Float

T PowersGenerator(Generator)
   i = 0.0
   Float e

   F (e)
      .e = e

   F.virtual.assign next() -> Float
      V r = .i ^ .e
      .i++
      R r

T Filter
   Generator gen, filter
   Float lastG, lastF

   F (Generator gen, filter)
      .gen = gen
      .filter = filter
      .lastG = .gen.next()
      .lastF = .filter.next()

   F ()()
      L .lastG >= .lastF
         I .lastG == .lastF
            .lastG = .gen.next()
         .lastF = .filter.next()

      V out = .lastG
      .lastG = .gen.next()
      R out

V gen = Filter(PowersGenerator(2), PowersGenerator(3))

L 20
   gen()
L 10
   print(gen(), end' ‘ ’)


package Generator is

   type Generator is tagged private;
   procedure Reset (Gen : in out Generator);
   function Get_Next (Gen : access Generator) return Natural;

   type Generator_Function is access function (X : Natural) return Natural;
   procedure Set_Generator_Function (Gen  : in out Generator;
                                     Func : Generator_Function);

   procedure Skip (Gen : access Generator'Class; Count : Positive := 1);

private

   function Identity (X : Natural) return Natural;

   type Generator is tagged record
      Last_Source : Natural := 0;
      Last_Value  : Natural := 0;
      Gen_Func    : Generator_Function := Identity'Access;
   end record;

end Generator;


MODE YIELDVALUE = PROC(VALUE)VOID;
MODE GENVALUE = PROC(YIELDVALUE)VOID;

PROC gen filtered = (GENVALUE gen candidate, gen exclude, YIELDVALUE yield)VOID: (
    VALUE candidate; SEMA have next exclude = LEVEL 0;
    VALUE exclude;   SEMA get next exclude  = LEVEL 0;
    BOOL initialise exclude := TRUE;

    PAR ( # run each generator in a different thread #
# Thread 1 #
      # FOR VALUE next exclude IN # gen exclude( # ) DO #
      ##   (VALUE next exclude)VOID: (
            DOWN get next exclude; exclude := next exclude;
            IF candidate <= exclude THEN
                UP have next exclude
            ELSE
                UP get next exclude
            FI
      # OD #)),
# Thread 2 #
      # FOR VALUE next candidate IN # gen candidate( # ) DO #
      ##   (VALUE next candidate)VOID: (
            candidate := next candidate;
            IF initialise exclude ORF candidate > exclude THEN
                UP get next exclude;
                DOWN have next exclude; # wait for result #
                initialise exclude := FALSE
            FI;
            IF candidate < exclude THEN
                yield(candidate)
            FI
      # OD #))
    )
);

PROC gen slice = (GENVALUE t, VALUE start, stop, YIELDVALUE yield)VOID: (
  INT index := 0;
  # FOR VALUE i IN # t( # ) DO #
  ##   (VALUE i)VOID: (
      IF   index >= stop THEN done
      ELIF index >= start THEN yield(i) FI;
      index +:= 1
  # OD # ));
    done: SKIP
);

PROC get list = (GENVALUE gen)[]VALUE: (
    INT upb := 0;
    INT ups := 2;
    FLEX [ups]VALUE out;
  # FOR VALUE i IN # gen( # ) DO #
  ##   (VALUE i)VOID:(
        upb +:= 1;
        IF upb > ups THEN # dynamically grow the array 50% #
          [ups +:= ups OVER 2]VALUE append; append[:upb-1] := out; out := append
        FI;
        out[upb] := i
  # OD # ))
    out[:upb]
);

PROC powers = (VALUE m, YIELDVALUE yield)VOID:
    FOR n FROM 0 DO yield(n ** m) OD;


----------------- EXPONENTIAL / GENERATOR ----------------

-- powers :: Gen [Int]
on powers(n)
    script f
        on |λ|(x)
            x ^ n as integer
        end |λ|
    end script
    fmapGen(f, enumFrom(0))
end powers

--------------------------- TEST -------------------------
on run
    take(10, ¬
        drop(20, ¬
            differenceGen(powers(2), powers(3))))

    --> {529, 576, 625, 676, 784, 841, 900, 961, 1024, 1089}
end run

------------------------- GENERIC ------------------------

-- Just :: a -> Maybe a
on Just(x)
    {type:"Maybe", Nothing:false, Just:x}
end Just

-- Nothing :: Maybe a
on Nothing()
    {type:"Maybe", Nothing:true}
end Nothing

-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
    {type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple

-- differenceGen :: Gen [a] -> Gen [a] -> Gen [a]
on differenceGen(ga, gb)
    -- All values of ga except any
    -- already seen in gb.
    script
        property g : zipGen(ga, gb)
        property bs : {}
        property xy : missing value
        on |λ|()
            set xy to g's |λ|()
            if missing value is xy then
                xy
            else
                set x to |1| of xy
                set y to |2| of xy
                set bs to {y} & bs
                if bs contains x then
                    |λ|() -- Next in series.
                else
                    x
                end if
            end if
        end |λ|
    end script
end differenceGen

-- drop :: Int -> [a] -> [a]
-- drop :: Int -> String -> String
on drop(n, xs)
    set c to class of xs
    if script is not c then
        if string is not c then
            if n < length of xs then
                items (1 + n) thru -1 of xs
            else
                {}
            end if
        else
            if n < length of xs then
                text (1 + n) thru -1 of xs
            else
                ""
            end if
        end if
    else
        take(n, xs) -- consumed
        return xs
    end if
end drop

-- enumFrom :: Int -> [Int]
on enumFrom(x)
    script
        property v : missing value
        on |λ|()
            if missing value is not v then
                set v to 1 + v
            else
                set v to x
            end if
            return v
        end |λ|
    end script
end enumFrom

-- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
on fmapGen(f, gen)
    script
        property g : mReturn(f)
        on |λ|()
            set v to gen's |λ|()
            if v is missing value then
                v
            else
                g's |λ|(v)
            end if
        end |λ|
    end script
end fmapGen

-- length :: [a] -> Int
on |length|(xs)
    set c to class of xs
    if list is c or string is c then
        length of xs
    else
        (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
    end if
end |length|

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
    set c to class of xs
    if list is c then
        if 0 < n then
            items 1 thru min(n, length of xs) of xs
        else
            {}
        end if
    else if string is c then
        if 0 < n then
            text 1 thru min(n, length of xs) of xs
        else
            ""
        end if
    else if script is c then
        set ys to {}
        repeat with i from 1 to n
            set v to xs's |λ|()
            if missing value is v then
                return ys
            else
                set end of ys to v
            end if
        end repeat
        return ys
    else
        missing value
    end if
end take

-- uncons :: [a] -> Maybe (a, [a])
on uncons(xs)
    set lng to |length|(xs)
    if 0 = lng then
        Nothing()
    else
        if (2 ^ 29 - 1) as integer > lng then
            if class of xs is string then
                set cs to text items of xs
                Just(Tuple(item 1 of cs, rest of cs))
            else
                Just(Tuple(item 1 of xs, rest of xs))
            end if
        else
            set nxt to take(1, xs)
            if {} is nxt then
                Nothing()
            else
                Just(Tuple(item 1 of nxt, xs))
            end if
        end if
    end if
end uncons

-- zipGen :: Gen [a] -> Gen [b] -> Gen [(a, b)]
on zipGen(ga, gb)
    script
        property ma : missing value
        property mb : missing value
        on |λ|()
            if missing value is ma then
                set ma to uncons(ga)
                set mb to uncons(gb)
            end if
            if Nothing of ma or Nothing of mb then
                missing value
            else
                set ta to Just of ma
                set tb to Just of mb
                set x to Tuple(|1| of ta, |1| of tb)
                set ma to uncons(|2| of ta)
                set mb to uncons(|2| of tb)
                return x
            end if
        end |λ|
    end script
end zipGen


#include <inttypes.h>	/* int64_t, PRId64 */
#include <stdlib.h>	/* exit() */
#include <stdio.h>	/* printf() */

#include <libco.h>	/* co_{active,create,delete,switch}() */

/* A generator that yields values of type int64_t. */
struct gen64 {
	cothread_t giver;	/* this cothread calls yield64() */
	cothread_t taker;	/* this cothread calls next64() */
	int64_t given;
	void (*free)(struct gen64 *);
	void *garbage;
};

/* Yields a value. */
inline void
yield64(struct gen64 *gen, int64_t value)
{
	gen->given = value;
	co_switch(gen->taker);
}

/* Returns the next value that the generator yields. */
inline int64_t
next64(struct gen64 *gen)
{
	gen->taker = co_active();
	co_switch(gen->giver);
	return gen->given;
}

static void
gen64_free(struct gen64 *gen)
{
	co_delete(gen->giver);
}

struct gen64 *entry64;

/*
 * Creates a cothread for the generator. The first call to next64(gen)
 * will enter the cothread; the entry function must copy the pointer
 * from the global variable struct gen64 *entry64.
 *
 * Use gen->free(gen) to free the cothread.
 */
inline void
gen64_init(struct gen64 *gen, void (*entry)(void))
{
	if ((gen->giver = co_create(4096, entry)) == NULL) {
		/* Perhaps malloc() failed */
		fputs("co_create: Cannot create cothread\n", stderr);
		exit(1);
	}
	gen->free = gen64_free;
	entry64 = gen;
}

/*
 * Generates the powers 0**m, 1**m, 2**m, ....
 */
void
powers(struct gen64 *gen, int64_t m)
{
	int64_t base, exponent, n, result;

	for (n = 0;; n++) {
		/*
		 * This computes result = base**exponent, where
		 * exponent is a nonnegative integer. The result
		 * is the product of repeated squares of base.
		 */
		base = n;
		exponent = m;
		for (result = 1; exponent != 0; exponent >>= 1) {
			if (exponent & 1) result *= base;
			base *= base;
		}
		yield64(gen, result);
	}
	/* NOTREACHED */
}

/* stuff for squares_without_cubes() */
#define ENTRY(name, code) static void name(void) { code; }
ENTRY(enter_squares, powers(entry64, 2))
ENTRY(enter_cubes, powers(entry64, 3))

struct swc {
	struct gen64 cubes;
	struct gen64 squares;
	void (*old_free)(struct gen64 *);
};

static void
swc_free(struct gen64 *gen)
{
	struct swc *f = gen->garbage;
	f->cubes.free(&f->cubes);
	f->squares.free(&f->squares);
	f->old_free(gen);
}

/*
 * Generates the squares 0**2, 1**2, 2**2, ..., but removes the squares
 * that equal the cubes 0**3, 1**3, 2**3, ....
 */
void
squares_without_cubes(struct gen64 *gen)
{
	struct swc f;
	int64_t c, s;

	gen64_init(&f.cubes, enter_cubes);
	c = next64(&f.cubes);

	gen64_init(&f.squares, enter_squares);
	s = next64(&f.squares);

	/* Allow other cothread to free this generator. */
	f.old_free = gen->free;
	gen->garbage = &f;
	gen->free = swc_free;

	for (;;) {
		while (c < s)
			c = next64(&f.cubes);
		if (c != s)
			yield64(gen, s);
		s = next64(&f.squares);
	}
	/* NOTREACHED */
}

ENTRY(enter_squares_without_cubes, squares_without_cubes(entry64))

/*
 * Look at the sequence of numbers that are squares but not cubes.
 * Drop the first 20 numbers, then print the next 10 numbers.
 */
int
main()
{
	struct gen64 gen;
	int i;

	gen64_init(&gen, enter_squares_without_cubes);

	for (i = 0; i < 20; i++)
		next64(&gen);
	for (i = 0; i < 9; i++)
		printf("%" PRId64 ", ", next64(&gen));
	printf("%" PRId64 "\n", next64(&gen));

	gen.free(&gen); /* Free memory. */
	return 0;
}


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

static class Program {
    static void Main() {
        Func<int, IEnumerable<int>> ms = m => Infinite().Select(i => (int)Math.Pow(i, m));
        var squares = ms(2);
        var cubes = ms(3);
        var filtered = squares.Where(square => cubes.First(cube => cube >= square) != square);
        var final = filtered.Skip(20).Take(10);
        foreach (var i in final) Console.WriteLine(i);
    }

    static IEnumerable<int> Infinite() {
        var i = 0;
        while (true) yield return i++;
    }
}


#include <iostream>
using namespace std;

template<class T>
class Generator
{
public:
  virtual T operator()() = 0;
};

// Does nothing unspecialized
template<class T, T P>
class PowersGenerator: Generator<T> {};

// Specialize with other types, or provide a generic version of pow
template<int P>
class PowersGenerator<int, P>: Generator<int>
{
public:
  int i;
  PowersGenerator() { i = 1; }
  virtual int operator()()
  {
    int o = 1;
    for(int j = 0; j < P; ++j) o *= i;
    ++i;
    return o;
  }
};

// Only works with non-decreasing generators
template<class T, class G, class F>
class Filter: Generator<T>
{
public:
  G gen;
  F filter;
  T lastG, lastF;

  Filter() { lastG = gen(); lastF = filter(); }

  virtual T operator()()
  {
    while(lastG >= lastF)
    {
      if(lastG == lastF)
        lastG = gen();
      lastF = filter();
    }

    T out = lastG;
    lastG = gen();
    return out;
  }
};

int main()
{
  Filter<int, PowersGenerator<int, 2>, PowersGenerator<int, 3>> gen;

  for(int i = 0; i < 20; ++i)
    gen();

  for(int i = 20; i < 30; ++i)
    cout << i << ": " << gen() << endl;
}


(defn powers [m] (for [n (iterate inc 1)] (reduce * (repeat m n)))))
(def squares (powers 2))
(take 5 squares) ; => (1 4 9 16 25)


(defun take (seq &optional (n 1))
  (values-list (loop repeat n collect (funcall seq))))

(defun power-seq (n)
  (let ((x 0))
    (lambda () (expt (incf x) n))))

(defun filter-seq (s1 s2) ;; remove s2 from s1
  (let ((x1 (take s1)) (x2 (take s2)))
    (lambda ()
      (tagbody g
	(if (= x1 x2)
	     (progn (setf x1 (take s1) x2 (take s2)) (go g)))
	(if (> x1 x2)
	     (progn (setf x2 (take s2)) (go g))))

      (prog1 x1 (setf x1 (take s1))))))

(let ((2not3 (filter-seq (power-seq 2) (power-seq 3))))
  (take 2not3 20) ;; drop 20
  (princ (multiple-value-list (take 2not3 10))))


void main() {
    import std.stdio, std.bigint, std.range, std.algorithm;

    auto squares = 0.sequence!"n".map!(i => i.BigInt ^^ 2);
    auto cubes = 0.sequence!"n".map!(i => i.BigInt ^^ 3);

    squares.setDifference(cubes).drop(20).take(10).writeln;
}


def genPowers(exponent) {
    var i := -1
    return def powerGenerator() {
        return (i += 1) ** exponent
    }
}

def filtered(source, filter) {
    var fval := filter()
    return def filterGenerator() {
        while (true) {
            def sval := source()
            while (sval > fval) {
                fval := filter()
            }
            if (sval < fval) {
                return sval
            }
        }
    }
}

def drop(n, gen) {
    for _ in 1..n { gen() }
}

def squares := genPowers(2)
def cubes := genPowers(3)
def squaresNotCubes := filtered(squares, cubes)
drop(20, squaresNotCubes)
for _ in 1..10 {
    print(`${squaresNotCubes()} `)
}
println()


(lib 'tasks) ;; for make-generator

;; generator of generators
(define (gen-power power)
	(make-generator
		(lambda(n) (yield (expt n power)) (1+ n))  1))

(define powers-2 (gen-power 2))
(define powers-3 (gen-power 3))

(take powers-3 10)
    → (1 8 27 64 125 216 343 512 729 1000)

;; generators substraction
;; input : two generators ga, gb - Sequences must be increasing
;; output : new generator  = ga sequence minus gb sequence

(define (gen-substract ga gb)
	(define (substract b (a))
	(set! a (next ga))
	(while (>= a b) ; avance b until > a
		(when (= a b) (set! a (next ga)))
		(set! b (next gb)))
	(yield a)
	b ) ;; b := next state
	(make-generator substract (next gb)))

;; application
(define task    (gen-substract (gen-power 2) (gen-power 3)))

(drop task 20)
(take task 10)
    → (529 576 625 676 784 841 900 961 1024 1089)

; inspect
task → #generator:state: 1331


defmodule Generator do
  def filter( source_pid, remove_pid ) do
    first_remove = next( remove_pid )
    spawn( fn -> filter_loop(source_pid, remove_pid, first_remove) end )
  end

  def next( pid ) do
    send(pid, {:next, self})
    receive do
      x -> x
    end
  end

  def power( m ), do: spawn( fn -> power_loop(m, 0) end )

  def task do
    squares_pid = power( 2 )
    cubes_pid = power( 3 )
    filter_pid = filter( squares_pid, cubes_pid )
    for _x <- 1..20, do: next(filter_pid)
    for _x <- 1..10, do: next(filter_pid)
  end

  defp filter_loop( pid1, pid2, n2 ) do
    receive do
      {:next, pid} ->
        {n, new_n2} = filter_loop_next( next(pid1), n2, pid1, pid2 )
        send( pid, n )
        filter_loop( pid1, pid2, new_n2 )
    end
  end

  defp filter_loop_next( n1, n2, pid1, pid2 ) when n1 > n2, do:
       filter_loop_next( n1, next(pid2), pid1, pid2 )
  defp filter_loop_next( n, n, pid1, pid2 ), do:
       filter_loop_next( next(pid1), next(pid2), pid1, pid2 )
  defp filter_loop_next( n1, n2, _pid1, _pid2 ), do: {n1, n2}

  defp power_loop( m, n ) do
    receive do
      {:next, pid} -> send( pid, round(:math.pow(n, m) ) )
    end
    power_loop( m, n + 1 )
  end
end

IO.inspect Generator.task


;; lexical-binding: t
(require 'generator)

(iter-defun exp-gen (pow)
  (let ((i -1))
    (while
      (setq i (1+ i))
      (iter-yield (expt i pow)))))

(iter-defun flt-gen ()
  (let* ((g (exp-gen 2))
	 (f (exp-gen 3))
	 (i (iter-next g))
	 (j (iter-next f)))
    (while
      (setq i (iter-next g))
      (while (> i j)
	(setq j (iter-next f)))
      (unless (= i j)
	(iter-yield i)))))

(let ((g (flt-gen))
      (o 'nil))
  (dotimes (i 29)
    (setq o (iter-next g))
    (when (>= i 20)
      (print o))))


-module( generator ).

-export( [filter/2, next/1, power/1, task/0] ).

filter(	Source_pid, Remove_pid ) ->
	First_remove = next( Remove_pid	),
        erlang:spawn( fun() -> filter_loop(Source_pid, Remove_pid, First_remove) end ).

next( Pid ) ->
    Pid ! {next, erlang:self()},
    receive X -> X end.

power( M ) -> erlang:spawn( fun() -> power_loop(M, 0) end ).

task() ->
    Squares_pid = power( 2 ),
    Cubes_pid = power( 3 ),
    Filter_pid = filter( Squares_pid, Cubes_pid ),
    [next(Filter_pid) || _X <- lists:seq(1, 20)],
    [next(Filter_pid) || _X <- lists:seq(1, 10)].

filter_loop( Pid1, Pid2, N2 ) ->
        receive
        {next, Pid} ->
	       {N, New_N2} = filter_loop_next( next(Pid1), N2, Pid1, Pid2 ),
               Pid ! N
        end,
        filter_loop( Pid1, Pid2, New_N2 ).

filter_loop_next( N1, N2, Pid1, Pid2 ) when N1 > N2 -> filter_loop_next( N1, next(Pid2), Pid1, Pid2 );
filter_loop_next( N, N, Pid1, Pid2 ) -> filter_loop_next( next(Pid1), next(Pid2), Pid1, Pid2 );
filter_loop_next( N1, N2, _Pid1, _Pid2 ) -> {N1, N2}.

power_loop( M, N ) ->
        receive	{next, Pid} -> Pid ! erlang:round(math:pow(N, M) ) end,
	power_loop( M, N + 1 ).


*        Generate lower case alphabet - 15/10/2015
LOWER    CSECT
         USING  LOWER,R15          set base register
         LA     R7,PG              [email protected]
         SR     R6,R6              clear
         IC     R6,=C'a'           char='a'
         BCTR   R6,0               char=char-1
LOOP     LA     R6,1(R6)           char=char+1
         STC    R6,CHAR
         CLI    CHAR,C'i'          if char>'i'
         BNH    OK
         CLI    CHAR,C'j'          and char<'j'
         BL     SKIP               then skip
         CLI    CHAR,C'r'          if char>'r'
         BNH    OK
         CLI    CHAR,C's'          and char<'s'
         BL     SKIP               then skip
OK       MVC    0(1,R7),CHAR       output char
         LA     R7,1(R7)           pgi=pgi+1
SKIP     CLI    CHAR,C'z'          if char='z'
         BNE    LOOP               loop
         XPRNT  PG,26              print buffer
         XR     R15,R15            set return code
         BR     R14                return to caller
CHAR     DS     C                  character
PG       DS     CL26               buffer
         YREGS
         END    LOWER


ASCLOW: PHA             ; push contents of registers that we
        TXA             ; shall be using onto the stack
        PHA
        LDA   #$61      ; ASCII "a"
        LDX   #$00
ALLOOP: STA   $2000,X
        INX
        CLC
        ADC   #$01
        CMP   #$7B      ; have we got beyond ASCII "z"?
        BNE   ALLOOP
        LDA   #$00      ; terminate the string with ASCII NUL
        STA   $2000,X
        PLA             ; retrieve register contents from
        TAX             ; the stack
        PLA
        RTS             ; return


Ascii_Low:
MOVEM.L D0/A0,-(SP)	;store D0 and A0 on stack

LEA $00100000,A0	;could also have used MOVE.L since the address is static
MOVE.B #$61,D0		;ascii "a"

loop_AsciiLow:
MOVE.B D0,(A0)+		;store letter in address and increment pointer by 1
ADDQ.B #1,D0		;add 1 to D0 to get the next letter
CMP.B #$7B,D0		;Are we done yet? (7B is the first character after lowercase "z")
BNE loop_AsciiLow	;if not, loop again
MOVE.B #0,(A0)		;store the null terminator

MOVEM.L (SP)+,D0/A0	;pop D0 and A0

rts


let m n = Seq.unfold(fun i -> Some(bigint.Pow(i, n), i + 1I)) 0I

let squares = m 2
let cubes = m 3

let (--) orig veto = Seq.where(fun n -> n <> (Seq.find(fun m -> m >= n) veto)) orig

let ``squares without cubes`` = squares -- cubes

Seq.take 10 (Seq.skip 20 (``squares without cubes``))
|> Seq.toList |> printfn "%A"


USING: fry kernel lists lists.lazy math math.functions
prettyprint ;
IN: rosetta-code.generator-exponential

: mth-powers-generator ( m -- lazy-list )
    [ 0 lfrom ] dip [ ^ ] curry lmap-lazy ;

: lmember? ( elt list -- ? )
    over '[ unswons dup _ >= ] [ drop ] until nip = ;

: 2-not-3-generator ( -- lazy-list )
    2 mth-powers-generator
    [ 3 mth-powers-generator lmember? not ] <lazy-filter> ;

10 2-not-3-generator 20 [ cdr ] times ltake list>array .


class Main
{
  // Create and return a function which generates mth powers when called
  |->Int| make_generator (Int m)
  {
    current := 0
    return |->Int|
    {
      current += 1
      return (current-1).pow (m)
    }
  }

  |->Int| squares_without_cubes ()
  {
    squares := make_generator (2)
    cubes := make_generator (3)
    c := cubes.call
    return |->Int|
    {
      while (true)
      {
        s := squares.call
        while (c < s) { c = cubes.call }
        if (c != s) return s
      }
      return 0
    }
  }

  Void main ()
  {
    swc := squares_without_cubes ()
    20.times { swc.call } // drop 20 values
    10.times // display the next 10
    {
      echo (swc.call)
    }
  }
}


	org	100h
	jmp	test

	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	;; Store the lowercase alphabet as a CP/M string
	;; ($-terminated), starting at HL.
	;; Destroys: b, c

alph:	lxi	b,611ah	; set B='a' and C=26 (counter)
aloop:	mov	m,b	; store letter in memory
	inr	b	; next letter
	inx	h	; next memory position
	dcr	c	; one fewer letter left
	jnz	aloop	; go do the next letter if there is one
	mvi	m,'$'	; terminate the string
	ret

	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	;; Test code
test:	lxi	h,buf	; select buffer
	call	alph	; generate alphabet

	lxi	d,buf	; print string in buffer
	mvi	c,9
	call	5
	rst	0

buf:	ds	27	; buffer to keep the alphabet in


	bits	16
	cpu	8086
	org	100h
section	.text
	jmp	demo
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	;;;	Store the lowercase alphabet starting at [ES:DI]
	;;;	Destroys AX, CX, DI
alph:	mov	cx,13		; 2*13 words = 26 bytes
	mov	ax,'ab'		; Do two bytes at once
.loop:	stosw			; Store AX at ES:DI and add 2 to DI
	add	ax,202h		; Add 2 to both bytes (CD, EF, ...)
	loop	.loop
	mov	al,'$'		; MS-DOS string terminator
	stosb
	ret
	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
demo:	mov	di,buf		; Pointer to buffer
	call	alph		; Generate the alphabet
	mov	dx,buf		; Print the contents of the buffer
	mov	ah,9
	int	21h
	ret
section	.bss
buf:	resb	27		; Buffer to store the alphabet in


\ genexp-rcode.fs   Generator/Exponential for RosettaCode.org

\ Generator/filter implementation using return stack as continuations stack
: ENTER         ( cont.addr --  ;borrowed from M.L.Gasanenko papers)
        >R
;
: |             ( f --  ;true->go ahead, false->return into generator )
        IF EXIT THEN R> DROP
;
: GEN           ( --  ;generate forever what is between 'GEN' and ';' )
        BEGIN [email protected] ENTER AGAIN
;
: STOP          ( f --  ;return to caller of word that contain 'GEN' )
        IF R> DROP R> DROP R> DROP THEN
;

\ Problem at hand
: square        ( n -- n^2 )    dup * ;
: cube          ( n -- n^3 )    dup square * ;

\ Faster tests using info that tested numbers are monotonic growing
        VARIABLE Sqroot         \ last square root
        VARIABLE Cbroot         \ last cubic  root
: square?       ( u -- f  ;test U for square number)
        BEGIN
                Sqroot @ square over <
        WHILE
                1 Sqroot +!
        REPEAT
        Sqroot @ square =
;
: cube?         ( u -- f  ;test U for cubic  number)
        BEGIN
                Cbroot @ cube over <
        WHILE
                1 Cbroot +!
        REPEAT
        Cbroot @ cube =
;
        VARIABLE Counter
: (go)  ( u -- u' )
        GEN 1+ Counter @ 30 >= STOP
        dup square? | dup cube? 0= | Counter @ 20 >= 1 Counter +! | dup .
;
:noname 0 Counter ! 1 Sqroot ! 1 Cbroot ! 0 (go) drop ;
execute cr bye


Dim Shared As Long lastsquare, nextsquare, lastcube, midcube, nextcube

Function squares() As Long
    lastsquare += nextsquare
    nextsquare += 2
    squares = lastsquare
End Function

Function cubes() As Long
    lastcube += nextcube
    nextcube += midcube
    midcube += 6
    cubes = lastcube
End Function

lastsquare = 1 : nextsquare = -1 : lastcube = -1 : midcube = 0 : nextcube = 1
Dim As Long cube, square
cube = cubes

For i As Byte = 1 To 30
    Do
        square = squares
        Do While cube < square
            cube = cubes
        Loop
        If square <> cube Then Exit Do
    Loop
    If i > 20 Then Print square;
Next i
Sleep


def powers( m ) = map( (^ m), 0.. )

def
  filtered( [email protected]:_, ch:ct ) | sh > ch = filtered( s, ct )
  filtered( sh:st, [email protected]:_ ) | sh < ch = sh # filtered( st, c )
  filtered( _:st, c ) = filtered( st, c )

println( filtered(powers(2), powers(3)).drop(20).take(10) )


REPORT lower_case_ascii.

WRITE: / to_lower( sy-abcde ).


byte X

Proc Main()

 For X=97 To 122
  Do
   Put(x)
  Od

Return


type Lower_Case is new Character range 'a' .. 'z';


    # in ALGOL 68, a STRING is an array of characters with flexible bounds #
    # so we can declare an array of 26 characters and assign a string      #
    # containing the lower-case letters to it                              #

    [ 26 ]CHAR lc := "abcdefghijklmnopqrstuvwxyz"


package main

import (
    "fmt"
    "math"
)

// note: exponent not limited to ints
func newPowGen(e float64) func() float64 {
    var i float64
    return func() (r float64) {
        r = math.Pow(i, e)
        i++
        return
    }
}

// given two functions af, bf, both monotonically increasing, return a
// new function that returns values of af not returned by bf.
func newMonoIncA_NotMonoIncB_Gen(af, bf func() float64) func() float64 {
    a, b := af(), bf()
    return func() (r float64) {
        for {
            if a < b {
                r = a
                a = af()
                break
            }
            if b == a {
                a = af()
            }
            b = bf()
        }
        return
    }
}

func main() {
    fGen := newMonoIncA_NotMonoIncB_Gen(newPowGen(2), newPowGen(3))
    for i := 0; i < 20; i++ {
        fGen()
    }
    for i := 0; i < 10; i++ {
        fmt.Print(fGen(), " ")
    }
    fmt.Println()
}


import Data.List.Ordered

powers :: Int -> [Int]
powers m = map (^ m) [0..]

squares :: [Int]
squares = powers 2

cubes :: [Int]
cubes = powers 3

foo :: [Int]
foo = filter (not . has cubes) squares

main :: IO ()
main = print $ take 10 $ drop 20 foo


    % set lc to the lower case alphabet          %
    string(26) lc;
    for c := 0 until 25 do lc( c // 1 ) := code( decode( "a" ) + c );


-------------------- ALPHABETIC SERIES -------------------
on run
    unlines(map(concat, ¬
        ({enumFromTo("a", "z"), ¬
            enumFromTo("🐟", "🐐"), ¬
            enumFromTo("z", "a"), ¬
            enumFromTo("α", "ω")})))
end run

-------------------- GENERIC FUNCTIONS -------------------

-- concat :: [[a]] -> [a]
-- concat :: [String] -> String
on concat(xs)
    set lng to length of xs
    if 0 < lng and string is class of (item 1 of xs) then
        set acc to ""
    else
        set acc to {}
    end if
    repeat with i from 1 to lng
        set acc to acc & item i of xs
    end repeat
    acc
end concat

-- enumFromTo :: Enum a => a -> a -> [a]
on enumFromTo(m, n)
    if class of m is integer then
        enumFromToInt(m, n)
    else
        enumFromToChar(m, n)
    end if
end enumFromTo

-- enumFromToChar :: Char -> Char -> [Char]
on enumFromToChar(m, n)
    set {intM, intN} to {id of m, id of n}
    set xs to {}
    repeat with i from intM to intN by signum(intN - intM)
        set end of xs to character id i
    end repeat
    return xs
end enumFromToChar

-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    -- 2nd class handler function lifted into 1st class script wrapper.
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    -- The list obtained by applying f
    -- to each element of xs.
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- signum :: Num -> Num
on signum(x)
    if x < 0 then
        -1
    else if x = 0 then
        0
    else
        1
    end if
end signum

-- unlines :: [String] -> String
on unlines(xs)
    -- A single string formed by the intercalation
    -- of a list of strings with the newline character.
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set s to xs as text
    set my text item delimiters to dlm
    s
end unlines


procedure main()

write("Non-cube Squares (21st to 30th):")
every (k := 0, s := noncubesquares()) do
   if(k +:= 1) > 30 then break
   else write(20 < k," : ",s)
end

procedure mthpower(m)   #: generate i^m for i = 0,1,...
while (/i := 0) | (i +:= 1) do suspend i^m
end

procedure noncubesquares()  #: filter for squares that aren't cubes
cu := create mthpower(3)    # co-expressions so that we can
sq := create mthpower(2)    # ... get our results where we need

repeat {
   if c === s then  ( c := @cu , s := @sq )
   else if s > c then c := @cu
   else {
      suspend s
      s := @sq
      }
   }
end


coclass 'mthPower'
  N=: 0
  create=: 3 :0
    M=: y
  )
  next=: 3 :0
    n=. N
    N=: N+1
    n^M
  )


import java.util.function.LongSupplier;
import static java.util.stream.LongStream.generate;

public class GeneratorExponential implements LongSupplier {
    private LongSupplier source, filter;
    private long s, f;

    public GeneratorExponential(LongSupplier source, LongSupplier filter) {
        this.source = source;
        this.filter = filter;
        f = filter.getAsLong();
    }

    @Override
    public long getAsLong() {
        s = source.getAsLong();

        while (s == f) {
            s = source.getAsLong();
            f = filter.getAsLong();
        }

        while (s > f) {
            f = filter.getAsLong();
        }

        return s;
    }

    public static void main(String[] args) {
        generate(new GeneratorExponential(new SquaresGen(), new CubesGen()))
                .skip(20).limit(10)
                .forEach(n -> System.out.printf("%d ", n));
    }
}

class SquaresGen implements LongSupplier {
    private long n;

    @Override
    public long getAsLong() {
        return n * n++;
    }
}

class CubesGen implements LongSupplier {
    private long n;

    @Override
    public long getAsLong() {
        return n * n * n++;
    }
}


ProgramStart:
	mov sp,#0x03000000			;Init Stack Pointer

	mov r4,#0x04000000  		        ;DISPCNT -LCD Control
	mov r2,#0x403    			;4= Layer 2 on / 3= ScreenMode 3
	str r2,[r4]         	                ;hardware specific routine, activates Game Boy's bitmap mode

	mov r0,#0x61				;ASCII "a"
	mov r2,#ramarea
	mov r1,#26

rep_inc_stosb:                                  ;repeatedly store a byte into memory, incrementing the destination and the value stored
                                                ;    each time.
	strB r0,[r2]
	add r0,r0,#1
	add r2,r2,#1
	subs r1,r1,#1
	bne rep_inc_stosb
	mov r0,#255
	strB r0,[r2]				;store a 255 terminator into r1

	mov r1,#ramarea
	bl PrintString                          ;Prints a 255-terminated string using a pre-defined bitmap font. Code omitted for brevity

forever:
        b forever                               ;halt the cpu


function PowersGenerator(m) {
	var n=0;
	while(1) {
		yield Math.pow(n, m);
		n += 1;
	}
}

function FilteredGenerator(g, f){
	var value = g.next();
	var filter = f.next();

	while(1) {
		if( value < filter ) {
			yield value;
			value = g.next();
		} else if ( value > filter ) {
			filter = f.next();
		} else {
			value = g.next();
			filter = f.next();
		}
	}
}

var squares = PowersGenerator(2);
var cubes = PowersGenerator(3);

var filtered = FilteredGenerator(squares, cubes);

for( var x = 0; x < 20; x++ ) filtered.next()
for( var x = 20; x < 30; x++ ) console.logfiltered.next());


# Compute self^m where m is a non-negative integer:
def pow(m): . as $in | reduce range(0;m) as $i (1; .*$in);

# state: [i, i^m]
def next_power(m): .[0] + 1 | [., pow(m) ];


drop(gen::Function, n::Integer) = (for _ in 1:n gen() end; gen)
take(gen::Function, n::Integer) = collect(gen() for _ in 1:n)

function pgen(n::Number)
    x = 0
    return () -> (x += 1) ^ n
end

function genfilter(g1::Function, g2::Function)
    local r1
    local r2 = g2()
    return () -> begin
        r1 = g1()
        while r2 <  r1 r2 = g2() end
        while r1 == r2 r1 = g1() end
        return r1
    end
end

@show take(drop(genfilter(pgen(2), pgen(3)), 20), 10)


(* ****** ****** *)
//
// How to compile:
//
// patscc -DATS_MEMALLOC_LIBC -o lowercase lowercase.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)

implement
main0 () =
{
//
val N = 26
//
val A =
arrayref_tabulate_cloref<char>
(
  i2sz(N), lam(i) => int2char0(char2int0('a') + sz2i(i))
) (* end of [val] *)
//
} (* end of [main0] *)


a :={}
Loop, 26
	a.Insert(Chr(A_Index + 96))


Func _a2z()
	Local $a2z = ""
	For $i = 97 To 122
		$a2z &= Chr($i)
	Next
	Return $a2z
EndFunc


# syntax: GAWK -f GENERATE_LOWER_CASE_ASCII_ALPHABET.AWK
BEGIN {
    for (i=0; i<=255; i++) {
      c = sprintf("%c",i)
      if (c ~ /[[:lower:]]/) {
        lower_chars = lower_chars c
      }
    }
    printf("%s %d: %s\n",ARGV[0],length(lower_chars),lower_chars)
    exit(0)
}


// version 1.1.0
// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning

import kotlin.coroutines.experimental.buildSequence

fun generatePowers(m: Int) =
    buildSequence {
        var n = 0
        val mm = m.toDouble()
        while (true) yield(Math.pow((n++).toDouble(), mm).toLong())
    }

fun generateNonCubicSquares(squares: Sequence<Long>, cubes: Sequence<Long>) =
    buildSequence {
        val iter2 = squares.iterator()
        val iter3 = cubes.iterator()
        var square = iter2.next()
        var cube = iter3.next()
        while (true) {
            if (square > cube) {
                cube = iter3.next()
                continue
            } else if (square < cube) {
                yield(square)
            }
            square = iter2.next()
        }
    }

fun main(args: Array<String>) {
    val squares = generatePowers(2)
    val cubes = generatePowers(3)
    val ncs = generateNonCubicSquares(squares, cubes)
    print("Non-cubic squares (21st to 30th) : ")
    ncs.drop(20).take(10).forEach { print("$it ") } // print 21st to 30th items
    println()
}


squares = script("generator.power").new(2)
cubes   = script("generator.power").new(3)
filter  = script("generator.filter").new(squares, cubes)
filter.skip(20)
res = []
i = 0
repeat while filter.exec(res)
    i = i + 1
    if i>10 then exit repeat
    put res[1]
end repeat


--could be done with a coroutine, but a simple closure works just as well.
local function powgen(m)
  local count = 0
  return function()
    count = count + 1
    return count^m
  end
end

local squares = powgen(2)
local cubes = powgen(3)

local cowrap,coyield = coroutine.wrap, coroutine.yield

local function filter(f,g)
  return cowrap(function()
    local ff,gg = f(), g()
    while true do
      if ff == gg then
        ff,gg = f(), g()
      elseif ff < gg then
        coyield(ff)
        ff = f()
      else
        gg = g()
      end
    end
  end)
end

filter = filter(squares,cubes)

for i = 1,30 do
  local result = filter()
  if i > 20 then
    print(result)
  end
end


      DIM lower&(25)
      FOR i%=0TO25
        lower&(i%)=ASC"a"+i%
      NEXT
      END


@echo off
setlocal enabledelayedexpansion

:: This code appends the ASCII characters from 97-122 to %alphabet%, removing any room for error.

for /l %%i in (97,1,122) do (
  cmd /c exit %%i
  set "alphabet=!alphabet! !=exitcodeAscii!"
)
echo %alphabet%
pause>nul


Module Generator {
      PowGen = Lambda (e)-> {
            =lambda i=0, e -> {
                  i++
                  =i**e
            }
      }

      Squares=lambda PowGen=PowGen(2) ->{
            =PowGen()
      }

      Cubes=Lambda PowGen=PowGen(3) -> {
            =PowGen()
      }

      Filter=Lambda  z=Squares(), Squares, m, Cubes->{
            while m<Z {m=cubes()}
            if z=m then z=Squares()
            =z
            z=Squares()
      }

      For i=1 to 20 : dropit=Filter() :Next i

      Document doc$="Non-cubic squares (21st to 30th)"
      Print doc$
      \\ a new line to doc$
      doc$={
      }
      For i=1 to  10 {
            f=Filter()
            Print Format$("I: {0::-2}, F: {1}",i+20, f)
            doc$=Format$("I: {0::-2}, F: {1}",i+20, f)+{
            }
      }
      Clipboard doc$
}
Generator


lastsquare = 1;
nextsquare = -1;
lastcube = -1;
midcube = 0;
nextcube = 1;
Gensquares[] := Module[{},
  lastsquare += nextsquare;
  nextsquare += 2;
  squares = lastsquare;
  squares
  ]
Gencubes[] := Module[{},
  lastcube += nextcube;
  nextcube += midcube;
  midcube += 6;
  cubes = lastcube
  ]

c = Gencubes[];
Do[
 While[True,
  s = Gensquares[];
  While[c < s,
   c = Gencubes[];
   ];
  If[s =!= c,
   Break[]
   ];
  ];
 If[i > 20,
  Print[s]
  ]
 ,
 {i, 30}
 ]


type Iterator = iterator(): int

proc `^`*(base: Natural; exp: Natural): int =
  var (base, exp) = (base, exp)
  result = 1
  while exp != 0:
    if (exp and 1) != 0:
      result *= base
    exp = exp shr 1
    base *= base

proc next(s: Iterator): int =
  for n in s(): return n

proc powers(m: Natural): Iterator =
  iterator it(): int {.closure.} =
    for n in 0 ..< int.high:
      yield n ^ m
  result = it

iterator filtered(s1, s2: Iterator): int =
  var v = next(s1)
  var f = next(s2)
  while true:
    if v > f:
      f = next(s2)
      continue
    elif v < f:
      yield v
    v = next(s1)

var
  squares = powers(2)
  cubes = powers(3)
  i = 1
for x in filtered(squares, cubes):
  if i > 20: echo x
  if i >= 30: break
  inc i


  a:?seq:?c
&   whl
  ' ( chr$(asc$!c+1):~>z:?c
    & !seq !c:?seq
    )
& !seq


blsq ) @azr\sh
abcdefghijklmnopqrstuvwxyz