ppm := Run("cmd.exe /c convert lena50.jpg ppm:-")
                       ; pipe in from imagemagick
img := ppm_read("", ppm) ;
x := img[4,4] ; get pixel(4,4)
y := img[24,24] ; get pixel(24,24)
msgbox % x.rgb() " " y.rgb()
img.write("lena50copy.ppm")
return

ppm_read(filename, ppmo=0) ; only ppm6 files supported
{
if !ppmo  ; if image not already in memory, read from filename
  fileread, ppmo, % filename

  index := 1
  pos := 1

  loop, parse, ppmo, `n, `r
  {
    if (substr(A_LoopField, 1, 1) == "#")
      continue
loop,
{
 if !pos := regexmatch(ppmo, "\d+", pixel, pos)
break
    bitmap%A_Index% := pixel
    if (index == 4)
      Break
    pos := regexmatch(ppmo, "\s", x, pos)
    index ++
}
  }

  type := bitmap1
  width := bitmap2
  height := bitmap3
  maxcolor := bitmap4
  bitmap := Bitmap(width, height, color(0,0,0))
  index := 1
  i := 1
  j := 1
 bits := pos
loop % width * height
  {
      bitmap[i, j, "r"]  := numget(ppmo, 3 * A_Index + bits, "uchar")
      bitmap[i, j, "g"]  := numget(ppmo, 3 * A_Index + bits + 1, "uchar")
      bitmap[i, j, "b"]  := numget(ppmo, 3 * A_Index + bits + 2, "uchar")

      if (j == width)
{
	j := 1
	i += 1
}
      else
	j++
}
 return bitmap
  }
#include bitmap_storage.ahk ; from http://rosettacode.org/wiki/Basic_bitmap_storage/AutoHotkey
#include run.ahk ; http://www.autohotkey.com/forum/viewtopic.php?t=16823


sym(',', commalist) --> ['\\',','], !.
sym(H, Context)         --> [H], { not(H = '{'; H = '}'), (Context = commalist -> not(H = ','); true) }.
syms([H|T], Context)    --> sym(H, Context), !, syms(T, Context).
syms([], _)             --> [].
symbol(Symbol, Context) --> syms(Syms,Context), {atom_chars(Symbol, Syms)}.

braces(Member) --> ['{'], commalist(List), ['}'], {length(List, Len), Len > 1, member(Member, List)}.

commalist([H|T]) --> sym_braces(H, commalist), [','], commalist(T).
commalist([H]) --> sym_braces(H, commalist).

sym_braces(String, Context) --> symbol(S1, Context), braces(S2), sym_braces(S3, Context), {atomics_to_string([S1,S2,S3],String)}.
sym_braces(String, Context) --> braces(S1), symbol(S2, Context), sym_braces(S3, Context), {atomics_to_string([S1,S2,S3],String)}.
sym_braces(String, Context) --> symbol(String, Context).
sym_braces(String, _) --> braces(String).
sym_braces(String, Context) --> ['{'], sym_braces(S2, Context), {atomics_to_string(['{',S2],String)}.
sym_braces(String, Context) --> ['}'], sym_braces(S2, Context), {atomics_to_string(['}',S2],String)}.

grammar(String) --> sym_braces(String, braces).

brace_expansion(In, Out) :- atom_chars(In, Chars), findall(Out,grammar(Out, Chars, []), List), list_to_set(List, Out).


#!/usr/bin/env js

function main() {
    var len = 4;
    playBullsAndCows(len);
}

function playBullsAndCows(len) {
    var num = pickNum(len);
    // print('The secret number is:\n  ' + num.join('\n  '));
    showInstructions(len);
    var nGuesses = 0;
    while (true) {
        nGuesses++;
        var guess = getGuess(nGuesses, len);
        var census = countBovine(num, guess);
        showScore(census.bulls, census.cows);
        if (census.bulls == len) {
            showFinalResult(nGuesses);
            return;
        }
    }
}

function showScore(nBulls, nCows) {
    print('    Bulls: ' + nBulls + ', cows: ' + nCows);
}

function showFinalResult(guesses) {
    print('You win!!! Guesses needed: ' + guesses);
}

function countBovine(num, guess) {
    var count = {bulls:0, cows:0};
    var g = guess.join('');
    for (var i = 0; i < num.length; i++) {
        var digPresent = g.search(num[i]) != -1;
        if (num[i] == guess[i]) count.bulls++;
        else if (digPresent) count.cows++;
    }
    return count;
}

function getGuess(nGuesses, len) {
    while (true) {
        putstr('Your guess #' + nGuesses + ': ');
        var guess = readline();
        guess = String(parseInt(guess)).split('');
        if (guess.length != len) {
            print('  You must enter a ' + len + ' digit number.');
            continue;
        }
        if (hasDups(guess)) {
            print('  No digits can be duplicated.');
            continue;
        }
        return guess;
    }
}

function hasDups(ary) {
    var t = ary.concat().sort();
    for (var i = 1; i < t.length; i++) {
        if (t[i] == t[i-1]) return true;
    }
    return false;
}

function showInstructions(len) {
    print();
    print('Bulls and Cows Game');
    print('-------------------');
    print('  You must guess the ' + len + ' digit number I am thinking of.');
    print('  The number is composed of the digits 1-9.');
    print('  No digit appears more than once.');
    print('  After each of your guesses, I will tell you:');
    print('    The number of bulls (digits in right place)');
    print('    The number of cows (correct digits, but in the wrong place)');
    print();
}

function pickNum(len) {
    var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    nums.sort(function(){return Math.random() - 0.5});
    return nums.slice(0, len);
}

main();


function sameDigits(n,b)
    local f = n % b
    n = math.floor(n / b)
    while n > 0 do
        if n % b ~= f then
            return false
        end
        n = math.floor(n / b)
    end
    return true
end

function isBrazilian(n)
    if n < 7 then
        return false
    end
    if (n % 2 == 0) and (n >= 8) then
        return true
    end
    for b=2,n-2 do
        if sameDigits(n,b) then
            return true
        end
    end
    return false
end

function isPrime(n)
    if n < 2 then
        return false
    end
    if n % 2 == 0 then
        return n == 2
    end
    if n % 3 == 0 then
        return n == 3
    end

    local d = 5
    while d * d <= n do
        if n % d == 0 then
            return false
        end
        d = d + 2

        if n % d == 0 then
            return false
        end
        d = d + 4
    end

    return true
end

function main()
    local kinds = {" ", " odd ", " prime "}

    for i=1,3 do
        print("First 20" .. kinds[i] .. "Brazillion numbers:")
        local c = 0
        local n = 7
        while true do
            if isBrazilian(n) then
                io.write(n .. " ")
                c = c + 1
                if c == 20 then
                    print()
                    print()
                    break
                end
            end
            if i == 1 then
                n = n + 1
            elseif i == 2 then
                n = n + 2
            elseif i == 3 then
                repeat
                    n = n + 2
                until isPrime(n)
            end
        end
    end
end

main()


package main

// Files required to build supporting package raster are found in:
// * Bitmap
// * Read a PPM file
// * Write a PPM file

import (
    "log"
    "os/exec"
    "raster"
)

func main() {
    c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-")
    pipe, err := c.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }
    if err = c.Start(); err != nil {
        log.Fatal(err)
    }
    b, err := raster.ReadPpmFrom(pipe)
    if err != nil {
        log.Fatal(err)
    }
    if err = b.WritePpmFile("Unfilledcirc.ppm"); err != nil {
        log.Fatal(err)
    }
}


using Images, FileIO

img = load("data/bitmapOutputTest.jpg")
save("data/bitmapOutputTest.ppm", img)


// Version 1.2.40

import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.PushbackInputStream
import java.io.File
import javax.imageio.ImageIO

class BasicBitmapStorage(width: Int, height: Int) {
    val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)

    fun fill(c: Color) {
        val g = image.graphics
        g.color = c
        g.fillRect(0, 0, image.width, image.height)
    }

    fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())

    fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))

    fun toGrayScale() {
        for (x in 0 until image.width) {
            for (y in 0 until image.height) {
                var rgb  = image.getRGB(x, y)
                val red   = (rgb shr 16) and 0xFF
                val green = (rgb shr  8) and 0xFF
                val blue  =  rgb and 0xFF
                val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt()
                rgb = (lumin shl 16) or (lumin shl 8) or lumin
                image.setRGB(x, y, rgb)
            }
        }
    }
}

fun PushbackInputStream.skipComment() {
    while (read().toChar() != '\n') {}
}

fun PushbackInputStream.skipComment(buffer: ByteArray) {
    var nl: Int
    while (true) {
        nl = buffer.indexOf(10) // look for newline at end of comment
        if (nl != -1) break
        read(buffer)  // read another buffer full if newline not yet found
    }
    val len = buffer.size
    if (nl < len - 1) unread(buffer, nl + 1, len - nl - 1)
}

fun Byte.toUInt() = if (this < 0) 256 + this else this.toInt()

fun main(args: Array<String>) {
    // use file, output_piped.jpg, created in the
    // Bitmap/PPM conversion through a pipe task
    val pb = ProcessBuilder("convert", "output_piped.jpg", "ppm:-")
    pb.directory(null)
    pb.redirectOutput(ProcessBuilder.Redirect.PIPE)
    val proc = pb.start()
    val pStdOut = proc.inputStream
    val pbis = PushbackInputStream(pStdOut, 80)
    pbis.use {
        with (it) {
            val h1 = read().toChar()
            val h2 = read().toChar()
            val h3 = read().toChar()
            if (h1 != 'P' || h2 != '6' || h3 != '\n') {
                println("Not a P6 PPM file")
                System.exit(1)
            }
            val sb = StringBuilder()
            while (true) {
                val r = read().toChar()
                if (r == '#') { skipComment(); continue }
                if (r == ' ') break  // read until space reached
                sb.append(r.toChar())
            }
            val width = sb.toString().toInt()
            sb.setLength(0)
            while (true) {
                val r = read().toChar()
                if (r == '#') { skipComment(); continue }
                if (r == '\n') break  // read until new line reached
                sb.append(r.toChar())
            }
            val height = sb.toString().toInt()
            sb.setLength(0)
            while (true) {
                val r = read().toChar()
                if (r == '#') { skipComment(); continue }
                if (r == '\n') break  // read until new line reached
                sb.append(r.toChar())
            }
            val maxCol = sb.toString().toInt()
            if (maxCol !in 0..255) {
                println("Maximum color value is outside the range 0..255")
                System.exit(1)
            }
            var buffer = ByteArray(80)
            // get rid of any more opening comments before reading data
            while (true) {
                read(buffer)
                if (buffer[0].toChar() == '#') {
                    skipComment(buffer)
                }
                else {
                    unread(buffer)
                    break
                }
            }
            // read data
            val bbs = BasicBitmapStorage(width, height)
            buffer = ByteArray(width * 3)
            var y = 0
            while (y < height) {
                read(buffer)
                for (x in 0 until width) {
                    val c = Color(
                        buffer[x * 3].toUInt(),
                        buffer[x * 3 + 1].toUInt(),
                        buffer[x * 3 + 2].toUInt()
                    )
                    bbs.setPixel(x, y, c)
                }
                y++
            }
            // convert to grayscale and save to a file
            bbs.toGrayScale()
            val grayFile = File("output_piped_gray.jpg")
            ImageIO.write(bbs.image, "jpg", grayFile)
        }
    }
}


def getitem(s, depth=0):
    out = [""]
    while s:
        c = s[0]
        if depth and (c == ',' or c == '}'):
            return out,s
        if c == '{':
            x = getgroup(s[1:], depth+1)
            if x:
                out,s = [a+b for a in out for b in x[0]], x[1]
                continue
        if c == '\\' and len(s) > 1:
            s, c = s[1:], c + s[1]

        out, s = [a+c for a in out], s[1:]

    return out,s

def getgroup(s, depth):
    out, comma = [], False
    while s:
        g,s = getitem(s, depth)
        if not s: break
        out += g

        if s[0] == '}':
            if comma: return out, s[1:]
            return ['{' + a + '}' for a in out], s[1:]

        if s[0] == ',':
            comma,s = True, s[1:]

    return None

# stolen cowbells from Raku example
for s in '''~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\\\{ edge, edge} \,}{ cases, {here} \\\\\\\\\}'''.split('\n'):
    print "\n\t".join([s] + getitem(s)[0]) + "\n"


#lang racket/base
(require racket/match)
(define (merge-lists as . bss)
  (match bss
    ['() as]
    [(cons b bt)
     (apply merge-lists
            (for*/list ((a (in-list as)) (b (in-list b))) (append a b))
            bt)]))

(define (get-item cs depth)
  (let loop ((out '(())) (cs cs))
    (match cs
      ['() (values out cs)]
      [`(,(or #\, #\}) . ,more) #:when (positive? depth) (values out cs)]
      [`(#\{ . ,more)
       (=> no-group-match)
       (define-values (group-out group-rem) (get-group more (add1 depth) no-group-match))
       (loop (merge-lists out group-out) group-rem)]
      [(or `(#\\ ,c ,more ...) `(,c . ,more)) (loop (merge-lists out (list (list c))) more)])))

(define (get-group cs depth no-group-match)
  (let loop ((out '()) (cs cs) (comma? #f))
    (when (null? cs) (no-group-match))
    (define-values (item-out item-rem) (get-item cs depth))
    (when (null? item-rem) (no-group-match))
    (let ((out (append out item-out)))
      (match item-rem
        [`(#\} . ,more) #:when comma? (values out more)]
        [`(#\} . ,more) (values (merge-lists '((#\{)) out '((#\}))) more)]
        [`(#\, . ,more) (loop out more #t)]
        [_ (no-group-match)]))))

(define (brace-expand s)
  (let-values (([out rem] (get-item (string->list s) 0))) (map list->string out)))

(module+ test
  (define patterns
    (list
     "~/{Downloads,Pictures}/*.{jpg,gif,png}"
     "It{{em,alic}iz,erat}e{d,}, please."
     #<<P
{,{,gotta have{ ,\, again\, }}more }cowbell!
P
     #<<P
{}} some }{,{\\\\{ edge, edge} \,}{ cases, {here} \\\\\\\\\}
P
     ))
  (for ((s (in-list patterns)) #:when (printf "expand: ~a~%" s) (x (in-list (brace-expand s))))
    (printf "\t~a~%" x)))


function cowsbulls()
	print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n
		You get one bull for every right number in the right position.\n
		You get one cow for every right number, but in the wrong position.\n
		Enter 'n' to pick a new number and 'q' to quit.\n>")
	function new_number()
		s = [1:9]
		n = ""
		for i = 9:-1:6
			n *= string(delete!(s,rand(1:i)))
		end
		return n
	end
	answer = new_number()
	while true
		input = chomp(readline(STDIN))
		input == "q" && break
		if input == "n"
			answer = new_number()
			print("\nI've picked a new number, go ahead and guess\n>")
			continue
		end
		!ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue)
		if input == answer
			print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>")
		else
			bulls = sum(answer.data .== input.data)
			cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4])
			print("\nNot quite! Your guess is worth:\n$bulls Bulls\n$cows Cows\nPlease guess again\n\n>")
		end
	end
end


// version 1.1.2

import java.util.Random

const val MAX_GUESSES = 20  // say

fun main(args: Array<String>) {
    val r = Random()
    var num: String
    // generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits
    do {
        num = (1234 + r.nextInt(8643)).toString()
    } while ('0' in num || num.toSet().size < 4)

    println("All guesses should have exactly 4 distinct digits excluding zero.")
    println("Keep guessing until you guess the chosen number (maximum $MAX_GUESSES valid guesses).\n")
    var guesses = 0
    while (true) {
        print("Enter your guess : ")
        val guess = readLine()!!
        if (guess == num) {
            println("You've won with ${++guesses} valid guesses!")
            return
        }
        val n = guess.toIntOrNull()
        if (n == null)
            println("Not a valid number")
        else if ('-' in guess || '+' in guess)
            println("Can't contain a sign")
        else if ('0' in guess)
            println("Can't contain zero")
        else if (guess.length != 4)
            println("Must have exactly 4 digits")
        else if (guess.toSet().size < 4)
            println("All digits must be distinct")
        else {
            var bulls = 0
            var cows  = 0
            for ((i, c) in guess.withIndex()) {
                if (num[i] == c) bulls++
                else if (c in num) cows++
            }
            println("Your score for this guess:  Bulls = $bulls  Cows = $cows")
            guesses++
            if (guesses == MAX_GUESSES)
                println("You've now had $guesses valid guesses, the maximum allowed")
        }
    }
}


brazilianQ[n_Integer /; n>6 ] := AnyTrue[
    Range[2, n-2],
    MatchQ[IntegerDigits[n, #], {x_ ...}] &
]
Select[Range[100], brazilianQ, 20]
Select[Range[100], [email protected]# && [email protected]# &, 20]
Select[Range[10000], [email protected]# && [email protected]# &, 20]


proc isPrime(n: Positive): bool =
  ## Check if a number is prime.
  if n mod 2 == 0:
    return n == 2
  if n mod 3 == 0:
    return n == 3
  var d = 5
  while d * d <= n:
    if n mod d == 0:
      return false
    if n mod (d + 2) == 0:
      return false
    inc d, 6
  result = true

proc sameDigits(n, b: Positive): bool =
  ## Check if the digits of "n" in base "b" are all the same.
  var d = n mod b
  var n = n div b
  if d == 0:
    return false
  while n > 0:
    if n mod b != d:
      return false
    n = n div b
  result = true

proc isBrazilian(n: Positive): bool =
  ## Check if a number is brazilian.
  if n < 7:
    return false
  if (n and 1) == 0:
    return true
  for b in 2..(n - 2):
    if sameDigits(n, b):
      return true

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

when isMainModule:
  import strutils

  template printList(title: string; findNextToCheck: untyped) =
    ## Template to print a list of brazilians numbers.
    ## "findNextTocheck" is a list of instructions to find the
    ## next candidate starting for the current one "n".

    block:
      echo '\n' & title
      var n {.inject.} = 7
      var list: seq[int]
      while true:
        if n.isBrazilian():
          list.add(n)
          if list.len == 20: break
        findNextToCheck
      echo list.join(", ")

  printList("First 20 Brazilian numbers:"):
    inc n

  printList("First 20 odd Brazilian numbers:"):
    inc n, 2

  printList("First 20 prime Brazilian numbers:"):
    inc n, 2
    while not n.isPrime():
      inc n, 2


program brazilianNumbers;

{$IFDEF FPC}
  {$MODE DELPHI}{$OPTIMIZATION ON,All}
  {$CODEALIGN proc=32,loop=4}
{$ELSE}
  {$APPTYPE CONSOLE}
{$ENDIF}
uses
  SysUtils;

const
  //Must not be a prime
  PrimeMarker = 0;
  SquareMarker = PrimeMarker + 1;
  //MAX =    110468;// 1E5 brazilian
  //MAX =   1084566;// 1E6 brazilian
  //MAX =  10708453;// 1E7 brazilian
  //MAX = 106091516;// 1E8 brazilian
  MAX = 1053421821;// 1E9 brazilian

var
  isprime: array of word;

  procedure MarkSmallestFactor;
  //sieve of erathotenes
  //but saving the smallest factor
  var
    i, j, lmt: NativeUint;
  begin
    lmt := High(isPrime);
    fillWord(isPrime[0], lmt + 1, PrimeMarker);
    //mark even numbers
    i := 2;
    j := i * i;
    isPrime[j] := SquareMarker;
    Inc(j, 2);
    while j <= lmt do
    begin
      isPrime[j] := 2;
      Inc(j, 2);
    end;
    //mark 3 but not 2
    i := 3;
    j := i * i;
    isPrime[j] := SquareMarker;
    Inc(j, 6);
    while j <= lmt do
    begin
      isPrime[j] := 3;
      Inc(j, 6);
    end;

    i := 5;
    while i * i <= lmt do
    begin
      if isPrime[i] = 0 then
      begin
        j := lmt div i;
        if not (odd(j)) then
          Dec(j);
        while j > i do
        begin
          if isPrime[j] = 0 then
            isPrime[i * j] := i;
          Dec(j, 2);
        end;
        //mark square prime
        isPrime[i * i] := SquareMarker;
      end;
      Inc(i, 2);
    end;
  end;

  procedure OutFactors(n: NativeUint);
  var
    divisor, Next, rest: NativeUint;
    pot: NativeUint;
  begin
    divisor := 2;
    Next := 3;
    rest := n;
    Write(n: 10, ' = ');
    while (rest <> 1) do
    begin
      if (rest mod divisor = 0) then
      begin
        Write(divisor);
        pot := 0;
        repeat
          rest := rest div divisor;
          Inc(pot)
        until rest mod divisor <> 0;
        if pot > 1 then
          Write('^', pot);
        if rest > 1 then
          Write('*');
      end;
      divisor := Next;
      Next := Next + 2;
      // cut condition: avoid many useless iterations
      if (rest <> 1) and (rest < divisor * divisor) then
      begin
        Write(rest);
        rest := 1;
      end;
    end;
    Write('  ', #9#9#9);
  end;

  procedure OutToBase(number, base: NativeUint);
  var
    BaseDgt: array[0..63] of NativeUint;
    i, rest: NativeINt;
  begin
    OutFactors(number);
    i := 0;
    while number <> 0 do
    begin
      rest := number div base;
      BaseDgt[i] := number - rest * base;
      number := rest;
      Inc(i);
    end;
    while i > 1 do
    begin
      Dec(i);
      Write(BaseDgt[i]);
    end;
    writeln(BaseDgt[0], ' to base ', base);
  end;

  function PrimeBase(number: NativeUint): NativeUint;
  var
    lnN: extended;
    i, exponent, n: NativeUint;
  begin
    // primes are only brazilian if 111...11 to base > 2
    // the count of "1" must be odd , because brazilian primes are odd
    lnN := ln(number);
    exponent := 4;
    //result := exponent.th root of number
    Result := trunc(exp(lnN*0.25));
    while result >2 do
    Begin
      // calc sum(i= 0 to exponent ) base^i;
      n := Result + 1;
      i := 2;
      repeat
        Inc(i);
        n := n*result + 1;
      until i > exponent;
      if n = number then
        EXIT;
      Inc(exponent,2);
      Result := trunc(exp(lnN/exponent));
    end;
    //not brazilian
    Result := 0;
  end;

  function GetPrimeBrazilianBase(number: NativeUint): NativeUint;
    //result is base
  begin
    // prime of 2^n - 1
    if (Number and (number + 1)) = 0 then
      Result := 2
    else
    begin
      Result := trunc(sqrt(number));
      //most of the brazilian primes are of this type base^2+base+1
      IF (sqr(result)+result+1) <> number then
        result := PrimeBase(number);
    end;
  end;

  function GetBrazilianBase(number: NativeUInt): NativeUint; inline;
  begin
    Result := isPrime[number];
    if Result > SquareMarker then
      Result := (number div Result) - 1
    else
    begin
      if Result = SquareMarker then
      begin
        if number = 121 then
          Result := 3
        else
          Result := 0;
      end
      else
        Result := GetPrimeBrazilianBase(number);
    end;
  end;

  procedure First20Brazilian;
  var
    i, n, cnt: NativeUInt;
  begin
    writeln('first 20 brazilian numbers');
    i := 7;
    cnt := 0;
    while cnt < 20 do
    begin
      n := GetBrazilianBase(i);
      if n <> 0 then
      begin
        Inc(cnt);
        OutToBase(i, n);
      end;
      Inc(i);
    end;
    writeln;
  end;

  procedure First33OddBrazilian;
  var
    i, n, cnt: NativeUInt;
  begin
    writeln('first 33 odd brazilian numbers');
    i := 7;
    cnt := 0;
    while cnt < 33 do
    begin
      n := GetBrazilianBase(i);
      if N <> 0 then
      begin
        Inc(cnt);
        OutToBase(i, n);
      end;
      Inc(i, 2);
    end;
    writeln;
  end;

  procedure First20BrazilianPrimes;
  var
    i, n, cnt: NativeUInt;
  begin
    writeln('first 20 brazilian prime numbers');
    i := 7;
    cnt := 0;
    while cnt < 20 do
    begin
      IF isPrime[i] = PrimeMarker then
      Begin
        n := GetBrazilianBase(i);
        if n <> 0 then
        begin
          Inc(cnt);
          OutToBase(i, n);
        end;
      end;
      Inc(i);
    end;
    writeln;
  end;

var
  T1, T0: TDateTime;
  i, n, cnt, lmt: NativeUInt;
begin
  lmt := MAX;
  setlength(isPrime, lmt + 1);
  MarkSmallestFactor;

  First20Brazilian;
  First33OddBrazilian;
  First20BrazilianPrimes;

  Write('count brazilian numbers up to ', lmt, ' = ');
  T0 := now;
  i := 7;
  cnt := 0;
  n := 0;

  while (i <= lmt) do
  begin
    Inc(n, Ord(isPrime[i] = PrimeMarker));
    if GetBrazilianBase(i) <> 0 then
      Inc(cnt);
    Inc(i);
  end;

  T1 := now;

  writeln(cnt);
  writeln('Count of primes ', n: 11+13);
  writeln((T1 - T0) * 86400 * 1000: 10: 0, ' ms');

  setlength(isPrime, 0);
end.


function Bitmap:loadPPM(filename, fp)
  if not fp then fp = io.open(filename, "rb") end
  if not fp then return end
  local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
  self.width, self.height = width, height
  self:alloc()
  for y = 1, self.height do
    for x = 1, self.width do
      self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
    end
  end
  fp:close()
end


import bitmap
import osproc
import ppm_read
import streams

# Launch Netpbm "jpegtopnm".
# Input is taken from "input.jpeg" and result sent to stdout.
let p = startProcess("jpegtopnm", args = ["input.jpeg"], options = {poUsePath})
let stream = FileStream(p.outputStream())
let image = stream.readPPM()
echo image.w, " ", image.h
p.close()


let read_image ~filename =
  if not(Sys.file_exists filename)
  then failwith(Printf.sprintf "the file %s does not exist" filename);
  let cmd = Printf.sprintf "convert \"%s\" ppm:-" filename in
  let ic, oc = Unix.open_process cmd in
  let img = read_ppm ~ic in
  (img)
;;


# 20211226 Perl programming solution

use strict;
use warnings;

use Imager;

my $raw;

open my $fh, '-|', 'cat Lenna50.jpg' or die;
binmode $fh;
while ( sysread $fh , my $chunk , 1024 ) { $raw .= $chunk }
close $fh;

my $enable = $Imager::formats{"jpeg"}; # some kind of tie ?

my $IO = Imager::io_new_buffer $raw or die;
my $im = Imager::File::JPEG::i_readjpeg_wiol $IO or die;

open my $fh2, '>', 'output.ppm' or die;
binmode $fh2;
my $IO2 = Imager::io_new_fd(fileno $fh2);
Imager::i_writeppm_wiol $im, $IO2 ;
close $fh2;
undef($im);


grammar BraceExpansion {
    token TOP  { ( <meta> | . )* }
    token meta { '{' <alts> '}' | \\ .  }
    token alts { <alt>+ % ',' }
    token alt  { ( <meta> | <-[ , } ]> )* }
}

sub crosswalk($/) {
    |[X~] flat '', $0.map: -> $/ { $<meta><alts><alt>.&alternatives or ~$/ }
}

sub alternatives($_) {
    when :not { () }
    when 1    { '{' X~ $_».&crosswalk X~ '}' }
    default   { $_».&crosswalk }
}

sub brace-expand($s) { crosswalk BraceExpansion.parse($s) }

# Testing:

sub bxtest(*@s) {
    for @s -> $s {
        say "\n$s";
        for brace-expand($s) {
            say "    ", $_;
        }
    }
}

bxtest Q:to/END/.lines;
    ~/{Downloads,Pictures}/*.{jpg,gif,png}
    It{{em,alic}iz,erat}e{d,}, please.
    {,{,gotta have{ ,\, again\, }}more }cowbell!
    a{b{1,2}c
    a{1,2}b}c
    a{1,{2},3}b
    more{ darn{ cowbell,},}
    ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr
    {a,{\,b}c
    a{b,{{c}}
    {a{\}b,c}d
    END


[
define randomizer() => {
	local(n = string)
	while(#n->size < 4) => {
		local(r = integer_random(1,9)->asString)
		#n !>> #r ? #n->append(#r)
	}
	return #n
}
define cowbullchecker(n::string,a::string) => {
	integer(#n) == integer(#a) ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a))
	local(cowbull = map('cows'=0,'bulls'=0,'choice'=#a),'checked' = array)
	loop(4) => {
		if(#checked !>> integer(#a->values->get(loop_count))) => {
			#checked->insert(integer(#a->values->get(loop_count)))
			if(integer(#n->values->get(loop_count)) == integer(#a->values->get(loop_count))) => {
				#cowbull->find('bulls') += 1
			else(#n->values >> #a->values->get(loop_count))
				#cowbull->find('cows') += 1
			}
		}
	}
	#cowbull->find('bulls') == 4 ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a))
	return (:true,#cowbull)
}
session_start('user')
session_addvar('user', 'num')
session_addvar('user', 'historic_choices')
// set up rand
var(num)->isNotA(::string) ? var(num = randomizer)
var(historic_choices)->isNotA(::array) ? var(historic_choices = array)
local(success = false)
// check answer
if(web_request->param('a')->asString->size) => {
	local(success,result) = cowbullchecker($num,web_request->param('a')->asString)
	$historic_choices->insert(#result)
}
if(web_request->params->asStaticArray >> 'restart') => {
	$num = randomizer
	$historic_choices = array
}
]

Bulls and Cows

Guess the 4-digit number...

Your win if the guess is the same as the randomly chosen number.

- A score of one bull is accumulated for each digit in your guess that equals the corresponding digit in the randomly chosen initial number.

- A score of one cow is accumulated for each digit in your guess that also appears in the randomly chosen number, but in the wrong position.

[
local(win = false)
if($historic_choices->size) => {
	with c in $historic_choices do => {^
		'
'+#c->find('choice')+': Bulls: '+#c->find('bulls')+', Cows: '+#c->find('cows')
		if(#c->find('bulls') == 4) => {^
			' - YOU WIN!'
			#win = true
		^}
		'
'
	^}
}
if(not #win) => {^
]
<form action="?" method="post">
	<input name="a" value="[web_request->param('a')->asString]" size="5">
	<input type="submit" name="guess">
	Restart
</form>
[else
	'Restart'
^}]


    do while len( secret$) <4
        c$ =chr$( int( rnd( 1) *9) +49)
        if not( instr( secret$, c$)) then secret$ =secret$ +c$
    loop

    print " Secret number has been guessed....                                                                                "; secret$

    guesses  =   0

[loop]
    print " Your guess ";
    input " "; guess$

    guesses  = guesses +1

    r$       =score$( guess$, secret$)

    bulls    =val( word$( r$, 1, ","))
    cows     =val( word$( r$, 2, ","))

    print "   Result: "; bulls; " bulls, and "; cows; " cows"
    print

    if guess$ =secret$ then
        print "  You won after "; guesses; " guesses!"
        print "  You guessed it in "; guesses
        print "  Thanks for playing!"
        wait
    end if

    goto [loop]

end '   _____________________________________________________________

function check( i$) '   check =0 if no digit repeats, else =1
    check =0
    for i =1 to 3
        for j =i +1 to 4
            if mid$( i$, i, 1) =mid$( i$, j, 1) then check =1
        next j
    next i
end function

function score$( a$, b$)    '   return as a csv string the number of bulls & cows.
    bulls    = 0:  cows     = 0
    for i = 1 to 4
        c$ = mid$( a$, i, 1)
        if mid$( b$, i, 1) = c$ then
            bulls = bulls + 1
        else
            if instr( b$, c$) <>0 and instr( b$, c$) <>i then
                cows = cows + 1
            end if
        end if
    next i
    score$ =str$( bulls); ","; str$( cows)
end function

[quit]
close #w
end


use strict;
use warnings;
use ntheory qw<is_prime>;
use constant Inf  => 1e10;

sub is_Brazilian {
    my($n) = @_;
    return 1 if $n > 6 && 0 == $n%2;
    LOOP: for (my $base = 2; $base < $n - 1; ++$base) {
        my $digit;
        my $nn = $n;
        while (1) {
            my $x = $nn % $base;
            $digit //= $x;
            next LOOP if $digit != $x;
            $nn = int $nn / $base;
            if ($nn < $base) {
                return 1 if $digit == $nn;
                next LOOP;
            }
        }
    }
}

my $upto = 20;

print "First $upto Brazilian numbers:\n";
my $n = 0;
print do { $n < $upto ? (is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf;

print "\n\nFirst $upto odd Brazilian numbers:\n";
$n = 0;
print do { $n < $upto ? (!!($_%2) and is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf;

print "\n\nFirst $upto prime Brazilian numbers:\n";
$n = 0;
print do { $n < $upto ? (!!is_prime($_) and is_Brazilian($_) and ++$n and "$_ ") : last } for 1 .. Inf;


-- demo\rosetta\Bitmap_Read_an_image_through_a_pipe.exw
without js -- file i/o, system_exec(), pipes[!!]
include builtins\pipeio.e
include ppm.e -- read_ppm(), write_ppm()

sequence pipes = repeat(0,3)
pipes[PIPOUT] = create_pipe(INHERIT_READ)

-- Create the child process, with replacement stdout.
string cmd = sprintf("%s viewppm -load test.jpg",{get_interpreter(true)})
atom hProc = system_exec(cmd, 12, pipes),
     hPipe = pipes[PIPOUT][READ_PIPE]

string ppm = read_from_pipe(hPipe, hProc)
while true do
    object chunk = read_from_pipe(hPipe, hProc)
    if chunk=-1 then exit end if
    ppm &= chunk
end while

pipes = close_handles(pipes)

if 0 then
    sequence img = read_ppm(ppm,bText:=true)
    write_ppm("Lenapipe.ppm", img)
else -- or
    integer fn = open("Lenapipe.ppm","wb")
    puts(fn,ppm)
    close(fn)
end if

?"done"
{} = wait_key()


(setq *Ppm (ppmRead '("convert" "img.jpg" "ppm:-")))


"""
Adapted from https://stackoverflow.com/questions/26937143/ppm-to-jpeg-jpg-conversion-for-python-3-4-1
Requires pillow-5.3.0 with Python 3.7.1 32-bit on Windows.
Sample ppm graphics files from http://www.cs.cornell.edu/courses/cs664/2003fa/images/
"""

from PIL import Image

# boxes_1.jpg is the jpg version of boxes_1.ppm

im = Image.open("boxes_1.jpg")
im.save("boxes_1v2.ppm")


(define (read-ppm port)
  (parameterize ([current-input-port port])
    (define magic (read-line))
    (match-define (list w h) (string-split (read-line) " "))
    (define width (string->number w))
    (define height (string->number h))
    (define maxcol (string->number (read-line)))
    (define bm (make-object bitmap% width height))
    (define dc (new bitmap-dc% [bitmap bm]))
    (send dc set-smoothing 'unsmoothed)
    (define (adjust v) (* 255 (/ v maxcol)))
    (for/list ([x width])
      (for/list ([y height])
        (define red (read-byte))
        (define green (read-byte))
        (define blue (read-byte))
        (define color (make-object color% (adjust red) (adjust green) (adjust blue)))
        (send dc set-pen color 1 'solid)
        (send dc draw-point x y)))
    bm))

(define (image->bmp filename)
  (define command (format "convert ~a ppm:-" filename))
  (match-define (list in out pid err ctrl)  (process command))
  (define bmp (read-ppm in))
  (close-input-port in)
  (close-output-port out)
  bmp)

(image->bmp "input.jpg")


class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
    has UInt ($.width, $.height);
    has Pixel @.data;
}

role PPM {
    method P6 returns Blob {
	"P6\n{self.width} {self.height}\n255\n".encode('ascii')
	~ Blob.new: flat map { .R, .G, .B }, self.data
    }
}

sub getline ( $proc ) {
    my $line = '#'; # skip comment when reading a .png
    $line = $proc.out.get while $line.substr(0,1) eq '#';
    $line;
}

my $filename = './camelia.png';

my $proc = run 'convert', $filename, 'ppm:-', :enc('ISO-8859-1'), :out;

my $type = getline($proc);
my ($width, $height) = getline($proc).split: ' ';
my $depth = getline($proc);

my Bitmap $b = Bitmap.new( width => $width.Int, height => $height.Int) but PPM;

$b.data = $proc.out.slurp.ords.rotor(3).map:
  { Pixel.new(R => .[0], G => .[1], B => .[2]) };

'./camelia.ppm'.IO.open(:bin, :w).write: $b.P6;


/*- REXX --------------------------------------------------------------
* Brace expansion
* 26.07.2016
* s.* holds the set of strings
*--------------------------------------------------------------------*/
text.1='{,{,gotta have{ ,\, again\, }}more }cowbell!'
text.2='~/{Downloads,Pictures}/*.{jpg,gif,png}'
text.3='It{{em,alic}iz,erat}e{d,}, please. '
text.4='{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\} '
text.5='x{,a,b,c}{d,e}y'
text.6='aa{,{,11}cc}22'
text.7='{}'
Parse Arg dbg
oid='brace.xxx'; 'erase' oid
Do case=1 To 7
  Call brac text.case
  End
Return
brac:
  s.=0
  Parse Arg s
  Say ''
  Say '  's
  s.1.0=1                            /* first iteration              */
  s.1.1=s                            /* the initial string           */
  Do it=1 To 10 Until todo=0         /* Iterate until all done       */
    todo=0                           /* will be 1 if more to be done */
    Call dbg 'Iteration' it
    do di=1 To s.it.0                /* show current state           */
      Call dbg 's.'it'.'di  s.it.di
      End
    ita=it+1                         /* index for next set of strings*/
    xp=0
    do di=1 To s.it.0                /* loop over all strings        */
      Call dbg it'.'di s.it.di
      Call bra s.it.di               /* analyze current string       */
      If braces=1 Then Do            /* If brace groups were found   */
        Do bgi=1 To bgdata.0         /* loop over grace groups       */
          If end.bgi=0 Then Iterate  /* Incomplete bg (... )         */
          clist=''
          Do cj=1 To ci.bgi.0
            clist=clist ci.bgi.cj
            End
          Call dbg bgdata.bgi '->' clist
          If ccount.bgi>0 Then Do    /* comma(s) founf in bg         */
            Call expand bgi          /* expand this bg               */
            xp=1                     /* indicate that we worked      */
            Leave
            End
          End
        If xp=0 Then Do              /* nothing done                 */
          z=s.ita.0+1                /* copy string to next iteration*/
          s.ita.z=s.it.di
          End
        End
      Else Do                        /* no brace group               */
        z=s.ita.0+1                  /* copy string to next iteration*/
        s.ita.z=s
        s.ita.0=z
        End
      End
    Do dd=1 To s.ita.0               /* log current set of strings   */
      Call dbg ita dd s.ita.dd
      End
    End
  Do dd=1 To s.it.0                  /* show final set of strings    */
    Say dd s.it.dd
    End
  Return

bra:
/*---------------------------------------------------------------------
* Analyze the given string
* Input: s
* Output:
* bgdata.*  Array of data about brace groups:
*                      level start column comma positions end column
*--------------------------------------------------------------------*/
parse Arg s
Call dbg 'bra:' s
level=0
bgdata.=0
bgn=0
bgnmax=0
ccount.=0
ol=''
ci.=0
bgnl=''
braces=0
end.=0
escape=0
Do i=1 To length(s)
  c=substr(s,i,1)
  Select
    When escape Then
      escape=0
    When c='\' Then
      escape=1
    When c='{' Then Do
      level=level+1
      Call bm c
      co=level
      End
    When c='}' Then Do
      If level>0 Then Do
        co=level
        Call bm c
        level=level-1
        End
      End
    When c=',' Then Do
      co=level
      If co>0 Then Do
        ccount.bgn=ccount.bgn+1
        z=ccount.bgn
        ci.bgn.0=z
        ci.bgn.z=i
        End
      If ccount.bgn>0 Then
        braces=1
      End
    Otherwise
      co=level
    End
  ol=ol||co
  bgnl=bgnl||bgn
  End
Call dbg s
Call dbg ol
Call dbg left(copies('123456789.',10),length(s))
Call dbg bgnl
Do bgi=1 To bgdata.0
  If end.bgi=1 Then Do
    cl=''
    Do cii=1 To ci.bgi.0
      cl=cl ci.bgi.cii
      End
    Parse Var bgdata.bgi level a e
    Call dbg bgi level a cl e
    End
  End
Return

bm:
/*---------------------------------------------------------------------
* Brace Management
* for '{' create a new brace group )record level and start column
* for '}' look for corresponding bg and add end column
* Input: column and character ( '{' or '}' )
* Output: bgdata.*  level start-column [end-column]
*--------------------------------------------------------------------*/
  Parse Arg oc
  Call dbg oc i level
  If oc='{' Then Do
    z=bgdata.0+1
    bgdata.z=level i
    bgdata.0=z
    bgn=bgnmax+1
    bgnmax=bgn
    End
  Else Do
    Do bgi=bgdata.0 To 1 By -1
      If level=word(bgdata.bgi,1) Then Do
        bgdata.bgi=bgdata.bgi i
        end.bgi=1
        Leave
        End
      End
    bgn=bgn-1
    Call dbg bgdata.bgi 'bgn='bgn
    End
  Return

expand:
/*---------------------------------------------------------------------
* Expand a brace group in string s
*--------------------------------------------------------------------*/
  Parse Arg bgi
  Parse Var bgdata.bgi . start end
  clist=start clist end
  If words(clist)>0 Then Do          /* commas in brace group        */
    left=left(s,start-1)             /* part of s before the '{'     */
    rite=substr(s,end+1)             /* part of s after the '}'      */
    Do k=1 To words(clist)-1         /* Loop over comma positions    */
      a=word(clist,k)                /* start position               */
      e=word(clist,k+1)              /* end position                 */
      choice.k=substr(s,a+1,e-a-1)   /* one of the choices           */
      z=s.ita.0+1                    /* add new string to next set   */
      s.ita.z=left||choice.k||rite   /* construct new string         */
      s.ita.0=z
      todo=1                         /* maybe more to be done        */
      End
    End
  Else Do                            /* no commas                    */
    z=s.ita.0+1                      /* copy string as is to next set*/
    s.ita.z=s
    s.ita.0=z
    End
  Do zz=1 To s.ita.0
    Call dbg zz s.ita.zz
    End
  Return

dbg:                                 /* handle debug output          */
  If dbg<>'' Then                    /* argument given               */
    Say arg(1)                       /* show on screen               */
  Call lineout oid,arg(1)            /* write to file                */
  Return


to ok? :n
  output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])
end

to init
  do.until [make "hidden random 10000] [ok? :hidden]
end

to guess :n
  if not ok? :n [print [Bad guess! (4 unique digits, 1-9)]  stop]
  localmake "bulls 0
  localmake "cows  0
  foreach :n [cond [
    [[? = item # :hidden] make "bulls 1 + :bulls]
    [[member?  ? :hidden] make "cows  1 + :cows ]
  ]]
  (print :bulls "bulls, :cows "cows)
  if :bulls = 4 [print [You guessed it!]]
end


function ShuffleArray(array)
   for i=1,#array-1 do
      local t = math.random(i, #array)
      array[i], array[t] = array[t], array[i]
   end
end

function GenerateNumber()
   local digits = {1,2,3,4,5,6,7,8,9}

   ShuffleArray(digits)

   return digits[1] * 1000 +
          digits[2] *  100 +
          digits[3] *   10 +
          digits[4]
end

function IsMalformed(input)
   local malformed = false

   if #input == 4 then
      local already_used = {}
      for i=1,4 do
         local digit = input:byte(i) - string.byte('0')
         if digit < 1 or digit > 9 or already_used[digit] then
            malformed = true
            break
         end
         already_used[digit] = true
      end
   else
      malformed = true
   end

   return malformed
end

math.randomseed(os.time())
math.randomseed(math.random(2^31-1)) -- since os.time() only returns seconds

print("\nWelcome to Bulls and Cows!")
print("")
print("The object of this game is to guess the random 4-digit number that the")
print("computer has chosen. The number is generated using only the digits 1-9,")
print("with no repeated digits. Each time you enter a guess, you will score one")
print("\"bull\" for each digit in your guess that matches the corresponding digit")
print("in the computer-generated number, and you will score one \"cow\" for each")
print("digit in your guess that appears in the computer-generated number, but is")
print("in the wrong position. Use this information to refine your guesses. When")
print("you guess the correct number, you win.");
print("")

quit = false

repeat
   magic_number = GenerateNumber()
   magic_string = tostring(magic_number) -- Easier to do scoring with a string
   repeat
      io.write("\nEnter your guess (or 'Q' to quit): ")
      user_input = io.read()
      if user_input == 'Q' or user_input == 'q' then
         quit = true
         break
      end

      if not IsMalformed(user_input) then
         if user_input == magic_string then
            print("YOU WIN!!!")
         else
            local bulls, cows = 0, 0
            for i=1,#user_input do
               local find_result = magic_string:find(user_input:sub(i,i))

               if find_result and find_result == i then
                  bulls = bulls + 1
               elseif find_result then
                  cows = cows + 1
               end
            end
            print(string.format("You scored %d bulls, %d cows", bulls, cows))
         end
      else
         print("Malformed input. You must enter a 4-digit number with")
         print("no repeated digits, using only the digits 1-9.")
      end

   until user_input == magic_string

   if not quit then
      io.write("\nPress <Enter> to play again or 'Q' to quit: ")
      user_input = io.read()
      if user_input == 'Q' or user_input == 'q' then
         quit = true
      end
   end

   if quit then
      print("\nGoodbye!")
   end
until quit


with javascript_semantics
function same_digits(integer n, b)
    integer f = remainder(n,b)
    n = floor(n/b)
    while n>0 do
        if remainder(n,b)!=f then return false end if
        n = floor(n/b)
    end while
    return true
end function

function is_brazilian(integer n)
    if n>=7 then
        if remainder(n,2)=0 then return true end if
        for b=2 to n-2 do
            if same_digits(n,b) then return true end if
        end for
    end if
    return false
end function

constant kinds = {" ", " odd ", " prime "}
for i=1 to length(kinds) do
    printf(1,"First 20%sBrazilian numbers:\n", {kinds[i]})
    integer c = 0, n = 7, p = 4
    while true do
        if is_brazilian(n) then
            printf(1,"%d ",n)
            c += 1
            if c==20 then
                printf(1,"\n\n")
                exit
            end if
        end if
        switch i
            case 1: n += 1
            case 2: n += 2
            case 3: p += 1; n = get_prime(p)
        end switch
    end while
end for

integer n = 7, c = 0
atom t0 = time(), t1 = time()+1
while c<100000 do
    if platform()!=JS and time()>t1 then
        printf(1,"checking %d [count:%d]...\r",{n,c})
        t1 = time()+1
    end if
    c += is_brazilian(n)
    n += 1
end while
printf(1,"The %,dth Brazilian number: %d\n", {c,n-1})
?elapsed(time()-t0)


# frozen_string_literal: true

require_relative 'raster_graphics'

class Pixmap
  def self.read_ppm(ios)
    format = ios.gets.chomp
    width, height = ios.gets.chomp.split.map(&:to_i)
    max_colour = ios.gets.chomp

    if !PIXMAP_FORMATS.include?(format) ||
       (width < 1) || (height < 1) ||
       (max_colour != '255')
      ios.close
      raise StandardError, "file '#{filename}' does not start with the expected header"
    end
    ios.binmode if PIXMAP_BINARY_FORMATS.include?(format)

    bitmap = new(width, height)
    height.times do |y|
      width.times do |x|
        # read 3 bytes
        red, green, blue = case format
                           when 'P3' then ios.gets.chomp.split
                           when 'P6' then ios.read(3).unpack('C3')
                           end
        bitmap[x, y] = RGBColour.new(red, green, blue)
      end
    end
    ios.close
    bitmap
  end

  def self.open(filename)
    read_ppm(File.open(filename, 'r'))
  end

  def self.open_from_jpeg(filename)
    read_ppm(IO.popen("convert jpg:#{filename} ppm:-", 'r'))
  end
end

bitmap = Pixmap.open_from_jpeg('foto.jpg')
bitmap.save('foto.ppm')


package require Tk

proc magickalReadImage {bufferImage fileName} {
    set f [open |[list convert [file normalize $fileName] ppm:-] "rb"]
    try {
        $bufferImage put [read $f] -format ppm
    } finally {
        close $f
    }
}


import "graphics" for Canvas, ImageData, Color
import "dome" for Window, Process
import "io" for FileSystem
import "plugin" for Plugin

Plugin.load("pipeconv")

import "pipeconv" for PipeConv

class Bitmap {
    construct new(fileName, fileName2, fileName3, width, height) {
        Window.title = "Bitmap - read image via pipe"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _w = width
        _h = height
        _fn3 = fileName3
        // convert .jpg file to .ppm via a pipe
        PipeConv.convert(fileName, fileName2)
        // load the .ppm file
        loadPPMFile(fileName2)
    }

    init() {
        toGrayScale()
        // display gray scale image
        _bmp2.draw(0, 0)
        // save it to file
        _bmp2.saveToFile(_fn3)
    }

    loadPPMFile(fileName) {
        var ppm = FileSystem.load(fileName)
        if (ppm[0..1] != "P6") {
            System.print("The loaded file is not a P6 file.")
            Process.exit()
        }
        var lines = ppm.split("\n")
        if (Num.fromString(lines[2]) > 255) {
            System.print("The maximum color value can't exceed 255.")
            Process.exit()
        }
        var wh = lines[1].split(" ")
        var w = Num.fromString(wh[0])
        var h = Num.fromString(wh[1])
        _bmp = ImageData.create(fileName, w, h)
        var bytes = ppm.bytes
        var i = bytes.count - 3 * w * h
        for (y in 0...h) {
            for (x in 0...w) {
                var r = bytes[i]
                var g = bytes[i+1]
                var b = bytes[i+2]
                var c = Color.rgb(r, g, b)
                pset(x, y, c)
                i = i + 3
            }
        }
    }

    toGrayScale() {
        _bmp2 = ImageData.create("gray scale", _bmp.width, _bmp.height)
        for (x in 0..._bmp.width) {
            for (y in 0..._bmp.height) {
                var c1 = _bmp.pget(x, y)
                var lumin = (0.2126 * c1.r + 0.7152 * c1.g + 0.0722 * c1.b).floor
                var c2 = Color.rgb(lumin, lumin,lumin, c1.a)
                _bmp2.pset(x, y, c2)
            }
        }
    }

    pset(x, y, col) { _bmp.pset(x, y, col) }

    pget(x, y) { _bmp.pget(x, y) }

    update() {}

    draw(alpha) {}
}

var Game = Bitmap.new("output_piped.jpg", "output_piped.ppm", "output_piped_gs.jpg", 350, 350)


def getitem(s, depth=0)
  out = [""]
  until s.empty?
    c = s[0]
    break  if depth>0 and (c == ',' or c == '}')
    if c == '{' and x = getgroup(s[1..-1], depth+1)
      out = out.product(x[0]).map{|a,b| a+b}
      s = x[1]
    else
      s, c = s[1..-1], c + s[1]  if c == '\\' and s.size > 1
      out, s = out.map{|a| a+c}, s[1..-1]
    end
  end
  return out, s
end

def getgroup(s, depth)
  out, comma = [], false
  until s.empty?
    g, s = getitem(s, depth)
    break  if s.empty?
    out += g
    case s[0]
      when '}' then return (comma ? out : out.map{|a| "{#{a}}"}), s[1..-1]
      when ',' then comma, s = true, s[1..-1]
    end
  end
end

strs = <<'EOS'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
EOS

strs.each_line do |s|
  puts s.chomp!
  puts getitem(s)[0].map{|str| "\t"+str}
  puts
end


Module Game {
      Malformed=lambda (a$)->{
            =true
            if len(a$)<>4 then exit
            n=0 : dummy=val(a$,"int",n)
            if n<>5 or dummy=0 then exit
            for i=1 to 9
                  if len(filter$(a$,str$(i,0)))<3 then break
            next i
            =false
      }
      BullsAndCows$=lambda$ (a$, b$, &ok) ->{
            Def b, c
            for i=1 to 4
            if mid$(a$,i,1)=mid$(b$,i,1) then
                  b++
            else.if instr(b$,mid$(a$,i,1))>0 then
                  c++
            end if
            next i
            ok=b=4
            =format$("bulls {0}, cows {1}", b, c)
      }
      Random$=lambda$ ->{
            def repl$, bank$, c$
            bank$="123456789"
            for i=1 to 4
                  c$=mid$(bank$,random(1,len(bank$)),1)
                  bank$=filter$(bank$, c$)
                  repl$+=c$
            next i
            =repl$
      }
      target$=Random$()
      def boolean win=false, a$
      do
            do
                  Input "Next guess ";a%
                  a$=str$(a%,0)
                  if Malformed(a$) then Print "Malformed input, try again" else exit
            always
            Print BullsAndCows$(a$, target$, &win)
            if win then exit
            Print "Bad guess! (4 unique digits, 1-9)"
      always
      Print "You guess it"
}
Game


BC := proc(n) #where n is the number of turns the user wishes to play before they quit
	local target, win, numGuesses, guess, bulls, cows, i, err;
    	target := [0, 0, 0, 0]:
    	randomize(); #This is a command that makes sure that the numbers are truly randomized each time, otherwise your first time will always give the same result.
	while member(0, target) or numelems({op(target)}) < 4 do #loop continues to generate random numbers until you get one with no repeating digits or 0s
		target := [seq(parse(i), i in convert(rand(1234..9876)(), string))]: #a list of random numbers
	end do:

	win := false:
	numGuesses := 0:
	while win = false and numGuesses < n do #loop allows the user to play until they win or until a set amount of turns have passed
		err := true;
		while err do #loop asks for values until user enters a valid number
			printf("Please enter a 4 digit integer with no repeating digits\n");
			try#catches any errors in user input
				guess := [seq(parse(i), i in readline())];
				if hastype(guess, 'Not(numeric)', 'exclude_container') then
					printf("Postive integers only! Please guess again.\n\n");
				elif numelems(guess) <> 4 then
					printf("4 digit numbers only! Please guess again.\n\n");
				elif numelems({op(guess)}) < 4 then
					printf("No repeating digits! Please guess again.\n\n");
				elif member(0, guess) then
					printf("No 0s! Please guess again.\n\n");
				else
					err := false;
				end if;
			catch:
				printf("Invalid input. Please guess again.\n\n");
			end try;
		end do:
		numGuesses := numGuesses + 1;
		printf("Guess %a: %a\n", numGuesses, guess);
		bulls := 0;
		cows := 0;
		for i to 4 do #loop checks for bulls and cows in the user's guess
			if target[i] = guess[i] then
				bulls := bulls + 1;
			elif member(target[i], guess) then
				cows := cows + 1;
			end if;
		end do;
		if bulls = 4 then
			win := true;
			printf("The number was %a.\n", target);
			printf(StringTools[FormatMessage]("You won with %1 %{1|guesses|guess|guesses}.", numGuesses));
		else
			printf(StringTools[FormatMessage]("%1 %{1|Cows|Cow|Cows}, %2 %{2|Bulls|Bull|Bulls}.\n\n", cows, bulls));
		end if;
	end do:
	if win = false and numGuesses >= n then
        printf("You lost! The number was %a.\n", target);
     end if;
	return NULL;
end proc:


'''Brazilian numbers'''

from itertools import count, islice

# isBrazil :: Int -> Bool
def isBrazil(n):
    '''True if n is a Brazilian number,
       in the sense of OEIS:A125134.
    '''
    return 7 <= n and (
        0 == n % 2 or any(
            map(monoDigit(n), range(2, n - 1))
        )
    )

# monoDigit :: Int -> Int -> Bool
def monoDigit(n):
    '''True if all the digits of n,
       in the given base, are the same.
    '''
    def go(base):
        def g(b, n):
            (q, d) = divmod(n, b)

            def p(qr):
                return d != qr[1] or 0 == qr[0]

            def f(qr):
                return divmod(qr[0], b)
            return d == until(p)(f)(
                (q, d)
            )[1]
        return g(base, n)
    return go

# -------------------------- TEST --------------------------
# main :: IO ()
def main():
    '''First 20 members each of:
        OEIS:A125134
        OEIS:A257521
        OEIS:A085104
    '''
    for kxs in ([
            (' ', count(1)),
            (' odd ', count(1, 2)),
            (' prime ', primes())
    ]):
        print(
            'First 20' + kxs[0] + 'Brazilians:\n' +
            showList(take(20)(filter(isBrazil, kxs[1]))) + '\n'
        )

# ------------------- GENERIC FUNCTIONS --------------------

# primes :: [Int]
def primes():
    ''' Non finite sequence of prime numbers.
    '''
    n = 2
    dct = {}
    while True:
        if n in dct:
            for p in dct[n]:
                dct.setdefault(n + p, []).append(p)
            del dct[n]
        else:
            yield n
            dct[n * n] = [n]
        n = 1 + n

# showList :: [a] -> String
def showList(xs):
    '''Stringification of a list.'''
    return '[' + ','.join(str(x) for x in xs) + ']'

# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
    '''The prefix of xs of length n,
       or xs itself if n > length xs.
    '''
    def go(xs):
        return (
            xs[0:n]
            if isinstance(xs, (list, tuple))
            else list(islice(xs, n))
        )
    return go

# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
    '''The result of repeatedly applying f until p holds.
       The initial seed value is x.
    '''
    def go(f):
        def g(x):
            v = x
            while not p(v):
                v = f(v)
            return v
        return g
    return go

# MAIN ---
if __name__ == '__main__':
    main()


p:=System.popen(0'|convert "fractalTree.jpg" ppm:-|,"r");
img:=PPM.readPPM(p); p.close();


const OPEN_CHAR: char = '{';
const CLOSE_CHAR: char = '}';
const SEPARATOR: char = ',';
const ESCAPE: char = '\\';

#[derive(Debug, PartialEq, Clone)]
enum Token {
    Open,
    Close,
    Separator,
    Payload(String),
    Branches(Branches),
}

impl From<char> for Token {
    fn from(ch: char) -> Token {
        match ch {
            OPEN_CHAR => Token::Open,
            CLOSE_CHAR => Token::Close,
            SEPARATOR => Token::Separator,
            _ => panic!("Non tokenizable char!"),
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
struct Branches {
    tokens: Vec<Vec<Token>>,
}

impl Branches {
    fn new() -> Branches {
        Branches{
            tokens: Vec::new(),
        }
    }

    fn add_branch(&mut self, branch: Vec<Token>) {
        self.tokens.push(branch);
    }

    fn from(tokens: &Vec<Token>) -> Branches {
        let mut branches = Branches::new();
        let mut tail = tokens.clone();
        while let Some(pos) = tail.iter().position(|token| { *token == Token::Separator }) {
            let mut rest = tail.split_off(pos);
            branches.add_branch(tail);
            rest.remove(0);
            tail = rest;
        }
        branches.add_branch(tail);
        branches
    }
}

impl From<Branches> for Token {
    fn from(branches: Branches) -> Token {
        Token::Branches(branches)
    }
}

impl From<Vec<Token>> for Branches {
    fn from(tokens: Vec<Token>) -> Branches {
        Branches::from(&tokens)
    }
}

impl From<Token> for String {
    fn from(token: Token) -> String {
        match token {
            Token::Branches(_) => panic!("Cannot convert to String!"),
            Token::Payload(text) => text,
            Token::Open => OPEN_CHAR.to_string(),
            Token::Close => CLOSE_CHAR.to_string(),
            Token::Separator => SEPARATOR.to_string(),
        }
    }
}

impl From<Branches> for Vec<String> {
    fn from(branches: Branches) -> Vec<String> {
        let Branches{ tokens: token_lines } = branches;
        let mut vec: Vec<String> = Vec::new();
        let braces = { if token_lines.len() == 1 { true } else { false } };
        for tokens in token_lines {
            let mut vec_string = output(tokens);
            vec.append(&mut vec_string);
        }
        if braces {
            vec.iter()
                .map(|line| {
                    format!("{}{}{}", OPEN_CHAR, line, CLOSE_CHAR)
                }).
                collect::<Vec<String>>()
        } else {
            vec
        }
    }
}

impl From<Token> for Vec<String> {
    fn from(token: Token) -> Vec<String> {
        match token {
            Token::Branches(branches) => {
                branches.into()
            },
            _ => {
                let frag: String = token.into();
                vec![frag]
            },
        }
    }
}

fn tokenize(string: &str) -> Vec<Token> {
    let mut tokens: Vec<Token> = Vec::new();
    let mut chars = string.chars();
    let mut payload = String::new();
    while let Some(ch) = chars.next() {
        match ch {
            OPEN_CHAR | SEPARATOR | CLOSE_CHAR => {
                if payload.len() > 0 {
                    tokens.push(Token::Payload(payload));
                }
                payload = String::new();
                if ch == CLOSE_CHAR {
                    let pos = tokens.iter().rposition(|token| *token == Token::Open);
                    if let Some(pos) = pos {
                        let branches: Branches = {
                            let mut to_branches = tokens.split_off(pos);
                            to_branches.remove(0);
                            to_branches
                        }.into();
                        tokens.push(branches.into());
                    } else {
                        tokens.push(ch.into());
                    }
                } else {
                    tokens.push(ch.into());
                }
            },
            ESCAPE => {
                payload.push(ch);
                if let Some(next_char) = chars.next() {
                    payload.push(next_char);
                }
            },
            _ => payload.push(ch),
        }
    }
    let payload = payload.trim_end();
    if payload.len() > 0 {
        tokens.push(Token::Payload(payload.into()));
    }
    tokens
}

fn output(tokens: Vec<Token>) -> Vec<String> {
    let mut output: Vec<String> = vec![String::new()];
    for token in tokens {
        let mut aux: Vec<String> = Vec::new();
        let strings: Vec<String> = token.into();
        for root in &output {
            for string in &strings {
                aux.push({format!("{}{}", root, string)});
            }
        }
        output = aux;
    }
    output
}

fn main() {
    let mut input: String = String::new();
    std::io::stdin().read_line(&mut input).unwrap();

    let tokens: Vec<Token> = tokenize(&input);
    // println!("Tokens:\n{:#?}", tokens);

    let output = output(tokens);
    for line in &output {
        println!("{}", line);
    }
}


import collection.mutable.ListBuffer
case class State(isChild: Boolean, alts: ListBuffer[String], rem: List[Char])
def expand(s: String): Seq[String] = {
  def parseGroup(s: State): State = s.rem match {
    case Nil =>  s.copy(alts = ListBuffer("{" + s.alts.mkString(",")))
    case ('{' | ',')::sp =>
      val newS = State(true, ListBuffer(""), rem = sp)
      val elem = parseElem(newS)
      elem.rem match {
        case Nil =>     elem.copy(alts = elem.alts.map(a => "{" + s.alts.map(_ + ",").mkString("") + a))
        case elemrem => parseGroup(s.copy(alts = (s.alts ++= elem.alts), rem = elem.rem))
      }
    case '}'::sp =>
      if (s.alts.isEmpty)          s.copy(alts = ListBuffer("{}"), rem = sp)
      else if(s.alts.length == 1)  s.copy(alts = ListBuffer("{"+s.alts.head + "}"), rem = sp)
      else                         s.copy(rem = sp)
    case _ => throw new Exception("parseGroup should be called only with delimitors")
  }
  def parseElem(s: State): State = s.rem match {
    case Nil =>  s
    case '{'::sp =>
      val ys = parseGroup(State(true, ListBuffer(), s.rem))
      val newAlts = for { x <- s.alts; y <- ys.alts} yield x + y
      parseElem(s.copy(alts = newAlts, rem = ys.rem))
    case (',' | '}')::_ if s.isChild => s
    case '\\'::c::sp => parseElem(s.copy(alts = s.alts.map(_ + '\\' + c), rem = sp))
    case c::sp =>       parseElem(s.copy(alts = s.alts.map(_ + c), rem = sp))
  }
  parseElem(State(false, ListBuffer(""), s.toList)).alts
}


[email protected][If[[email protected]@#==4,#,Table[Random[Integer,{1,9}],{4}]]&,{}]
codes=ToCharacterCode[StringJoin[ToString/@digits]];
Module[{r,bulls,cows},
	While[True,
	r=InputString[];
	If[r===$Canceled,Break[],
		With[{[email protected]},
		If[userCodes===codes,Print[r<>": You got it!"];Break[],
			If[[email protected][email protected],
				bulls=Count[userCodes-codes,0];[email protected][codes,userCodes]-bulls;
				Print[r<>": "<>ToString[bulls]<>"bull(s), "<>[email protected]<>"cow(s)."],
				Print["Guess four digits."]]]]]]]


function BullsAndCows
% Plays the game Bulls and Cows as the "game master"

    % Create a secret number
    nDigits = 4;
    lowVal = 1;
    highVal = 9;
    digitList = lowVal:highVal;
    secret = zeros(1, 4);
    for k = 1:nDigits
        idx = randi(length(digitList));
        secret(k) = digitList(idx);
        digitList(idx) = [];
    end

    % Give game information
    fprintf('Welcome to Bulls and Cows!\n')
    fprintf('Try to guess the %d-digit number (no repeated digits).\n', nDigits)
    fprintf('Digits are between %d and %d (inclusive).\n', lowVal, highVal)
    fprintf('Score: 1 Bull per correct digit in correct place.\n')
    fprintf('       1 Cow per correct digit in incorrect place.\n')
    fprintf('The number has been chosen. Now it''s your moooooove!\n')
    gs = input('Guess: ', 's');

    % Loop until user guesses right or quits (no guess)
    nGuesses = 1;
    while gs
        gn = str2double(gs);
        if isnan(gn) || length(gn) > 1  % Not a scalar
            fprintf('Malformed guess. Keep to valid scalars.\n')
            gs = input('Try again: ', 's');
        else
            g = sprintf('%d', gn) - '0';
            if length(g) ~= nDigits || any(g < lowVal) || any(g > highVal) || ...
                    length(unique(g)) ~= nDigits    % Invalid number for game
                fprintf('Malformed guess. Remember:\n')
                fprintf('  %d digits\n', nDigits)
                fprintf('  Between %d and %d inclusive\n', lowVal, highVal)
                fprintf('  No repeated digits\n')
                gs = input('Try again: ', 's');
            else
                score = CountBullsCows(g, secret);
                if score(1) == nDigits
                    fprintf('You win! Bully for you! Only %d guesses.\n', nGuesses)
                    gs = '';
                else
                    fprintf('Score: %d Bulls, %d Cows\n', score)
                    gs = input('Guess: ', 's');
                end
            end
        end
        nGuesses = nGuesses+1;  % Counts malformed guesses
    end
end

function score = CountBullsCows(guess, correct)
% Checks the guessed array of digits against the correct array to find the score
% Assumes arrays of same length and valid numbers
    bulls = guess == correct;
    cows = ismember(guess(~bulls), correct);
    score = [sum(bulls) sum(cows)];
end


#lang racket

(require math/number-theory)

(define (repeat-digit? n base d-must-be-1?)
  (call-with-values
   (λ () (quotient/remainder n base))
   (λ (q d) (and (or (not d-must-be-1?) (= d 1))
                 (let loop ((n q))
                   (if (zero? n)
                       d
                       (call-with-values
                        (λ () (quotient/remainder n base))
                        (λ (q r) (and (= d r) (loop q))))))))))

(define (brazilian? n (for-prime? #f))
  (for/first ((b (in-range 2 (sub1 n))) #:when (repeat-digit? n b for-prime?)) b))

(define (prime-brazilian? n)
  (and (prime? n) (brazilian? n #t)))

(module+ main
  (displayln "First 20 Brazilian numbers:")
  (stream->list (stream-take (stream-filter brazilian? (in-naturals)) 20))
  (displayln "First 20 odd Brazilian numbers:")
  (stream->list (stream-take (stream-filter brazilian? (stream-filter odd? (in-naturals))) 20))
  (displayln "First 20 prime Brazilian numbers:")
  (stream->list (stream-take (stream-filter prime-brazilian? (stream-filter odd? (in-naturals))) 20)))


multi is-Brazilian (Int $n where $n %% 2 && $n > 6) { True }

multi is-Brazilian (Int $n) {
    LOOP: loop (my int $base = 2; $base < $n - 1; ++$base) {
        my $digit;
        for $n.polymod( $base xx * ) {
            $digit //= $_;
            next LOOP if $digit != $_;
        }
        return True
    }
    False
}

my $upto = 20;

put "First $upto Brazilian numbers:\n", (^Inf).hyper.grep( &is-Brazilian )[^$upto];

put "\nFirst $upto odd Brazilian numbers:\n", (^Inf).hyper.map( * * 2 + 1 ).grep( &is-Brazilian )[^$upto];

put "\nFirst $upto prime Brazilian numbers:\n", (^Inf).hyper(:8degree).grep( { .is-prime && .&is-Brazilian } )[^$upto];


T Colour
   Byte r, g, b

   F (r, g, b)
      .r = r
      .g = g
      .b = b

   F ==(other)
      R .r == other.r & .g == other.g & .b == other.b

V black = Colour(0, 0, 0)
V white = Colour(255, 255, 255)

T Bitmap
   Int width, height
   Colour background
   [[Colour]] map

   F (width = 40, height = 40, background = white)
      assert(width > 0 & height > 0)
      .width = width
      .height = height
      .background = background
      .map = (0 .< height).map(h -> (0 .< @width).map(w -> @@background))

   F fillrect(x, y, width, height, colour = black)
      assert(x >= 0 & y >= 0 & width > 0 & height > 0)
      L(h) 0 .< height
         L(w) 0 .< width
            .map[y + h][x + w] = colour

   F set(x, y, colour = black)
      .map[y][x] = colour

   F get(x, y)
      R .map[y][x]

   F writeppmp3()
      V magic = "P3\n"
      V comment = "# generated from Bitmap.writeppmp3\n"
      V s = magic‘’comment‘’("#. #.\n#.\n".format(.width, .height, 255))
      L(h) (.height - 1 .< -1).step(-1)
         L(w) 0 .< .width
            V (r, g, b) = .get(w, h)
            s ‘’= ‘   #3 #3 #3’.format(r, g, b)
         s ‘’= "\n"
      R s

   F writeppmp6()
      V magic = "P6\n"
      V comment = "# generated from Bitmap.writeppmp6\n"
      [Byte] b
      b [+]= magic.encode()
      b [+]= comment.encode()
      b [+]= ("#. #.\n#.\n".format(.width, .height, 255)).encode()
      L(h) (.height - 1 .< -1).step(-1)
         L(w) 0 .< .width
            V (r, g, bl) = .get(w, h)
            b [+]= [r, g, bl]
      R b

V bitmap = Bitmap(4, 4, black)
bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))
print(bitmap.writeppmp3())

File(‘tmp.ppm’, ‘w’).write_bytes(bitmap.writeppmp6())


(define (parse-brackets str)
  ;; We parse the bracketed strings using an accumulator and a stack
  ;;
  ;; lst is the stream of tokens
  ;; acc is the accumulated list of "bits" in this branch
  ;; stk is a list of partially completed accumulators
  ;;
  (let go ((lst (string->list str))
           (acc '())
           (stk '()))
    (cond ((null? lst)
           (unless (null? stk)
             (error "parse-brackets" 'non-empty-stack))
           (comma-sep acc))
          ((eq? (car lst) #\{)
           (go (cdr lst)
               '()
               (cons acc stk)))
          ((eq? (car lst) #\})
           (when (null? stk)
             (error "parse-brackets" 'empty-stack))
           (go (cdr lst)
               (cons (comma-sep acc) (car stk))
               (cdr stk)))
          (else
           (go (cdr lst)
               (cons (car lst) acc)
               stk)))))

(define (comma-sep lst)
  ;; This function is applied to the accumulator, it does three things:
  ;; - it reverses the list
  ;; - joins characters into short strings
  ;; - splits the strings based on commas
  ;;
  (let go ((lst lst)
           (acc '())
           (rst '()))
    (if (null? lst)
        (cons (list->string acc) rst)
        (cond ((eq? #\, (car lst))
               (go (cdr lst)
                   '()
                   (cons (list->string acc) rst)))
              ((char? (car lst))
               (go (cdr lst)
                   (cons (car lst) acc)
                   rst))
              (else
               (go (cdr lst)
                   '()
                   (cons (car lst)
                         (cons (list->string acc)
                               rst))))))))

;; We use the list monad for the nondeterminism needed to expand out every possible bracket option

(define (concatenate lists)
  (apply append lists))

(define (return x)
  (list x))
(define (>>= l f)
  (concatenate (map f l)))

(define (sequence lsts)
  (if (null? lsts)
      (return '())
      (>>= (car lsts)
           (lambda (option)
             (>>= (sequence (cdr lsts))
                  (lambda (tail)
                    (return (cons option tail))))))))

(define (expand-inner tree)
  (if (string? tree)
      (return tree)
      (>>= tree
           (lambda (option)
             (expand-inner option)))))

(define (expand tree)
  (define (string-append* lst) (apply string-append lst))
  (map string-append* (sequence (map expand-inner tree))))

(define (bracket-expand str)
  (expand (parse-brackets str)))

(bracket-expand "It{{em,alic}iz,erat}e{d,}")
;; '("Ited" "Ite" "Itemed" "Iteme" "Italiced" "Italice" "Itized" "Itize" "Iterated" "Iterate")


numCount = 4 -- number of digits to use

digits = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
num = ""
while num.count < numCount and digits.count > 0 do
(
	local r = random 1 digits.count
	append num (digits[r] as string)
	deleteitem digits r
)
digits = undefined
numGuesses = 0
inf = "Rules: \n1. Choose only % unique digits in any combination"+\
		" (0 can't be used).\n2. Only positive integers are allowed."+\
		"\n3. For each digit that is in it's place, you get a bull,\n"+\
		"\tand for each digit that is not in it's place, you get a cow."+\
		"\n4. The game is won when your number matches the number I chose."+\
		"\n\nPress [esc] to quit the game.\n\n"
clearlistener()
format inf num.count
while not keyboard.escpressed do
(
	local userVal = getkbvalue prompt:"\nEnter your number: "
	if (userVal as string) == num do
	(
		format "\nCorrect! The number is %. It took you % moves.\n" num numGuesses
		exit with OK
	)
	local bulls = 0
	local cows = 0
	local badInput = false
	case of
	(
		(classof userVal != integer):
			(
			format "\nThe number must be a positive integer.\n"
			badInput = true
			)
		((userVal as string).count != num.count):
			(
			format "\nThe number must have % digits.\n" num.count
			badInput = true
			)
		((makeuniquearray (for i in 1 to (userVal as string).count \
			collect (userVal as string)[i])).count != (userVal as string).count):
			(
				format "\nThe number can only have unique digits.\n"
				badInput = true
			)
	)
	if not badInput do
	(
		userVal = userVal as string
		i = 1
		while i <= userVal.count do
		(
			for j = 1 to num.count do
			(
				if userVal[i] == num[j] do
				(
					if i == j then bulls += 1 else cows += 1
				)
			)
			i += 1
		)
		numGuesses += 1
		format "\nBulls: % Cows: %\n" bulls cows
	)
)


secret = range(1,9)
secret.shuffle
secret = secret[:4].join("")

while true
    guess = input("Your guess? ").split("")
    if guess.len != 4 then
        print "Please enter 4 numbers, with no spaces."
        continue
    end if
    bulls = 0
    cows = 0
    for i in guess.indexes
        if secret[i] == guess[i] then
            bulls = bulls + 1
        else if secret.indexOf(guess[i]) != null then
            cows = cows + 1
        end if
    end for
    if bulls == 4 then
        print "You got it!  Great job!"
        break
    end if
    print "You score " + bulls + " bull" + "s"*(bulls!=1) +
    " and " + cows + " cow" + "s"*(cows!=1) + "."
end while


/*REXX pgm finds:  1st N Brazilian #s;  odd Brazilian #s;  prime Brazilian #s;  ZZZth #.*/
parse arg  t.1  t.2  t.3  t.4  .                 /*obtain optional arguments from the CL*/
if t.4=='' | t.4==","  then t.4= 0               /*special test case of Nth Brazilian #.*/
hdr.1= 'first';   hdr.2= "first odd";   hdr.3= 'first prime';   hdr.4=   /*four headers.*/
                                        #p= 0    /*#P:   the number of primes  (so far).*/
    do c=1  for 4                                /*process each of the four cases.      */
    if t.c=='' | t.c==","  then t.c= 20          /*check if a target is null or a comma.*/
    step= 1 + (c==2)                             /*STEP is set to unity or two (for ODD)*/
    if t.c==0  then iterate                      /*check to see if this case target ≡ 0.*/
    $=;                       #= 0               /*initialize list to null; counter to 0*/
       do j=1  by step  until #>= t.c            /*search integers for Brazilian # type.*/
       prime= 0                                  /*signify if  J  may not be prime.     */
       if c==3  then do                          /*is this a  "case 3"  calculation?    */
                     if \isPrime(j) then iterate /*(case 3)  Not a prime?  Then skip it.*/
                     prime= 1                    /*signify if  J  is definately a prime.*/
                     end                         /* [↓] J≡prime will be used for speedup*/
       if \isBraz(j, prime)  then iterate        /*Not  Brazilian number?   "    "    " */
       #= # + 1                                  /*bump the counter of Brazilian numbers*/
       if c\==4  then $= $  j                    /*for most cases, append J to ($) list.*/
       end   /*j*/                               /* [↑] cases 1──►3, $ has leading blank*/
    say                                          /* [↓]  use a special header for cases.*/
    if c==4  then do;  $= j;  t.c= th(t.c);  end /*for Nth Brazilian number, just use J.*/
    say center(' 'hdr.c" "    t.c      " Brazilian number"left('s',  c\==4)" ",  79,  '═')
    say strip($)                                 /*display a case result to the terminal*/
    end      /*c*/                               /* [↑] cases 1──►3 have a leading blank*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isBraz:  procedure; parse arg x,p;  if x<7      then return 0  /*Is # < seven?  Nope.   */
                                    if x//2==0  then return 1  /*Is # even?     Yup.   _*/
         if p  then mx= iSqrt(x)                               /*X prime? Use integer √X*/
               else mx= x%3 -1                                 /*X  not known if prime. */
                              do b=2  for mx                   /*scan for base 2 ──► max*/
                              if sameDig(x, b)  then return 1  /*it's a Brazilian number*/
                              end   /*b*/;           return 0  /*not  "     "        "  */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure expose @. !. #p; parse arg x '' -1 _ /*get 1st arg & last decimal dig*/
         if #p==0 then do;  !.=0;  y= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67
                         do i=1  for words(y);  #p= #p+1; z=word(y,i); @.#p= z; !.z=1; end
                       end                              /*#P:  is the number of primes. */
         if !.x      then return 1;   if x<61  then return 0;  if x//2==0  then return 0
         if x//3==0  then return 0;   if _==5  then return 0;  if x//7==0  then return 0
            do j=5  until @.j**2>x;                 if x//@.j     ==0  then return 0
                                                    if x//(@.j+2) ==0  then return 0
            end   /*j*/;   #p= #p + 1;   @.#p= x;   !.x= 1;    return 1  /*it's a prime.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt:   procedure; parse arg x;     q= 1;     r= 0;        do while q<=x;   q= q*4;   end
          do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q;end;end; return r
/*──────────────────────────────────────────────────────────────────────────────────────*/
sameDig: procedure; parse arg x, b;           f= x // b        /* //  ◄── the remainder.*/
                                              x= x  % b        /*  %  ◄── is integer  ÷ */
                    do while x>0;  if x//b \==f  then return 0
                    x= x % b
                    end   /*while*/;      return 1             /*it has all the same dig*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
th: parse arg th; return th || word('th st nd rd', 1+(th//10)*(th//100%10\==1)*(th//10<4))


load "stdlib.ring"

decList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
brazil = []
brazilOdd = []
brazilPrime = []
num1 = 0
num2 = 0
num3 = 0
limit = 20

see "working..." + nl
for n = 1 to 2802
    for m = 2 to 16
        flag = 1
        basem = decimaltobase(n,m)
        for p = 1 to len(basem)-1
            if basem[p] != basem[p+1]
               flag = 0
               exit
            ok
        next
        if flag = 1 and m < n - 1
           add(brazil,n)
           delBrazil(brazil)
        ok
        if flag = 1 and m < n - 1 and n % 2 = 1
           add(brazilOdd,n)
           delBrazil(brazilOdd)
        ok
        if flag = 1 and m < n - 1 and isprime(n)
           add(brazilPrime,n)
           delBrazil(brazilPrime)
        ok
    next
next

see "2 <= base <= 16" + nl
see "first 20 brazilian numbers:" + nl
showarray(brazil)
see "first 20 odd brazilian numbers:" + nl
showarray(brazilOdd)
see "first 11 brazilian prime numbers:" + nl
showarray(brazilPrime)

see "done..." + nl

func delBrazil(brazil)
     for z = len(brazil) to 2 step -1
         if brazil[z] = brazil[z-1]
            del(brazil,z)
         ok
     next

func decimaltobase(nr,base)
     binList = []
     binary = 0
     remainder = 1
     while(nr != 0)
          remainder = nr % base
          ind = find(decList,remainder)
          rem = baseList[ind]
          add(binList,rem)
          nr = floor(nr/base)
     end
     binlist = reverse(binList)
     binList = list2str(binList)
     binList = substr(binList,nl,"")
     return binList

func showArray(array)
     txt = ""
     if len(array) < limit
        limit = len(array)
     ok
     for n = 1 to limit
         txt = txt + array[n] + ","
     next
     txt = left(txt,len(txt)-1)
     see txt + nl


def sameDigits(n,b)
    f = n % b
    while (n /= b) > 0 do
        if n % b != f then
            return false
        end
    end
    return true
end

def isBrazilian(n)
    if n < 7 then
        return false
    end
    if n % 2 == 0 then
        return true
    end
    for b in 2 .. n - 2 do
        if sameDigits(n, b) then
            return true
        end
    end
    return false
end

def isPrime(n)
    if n < 2 then
        return false
    end
    if n % 2 == 0 then
        return n == 2
    end
    if n % 3 == 0 then
        return n == 3
    end
    d = 5
    while d * d <= n do
        if n % d == 0 then
            return false
        end
        d = d + 2

        if n % d == 0 then
            return false
        end
        d = d + 4
    end
    return true
end

def main
    for kind in ["", "odd ", "prime "] do
        quiet = false
        bigLim = 99999
        limit = 20
        puts "First %d %sBrazilian numbers:" % [limit, kind]
        c = 0
        n = 7
        while c < bigLim do
            if isBrazilian(n) then
                if not quiet then
                    print "%d " % [n]
                end
                c = c + 1
                if c == limit then
                    puts
                    puts
                    quiet = true
                end
            end
            if quiet and kind != "" then
                next
            end
            if kind == "" then
                n = n + 1
            elsif kind == "odd " then
                n = n + 2
            elsif kind == "prime " then
                loop do
                    n = n + 2
                    if isPrime(n) then
                        break
                    end
                end
            else
                raise "Unexpected"
            end
        end
        if kind == "" then
            puts "The %dth Brazillian number is: %d" % [bigLim + 1, n]
            puts
        end
    end
end

main()


INCLUDE "H6:RGBIMAGE.ACT" ;from task Bitmap

PROC SaveHeader(RgbImage POINTER img
  CHAR ARRAY format BYTE dev)

  PrintDE(dev,format)
  PrintBD(dev,img.w)
  PutD(dev,32)
  PrintBDE(dev,img.h)
  PrintBDE(dev,255)
RETURN

PROC SavePPM3(RgbImage POINTER img CHAR ARRAY path)
  BYTE dev=[1],x,y
  RGB c

  Close(dev)
  Open(dev,path,8)
  SaveHeader(img,"P3",dev)
  FOR y=0 TO img.h-1
  DO
    FOR x=0 TO img.w-1
    DO
      GetRgbPixel(img,x,y,c)
      PrintBD(dev,c.r) PutD(dev,32)
      PrintBD(dev,c.g) PutD(dev,32)
      PrintBD(dev,c.b)
      IF x=img.w-1 THEN
        PutDE(dev)
      ELSE
        PutD(dev,32)
      FI
    OD
  OD
  Close(dev)
RETURN

PROC SavePPM6(RgbImage POINTER img CHAR ARRAY path)
  BYTE dev=[1],x,y
  RGB c

  Close(dev)
  Open(dev,path,8)
  SaveHeader(img,"P6",dev)
  FOR y=0 TO img.h-1
  DO
    FOR x=0 TO img.w-1
    DO
      GetRgbPixel(img,x,y,c)
      PutD(dev,c.r)
      PutD(dev,c.g)
      PutD(dev,c.b)
    OD
  OD
  Close(dev)
RETURN

PROC Load(CHAR ARRAY path)
  CHAR ARRAY line(255)
  BYTE dev=[1]

  Close(dev)
  Open(dev,path,4)
  WHILE Eof(dev)=0
  DO
    InputSD(dev,line)
    PrintE(line)
  OD
  Close(dev)
RETURN

PROC Main()
  BYTE ARRAY rgbdata=[
      0   0   0    0   0 255    0 255   0
    255   0   0    0 255 255  255   0 255
    255 255   0  255 255 255   31  63 127
     63  31 127  127  31  63  127  63  31]
  BYTE width=[3],height=[4]
  RgbImage img
  CHAR ARRAY path3="D:PPM3.PPM"
  CHAR ARRAY path6="D:PPM6.PPM"

  Put(125) PutE() ;clear the screen
  InitRgbImage(img,width,height,rgbdata)

  PrintF("Saving %S...%E%E",path3)
  SavePPM3(img,path3)
  PrintF("Saving %S...%E%E",path6)
  SavePPM6(img,path6)
  PrintF("Loading %S...%E%E",path3)
  Load(path3)
RETURN


with Ada.Characters.Latin_1;
with Ada.Streams.Stream_IO;  use Ada.Streams.Stream_IO;

procedure Put_PPM (File : File_Type; Picture : Image) is
   use Ada.Characters.Latin_1;
   Size   : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1));
   Buffer : String (1..Picture'Length (2) * 3);
   Color  : Pixel;
   Index  : Positive;
begin
   String'Write (Stream (File), "P6" & LF);
   String'Write (Stream (File), Size (2..Size'Last) & LF);
   String'Write (Stream (File), "255" & LF);
   for I in Picture'Range (1) loop
      Index := Buffer'First;
      for J in Picture'Range (2) loop
         Color := Picture (I, J);
         Buffer (Index)     := Character'Val (Color.R);
         Buffer (Index + 1) := Character'Val (Color.G);
         Buffer (Index + 2) := Character'Val (Color.B);
         Index := Index + 3;
      end loop;
      String'Write (Stream (File), Buffer);
   end loop;
   Character'Write (Stream (File), LF);
end Put_PPM;


$ include "seed7_05.s7i";

const proc: expandBraces (in string: stri) is func
  local
    var boolean: escaped is FALSE;
    var integer: depth is 0;
    var array integer: bracePoints is 0 times 0;
    var array integer: bracesToParse is 0 times 0;
    var string: prefix is "";
    var string: suffix is "";
    var string: option is "";
    var integer: idx is 0;
  begin
    for key idx range stri do
      case stri[idx] of
        when {'\\'}:
          escaped := not escaped;
        when {'{'}:
          incr(depth);
          if not escaped and depth = 1 then
            bracePoints := [] (idx);
          end if;
        when {','}:
          if not escaped and depth = 1 then
            bracePoints &:= idx;
          end if;
        when {'}'}:
          if not escaped and depth = 1 and length(bracePoints) >= 2 then
            bracesToParse := bracePoints & [] (idx);
          end if;
          decr(depth);
      end case;
      if stri[idx] <> '\\' then
        escaped := FALSE;
      end if;
    end for;
    if length(bracesToParse) <> 0 then
      prefix := stri[.. pred(bracesToParse[1])];
      suffix := stri[succ(bracesToParse[length(bracesToParse)]) ..];
      for idx range 1 to pred(length(bracesToParse)) do
        option := stri[succ(bracesToParse[idx]) .. pred(bracesToParse[succ(idx)])];
        expandBraces(prefix & option & suffix);
      end for;
    else
      writeln(stri);
    end if;
  end func;

const proc: main is func
  local
    var string: stri is "";
  begin
    for stri range [] ("It{{em,alic}iz,erat}e{d,}, please.",
                       "~/{Downloads,Pictures}/*.{jpg,gif,png}",
                       "{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
                       "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}") do
      writeln;
      expandBraces(stri);
    end for;
  end func;


func brace_expand (input) {
    var current = ['']
    var stack = [[current]]

    loop {
        var t = input.match(
            /\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx
        )[0] \\ break

        if (t == '{') {
            stack << [current = ['']]
        }
        elsif ((t == ',') && (stack.len > 1)) {
            stack[-1] << (current = [''])
        }
        elsif ((t == '}') && (stack.len > 1)) {
            var group = stack.pop
            current   = stack[-1][-1]

            # handle the case of brace pairs without commas:
            group[0][] = group[0].map{ '{'+_+'}' }... if (group.len == 1)

            current[] = current.map { |c|
                group.map { .map { c + _ }... }...
            }...
        }
        else {
            current[] = current.map { _ + t }...
        }
    }

    # handle the case of missing closing braces:
    while (stack.len > 1) {

        var right = stack[-1].pop
        var sep = ','

        if (stack[-1].is_empty) {
            sep = '{'
            stack.pop
        }

        current = stack[-1][-1]
        current[] = current.map  { |c|
            right.map { c + sep + _ }...
        }...
    }

    return current
}

DATA.each { |line|
    say line
    brace_expand(line).each { "\t#{_}".say }
    say ''
}

__DATA__
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}


BullCow	New bull,cow,guess,guessed,ii,number,pos,x
	Set number="",x=1234567890
	For ii=1:1:4 Do
	. Set pos=$Random($Length(x))+1
	. Set number=number_$Extract(x,pos)
	. Set $Extract(x,pos)=""
	. Quit
	Write !,"The computer has selected a number that consists"
	Write !,"of four different digits."
	Write !!,"As you are guessing the number, ""bulls"" and ""cows"""
	Write !,"will be awarded: a ""bull"" for each digit that is"
	Write !,"placed in the correct position, and a ""cow"" for each"
	Write !,"digit that occurs in the number, but in a different place.",!
	Write !,"For a guess, enter 4 digits."
	Write !,"Any other input is interpreted as ""I give up"".",!
	Set guessed=0 For  Do  Quit:guessed
	. Write !,"Your guess: " Read guess If guess'?4n Set guessed=-1 Quit
	. Set (bull,cow)=0,x=guess
	. For ii=4:-1:1 If $Extract(x,ii)=$Extract(number,ii) Do
	. . Set bull=bull+1,$Extract(x,ii)=""
	. . Quit
	. For ii=1:1:$Length(x) Set:number[$Extract(x,ii) cow=cow+1
	. Write !,"You guessed ",guess,". That earns you "
	. If 'bull,'cow Write "neither bulls nor cows..." Quit
	. If bull Write bull," bull" Write:bull>1 "s"
	. If cow Write:bull " and " Write cow," cow" Write:cow>1 "s"
	. Write "."
	. If bull=4 Set guessed=1 Write !,"That's a perfect score."
	. Quit
	If guessed<0 Write !!,"The number was ",number,".",!
	Quit
Do BullCow

The computer has selected a number that consists
of four different digits.

As you are guessing the number, "bulls" and "cows"
will be awarded: a "bull" for each digit that is
placed in the correct position, and a "cow" for each
digit that occurs in the number, but in a different place.

For a guess, enter 4 digits.
Any other input is interpreted as "I give up".

Your guess: 1234
You guessed 1234. That earns you 1 cow.
Your guess: 5678
You guessed 5678. That earns you 1 cow.
Your guess: 9815
You guessed 9815. That earns you 1 cow.
Your guess: 9824
You guessed 9824. That earns you 2 cows.
Your guess: 9037
You guessed 9037. That earns you 1 bull and 2 cows.
Your guess: 9048
You guessed 2789. That earns you 1 bull and 2 cows.
Your guess: 2079
You guessed 2079. That earns you 1 bull and 3 cows.
Your guess: 2709
You guessed 2709. That earns you 2 bulls and 2 cows.
Your guess: 0729
You guessed 0729. That earns you 4 cows.
Your guess: 2907
You guessed 2907. That earns you 4 bulls.
That's a perfect score.


import Nanoquery.Util; random = new(Random)

// a function to verify the user's input
def verify_digits(input)
	global size
	seen = ""

	if len(input) != size
		return false
	else
		for char in input
			if not char in "0123456789"
				return false
			else if char in seen
				return false
			end

			seen += char
		end
	end

	return true
end

size = 4
chosen = ""
while len(chosen) < size
	digit = random.getInt(8) + 1

	if not str(digit) in chosen
		chosen += str(digit)
	end
end

println "I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order."
println "You need to input a 4 digit, unique digit number as a guess at what I have chosen."

guesses = 1
won = false
while !won
	print "\nNext guess [" + str(guesses) + "]: "
	guess = input()

	if !verify_digits(guess)
		println "Problem, try again. You need to enter 4 unique digits from 1 to 9"
	else
		if guess = chosen
			won = true
		else
			bulls = 0
			cows = 0
			for i in range(0, size - 1)
				if guess[i] = chosen[i]
					bulls += 1
				else if guess[i] in chosen
					cows += 1
				end
			end

			println format("  %d Bulls\n  %d Cows", bulls, cows)
			guesses += 1
		end
	end
end

println "\nCongratulations you guess correctly in " + guesses + " attempts"


fn same_digits(x: u64, base: u64) -> bool {
    let f = x % base;
    let mut n = x;
    while n > 0 {
        if n % base != f {
            return false;
        }
        n /= base;
    }

    true
}
fn is_brazilian(x: u64) -> bool {
    if x < 7 {
        return false;
    };
    if x % 2 == 0 {
        return true;
    };

    for base in 2..(x - 1) {
        if same_digits(x, base) {
            return true;
        }
    }
    false
}

fn main() {
    let mut counter = 0;
    let limit = 20;
    let big_limit = 100_000;
    let mut big_result: u64 = 0;
    let mut br: Vec<u64> = Vec::new();
    let mut o: Vec<u64> = Vec::new();
    let mut p: Vec<u64> = Vec::new();

    for x in 7.. {
        if is_brazilian(x) {
            counter += 1;
            if br.len() < limit {
                br.push(x);
            }
            if o.len() < limit && x % 2 == 1 {
                o.push(x);
            }
            if p.len() < limit && primes::is_prime(x) {
                p.push(x);
            }
            if counter == big_limit {
                big_result = x;
                break;
            }
        }
    }
    println!("First {} Brazilian numbers:", limit);
    println!("{:?}", br);
    println!("\nFirst {} odd Brazilian numbers:", limit);
    println!("{:?}", o);
    println!("\nFirst {} prime Brazilian numbers:", limit);
    println!("{:?}", p);

    println!("\nThe {}th Brazilian number: {}", big_limit, big_result);
}


CLASS ARRAYLISTS;
BEGIN

   CLASS ITEM;;

   CLASS ITEMARRAY(N); INTEGER N;
   BEGIN
      REF(ITEM) ARRAY DATA(1:N);
   !  OUTTEXT("NEW ITEMARRAY WITH ");!OUTINT(N, 0);!OUTTEXT(" ELEMENTS");
   !  OUTIMAGE;
   END;

   CLASS ARRAYLIST;
   BEGIN

      PROCEDURE EXPAND(N); INTEGER N;
      BEGIN
         INTEGER I;
         REF(ITEMARRAY) TEMP;
      !  OUTTEXT("EXPAND TO CAPACITY ");!OUTINT(N, 0);!OUTIMAGE;
         TEMP :- NEW ITEMARRAY(N);
         FOR I := 1 STEP 1 UNTIL SIZE DO
            TEMP.DATA(I) :- ITEMS.DATA(I);
         ITEMS :- TEMP;
      END;

      PROCEDURE ADD(T); REF(ITEM) T;
      BEGIN
         IF SIZE + 1 > CAPACITY THEN
         BEGIN
            CAPACITY := 2 * CAPACITY;
            EXPAND(CAPACITY);
         END;
         SIZE := SIZE + 1;
         ITEMS.DATA(SIZE) :- T;
      !  OUTTEXT("SIZE IS ");!OUTINT(SIZE, 0);!OUTIMAGE;
      END;

      PROCEDURE REMOVE(I); INTEGER I;
      BEGIN
        INTEGER J;
        IF I < 1 OR I > SIZE THEN ERROR("REMOVE: INDEX OUT OF BOUNDS");
        FOR J := I STEP 1 UNTIL SIZE - 1 DO
          ITEMS.DATA(J) :- ITEMS.DATA(J + 1);
        ITEMS.DATA(SIZE) :- NONE;
        SIZE := SIZE - 1;
      END;

      REF(ITEM) PROCEDURE GET(I); INTEGER I;
      BEGIN
         IF I < 1 OR I > SIZE THEN ERROR("GET: INDEX OUT OF BOUNDS");
         GET :- ITEMS.DATA(I);
      END;

      INTEGER CAPACITY;
      INTEGER SIZE;
      REF(ITEMARRAY) ITEMS;

      CAPACITY := 20;
      SIZE := 0;
      EXPAND(CAPACITY);

   END;

   ITEM CLASS TEXTITEM(TXT); TEXT TXT;;

   ARRAYLIST CLASS TEXTARRAYLIST;
   BEGIN
      PROCEDURE ADD(T); TEXT T;
         THIS TEXTARRAYLIST QUA ARRAYLIST.ADD(NEW TEXTITEM(T));
      TEXT PROCEDURE GET(I); INTEGER I;
         GET :- THIS TEXTARRAYLIST QUA ARRAYLIST.GET(I) QUA TEXTITEM.TXT;
   END;

   ITEM CLASS REALITEM(X); REAL X;;

   ARRAYLIST CLASS REALARRAYLIST;
   BEGIN
      PROCEDURE ADD(X); REAL X;
         THIS REALARRAYLIST QUA ARRAYLIST.ADD(NEW REALITEM(X));
      REAL PROCEDURE GET(I); INTEGER I;
         GET := THIS REALARRAYLIST QUA ARRAYLIST.GET(I) QUA REALITEM.X;
   END;

END;


templates braceExpansion
  composer braceParse
    [ <part|'[{}\\,]'>* ] // This is not simply <production> because there may be unbalanced special chars
    rule production: [ <part>* ]
    rule part: <alternation|balancedBraces|escapedCharacter|'[^{}\\,]+'>+
    rule alternation: (<='{'>) [ <production> <alternate>+ ] (<='}'>)
    rule alternate: (<=','>) <production>
    rule balancedBraces: <='{'> <part>* <='}'>
    rule escapedCharacter: <'\\.'>
  end braceParse

  templates collateSequence
    @: [''];
    $... -> #
    [email protected]!
    when <'.*'> do
      def part: $;
      @: [[email protected] -> '$;$part;'];
    otherwise
      def alternates: [ $... -> collateSequence ... ];
      @: [[email protected] -> \(def prefix: $; $alternates... -> '$prefix;$;' ! \)];
  end collateSequence

  $ -> braceParse -> collateSequence !
end braceExpansion

'~/{Downloads,Pictures}/*.{jpg,gif,png}' -> '"$;" expands to:$ -> braceExpansion ... -> '$#10;$;';$#10;$#10;' -> !OUT::write

'It{{em,alic}iz,erat}e{d,}, please.' -> '"$;" expands to $ -> braceExpansion ... -> '$#10;$;';$#10;$#10;' -> !OUT::write

'{,{,gotta have{ ,\, again\, }}more }cowbell!' -> '"$;" expands to $ -> braceExpansion ... -> '$#10;$;';$#10;$#10;' -> !OUT::write

'{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}' -> '"$;" expands to $ -> braceExpansion ... -> '$#10;$;';$#10;$#10;' -> !OUT::write