import std.stdio, std.typecons, std.array, std.range, std.algorithm, std.string;

Nullable!(Tuple!(string[], string)) getGroup(string s, in uint depth)
pure nothrow @safe {
    string[] sout;
    auto comma = false;

    while (!s.empty) {
        // {const g, s} = getItems(s, depth);
        const r = getItems(s, depth);
        const g = r[0];
        s = r[1];

        if (s.empty)
            break;
        sout ~= g;

        if (s[0] == '}') {
            if (comma)
                return typeof(return)(tuple(sout, s[1 .. $]));
            return typeof(return)(tuple(
                sout.map!(a => '{' ~ a ~ '}').array, s[1 .. $]));
        }

        if (s[0] == ',') {
            comma = true;
            s = s[1 .. $];
        }
    }
    return typeof(return)();
}

Tuple!(string[], string) getItems(string s, in uint depth=0) pure @safe nothrow {
    auto sout = [""];

    while (!s.empty) {
        auto c = s[0 .. 1];
        if (depth && (c == "," || c == "}"))
            return tuple(sout, s);

        if (c == "{") {
            /*const*/ auto x = getGroup(s.dropOne, depth + 1);
            if (!x.isNull) {
                sout = cartesianProduct(sout, x[0])
                       .map!(ab => ab[0] ~ ab[1])
                       .array;
                s = x[1];
                continue;
            }
        }

        if (c == "\\" && s.length > 1) {
            c ~= s[1];
            s = s[1 .. $];
        }

        sout = sout.map!(a => a ~ c).array;
        s = s[1 .. $];
    }
    return tuple(sout, s);
}

void main() @safe {
    immutable testCases = r"~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
a{b{1,2}c
a{1,2}b}c
a{1,{2},3}b
a{b{1,2}c{}}
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
{a,b{{1,2}e}f";

    foreach (const s; testCases.splitLines)
        writefln("%s\n%-(    %s\n%)\n", s, s.getItems[0]);
}


include std\text.e
include std\os.e
include std\sequence.e
include std\console.e

sequence bcData = {0,0} --bull,cow score for the player
sequence goalNum = { {0,0,0,0}, {0,0,0,0}, 0} --computer's secret number digits (element 1), marked as bull/cow
--indexes in element 2, integer value of it in element 3
sequence currentGuess = { {0,0,0,0}, {0,0,0,0}, 0} --player's guess, same format as goalNum
sequence removeChars = 0 & " 0\r\t\n" --characters to trim (remove) from user's input. \r, \t are single escaped characters,
--0 is ascii 0x0 and number zero is ascii 48, or 0x30. The rest are wysiwyg
integer tries = 0 --track number of tries to guess the number
sequence bcStrings ={"bull", "cow"} --stores singular and/or plural strings depending on score in bcData

goalNum[1] = rand( {9,9,9,9} ) --rand function works on objects. here it outputs into each sequence element.
goalNum[3] = goalNum[1][1] * 1000 + goalNum[1][2] * 100 + goalNum[1][3] * 10 + goalNum[1][4] --convert digits to an integer
--and store it

procedure getInputAndProcess(integer stage = 1)  --object = 1 sets default value for the parameter if it isn't specified

    goalNum[2][1..4] = 0 --{0,0,0,0} --set these to unscaned (0) since the scanning will start over.
    currentGuess[1][1..4] = 0 --{0,0,0,0} --these too, or they will contain old marks
    currentGuess[2][1..4] = 0
    tries += 1 --equivalent to tries = tries + 1, but faster and shorter to write
    bcData[1..2] = 0 -- {0,0}

    if stage <= 1 then --if this process was run for the first time or with no parameters, then..
        puts(1,"The program has thought of a four digit number using only digits 1 to 9.\nType your guess and press enter.\n")
    end if

    while 1 label "guesscheck" do --labels can be used to specify a jump point from exit or retry, and help readability
        currentGuess[1] = trim(gets(0), removeChars) --get user input, trim unwanted characters from it, store it in currentGuess[1]
        currentGuess[1] = mapping( currentGuess[1], {49,50,51,52,53,54,55,56,57}, {1,2,3,4,5,6,7,8,9} ) --convert ascii codes to
        -- integer digits they represent
        integer tempF = find('0',currentGuess[1])
        if length(currentGuess[1]) != 4 or tempF != 0 then --if the input string is now more than 4 characters/integers,
            --the input won't be used.
            puts(1,"You probably typed too many digits or a 0. Try typing a new 4 digit number with only numbers 1 through 9.\n")
            retry "guesscheck"
            else
                exit "guesscheck"
        end if
    end while
    --convert separate digits to the one integer they represent and store it, like with goalNum[3]
    currentGuess[3] = currentGuess[1][1] * 1000 + currentGuess[1][2] * 100 + currentGuess[1][3] * 10 + currentGuess[1][4]
--convert digits to the integer they represent, to print to a string later

    --check for bulls
    for i = 1 to 4 do
        if goalNum[1][i] = currentGuess[1][i] then
            goalNum[2][i] = 1
            currentGuess[2][i] = 1
            bcData[1] += 1
        end if
    end for

    --check for cows, but not slots marked as bulls or cows already.
    for i = 1 to 4 label "iGuessElem"do --loop through each guessed digit
        for j = 1 to 4 label "jGoalElem" do --but first go through each goal digit, comparing the first guessed digit,
            --and then the other guessed digits 2 through 4

            if currentGuess[2][i] = 1 then --if the guessed digit we're comparing right now has been marked as bull or cow already
                continue "iGuessElem" --skip to the next guess digit without comparing this guess digit to the other goal digits
            end if

            if goalNum[2][j] = 1 then --if the goal digit we're comparing to right now has been marked as a bull or cow already
                continue "jGoalElem" --skip to the next goal digit
            end if

            if currentGuess[1][i] = goalNum[1][j] then --if the guessed digit is the same as the goal one,
                --it won't be a bull, so it's a cow
                bcData[2] += 1 --score one more cow
                goalNum[2][j] = 1 --mark this digit as a found cow in the subsequence that stores 0's or 1's as flags
                continue "iGuessElem" --skip to the next guess digit, so that this digit won't try to check for
                --matches(cow) with other goal digits
            end if

        end for --this guess digit was compared to one goal digit , try comparing this guess digit with the next goal digit
    end for --this guess digit was compared with all goal digits, compare the next guess digit to all the goal digits

    if bcData[1] = 1 then --uses singular noun when there is score of 1, else plural
        bcStrings[1] = "bull"
        else
            bcStrings[1] = "bulls"
    end if

    if bcData[2] = 1 then --the same kind of thing as above block
        bcStrings[2] = "cow"
        else
            bcStrings[2] = "cows"
    end if

    if bcData[1] < 4 then --if less than 4 bulls were found, the player hasn't won, else they have...
        printf(1, "Guess #%d : You guessed %d . You found %d %s, %d %s. Type new guess.\n", {tries, currentGuess[3], bcData[1], bcStrings[1], bcData[2], bcStrings[2]} )
        getInputAndProcess(2)
    else --else they have won and the procedure ends
        printf(1, "The number was %d. You guessed %d in %d tries.\n", {goalNum[3], currentGuess[3], tries} )
        any_key()--wait for keypress before closing console window.
    end if

end procedure
--run the procedure
getInputAndProcess(1)


go ?=>
  member(N,1..5),
  println(N),
  fail, % or false/0 to get other solutions
  nl.
go => true.


> 0;
(3) Result: 0
> false;
(4) Result: 0
> 0;
(6) Result: 0
> !true;
(7) Result: 0
> true;
(8) Result: 1
> 1;
(9) Result: 1
>


#include <stdio.h>

typedef char bool;

#define TRUE 1
#define FALSE 0

bool same_digits(int n, int b) {
    int f = n % b;
    n /= b;
    while (n > 0) {
        if (n % b != f) return FALSE;
        n /= b;
    }
    return TRUE;
}

bool is_brazilian(int n) {
    int b;
    if (n < 7) return FALSE;
    if (!(n % 2) && n >= 8) return TRUE;
    for (b = 2; b < n - 1; ++b) {
        if (same_digits(n, b)) return TRUE;
    }
    return FALSE;
}

bool is_prime(int n) {
    int d = 5;
    if (n < 2) return FALSE;
    if (!(n % 2)) return n == 2;
    if (!(n % 3)) return n == 3;
    while (d * d <= n) {
        if (!(n % d)) return FALSE;
        d += 2;
        if (!(n % d)) return FALSE;
        d += 4;
    }
    return TRUE;
}

int main() {
    int i, c, n;
    const char *kinds[3] = {" ", " odd ", " prime "};
    for (i = 0; i < 3; ++i) {
        printf("First 20%sBrazilian numbers:\n", kinds[i]);
        c = 0;
        n = 7;
        while (TRUE) {
            if (is_brazilian(n)) {
                printf("%d ", n);
                if (++c == 20) {
                    printf("\n\n");
                    break;
                }
            }
            switch (i) {
                case 0: n++; break;
                case 1: n += 2; break;
                case 2:
                    do {
                        n += 2;
                    } while (!is_prime(n));
                    break;
            }
        }
    }

    for (n = 7, c = 0; c < 100000; ++n) {
        if (is_brazilian(n)) c++;
    }
    printf("The 100,000th Brazilian number: %d\n", n - 1);
    return 0;
}


defmodule Brace_expansion do
  def getitem(s), do: getitem(String.codepoints(s), 0, [""])

  defp getitem([], _, out), do: {out,[]}
  defp getitem([c|_]=s, depth, out) when depth>0 and (c == "," or c == "}"), do: {out,s}
  defp getitem([c|t], depth, out) do
    x = getgroup(t, depth+1, [], false)
    if (c == "{") and x do
      {y, z} = x
      out2 = for a <- out, b <- y, do: a<>b
      getitem(z, depth, out2)
    else
      if c == "\\" and length(t) > 0 do
        c2 = c <> hd(t)
        getitem(tl(t), depth, Enum.map(out, fn a -> a <> c2 end))
      else
        getitem(t, depth, Enum.map(out, fn a -> a <> c end))
      end
    end
  end

  defp getgroup([], _, _, _), do: nil
  defp getgroup(s, depth, out, comma) do
    {g, s2} = getitem(s, depth, [""])
    if s2 == [] do
      nil
    else
      out2 = out ++ g
      case hd(s2) do
        "}" -> if comma, do: {out2, tl(s2)},
                       else: {Enum.map(out2, &"{#{&1}}"), tl(s2)}
        "," -> getgroup(tl(s2), depth, out2, true)
        _   -> getgroup(s2, depth, out2, comma)
      end
    end
  end
end

test_cases = ~S"""
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
""" |> String.split("\n", trim: true)

Enum.each(test_cases, fn s ->
  IO.puts s
  Brace_expansion.getitem(s)
  |> elem(0)
  |> Enum.each(fn str -> IO.puts "\t#{str}" end)
  IO.puts ""
end)


package expand

// Expander is anything that can be expanded into a slice of strings.
type Expander interface {
	Expand() []string
}

// Text is a trivial Expander that expands to a slice with just itself.
type Text string

func (t Text) Expand() []string { return []string{string(t)} }

// Alternation is an Expander that expands to the union of its
// members' expansions.
type Alternation []Expander

func (alt Alternation) Expand() []string {
	var out []string
	for _, e := range alt {
		out = append(out, e.Expand()...)
	}
	return out
}

// Sequence is an Expander that expands to the combined sequence of its
// members' expansions.
type Sequence []Expander

func (seq Sequence) Expand() []string {
	if len(seq) == 0 {
		return nil
	}
	out := seq[0].Expand()
	for _, e := range seq[1:] {
		out = combine(out, e.Expand())
	}
	return out
}

func combine(al, bl []string) []string {
	out := make([]string, 0, len(al)*len(bl))
	for _, a := range al {
		for _, b := range bl {
			out = append(out, a+b)
		}
	}
	return out
}

// Currently only single byte runes are supported for these.
const (
	escape   = '\\'
	altStart = '{'
	altEnd   = '}'
	altSep   = ','
)

type piT struct{ pos, cnt, depth int }

type Brace string

// Expand takes an input string and returns the expanded list of
// strings. The input string can contain any number of nested
// alternation specifications of the form "{A,B}" which is expanded to
// the strings "A", then "B".
//
// E.g. Expand("a{2,1}b{X,Y,X}c") returns ["a2bXc", "a2bYc", "a2bXc",
// "a1bXc", "a1bYc", "a1bXc"].
//
// Unmatched '{', ',', and '}' characters are passed through to the
// output. The special meaning of these characters can be escaped with
// '\', (which itself can be escaped).
// Escape characters are not removed, but passed through to the output.
func Expand(s string) []string   { return Brace(s).Expand() }
func (b Brace) Expand() []string { return b.Expander().Expand() }
func (b Brace) Expander() Expander {
	s := string(b)
	//log.Printf("Exapand(%#q)\n", s)
	var posInfo []piT
	var stack []int // indexes into posInfo
	removePosInfo := func(i int) {
		end := len(posInfo) - 1
		copy(posInfo[i:end], posInfo[i+1:])
		posInfo = posInfo[:end]
	}

	inEscape := false
	for i, r := range s {
		if inEscape {
			inEscape = false
			continue
		}
		switch r {
		case escape:
			inEscape = true
		case altStart:
			stack = append(stack, len(posInfo))
			posInfo = append(posInfo, piT{i, 0, len(stack)})
		case altEnd:
			if len(stack) == 0 {
				continue
			}
			si := len(stack) - 1
			pi := stack[si]
			if posInfo[pi].cnt == 0 {
				removePosInfo(pi)
				for pi < len(posInfo) {
					if posInfo[pi].depth == len(stack) {
						removePosInfo(pi)
					} else {
						pi++
					}
				}
			} else {
				posInfo = append(posInfo, piT{i, -2, len(stack)})
			}
			stack = stack[:si]
		case altSep:
			if len(stack) == 0 {
				continue
			}
			posInfo = append(posInfo, piT{i, -1, len(stack)})
			posInfo[stack[len(stack)-1]].cnt++
		}
	}
	//log.Println("stack:", stack)
	for len(stack) > 0 {
		si := len(stack) - 1
		pi := stack[si]
		depth := posInfo[pi].depth
		removePosInfo(pi)
		for pi < len(posInfo) {
			if posInfo[pi].depth == depth {
				removePosInfo(pi)
			} else {
				pi++
			}
		}
		stack = stack[:si]
	}
	return buildExp(s, 0, posInfo)
}

func buildExp(s string, off int, info []piT) Expander {
	if len(info) == 0 {
		return Text(s)
	}
	//log.Printf("buildExp(%#q, %d, %v)\n", s, off, info)
	var seq Sequence
	i := 0
	var dj, j, depth int
	for dk, piK := range info {
		k := piK.pos - off
		switch s[k] {
		case altStart:
			if depth == 0 {
				dj = dk
				j = k
				depth = piK.depth
			}
		case altEnd:
			if piK.depth != depth {
				continue
			}
			if j > i {
				seq = append(seq, Text(s[i:j]))
			}
			alt := buildAlt(s[j+1:k], depth, j+1+off, info[dj+1:dk])
			seq = append(seq, alt)
			i = k + 1
			depth = 0
		}
	}
	if j := len(s); j > i {
		seq = append(seq, Text(s[i:j]))
	}
	if len(seq) == 1 {
		return seq[0]
	}
	return seq
}

func buildAlt(s string, depth, off int, info []piT) Alternation {
	//log.Printf("buildAlt(%#q, %d, %d, %v)\n", s, depth, off, info)
	var alt Alternation
	i := 0
	var di int
	for dk, piK := range info {
		if piK.depth != depth {
			continue
		}
		if k := piK.pos - off; s[k] == altSep {
			sub := buildExp(s[i:k], i+off, info[di:dk])
			alt = append(alt, sub)
			i = k + 1
			di = dk + 1
		}
	}
	sub := buildExp(s[i:], i+off, info[di:])
	alt = append(alt, sub)
	return alt
}


USING: accessors assocs combinators fry grouping hashtables kernel
       locals math math.parser math.ranges random sequences strings
       io ascii ;

IN: bullsncows

TUPLE: score bulls cows ;
: <score> ( -- score ) 0 0 score boa ;

TUPLE: cow ;
: <cow> ( -- cow ) cow new ;

TUPLE: bull ;
: <bull> ( -- bull ) bull new ;

: inc-bulls ( score -- score ) dup bulls>> 1 + >>bulls ;
: inc-cows ( score -- score ) dup cows>> 1 + >>cows ;

: random-nums ( -- seq ) 9 [1,b] 4 sample ;

: add-digits ( seq -- n ) 0 [ swap 10 * + ] reduce number>string ;

: new-number ( -- n narr ) random-nums dup add-digits ;

: narr>nhash ( narr -- nhash ) { 1 2 3 4 } swap zip ;

: num>hash ( n -- hash )
    [ 1string string>number ] { } map-as narr>nhash ;

:: cow-or-bull ( n g -- arr )
    {
        { [ n first g at n second = ] [ <bull> ] }
        { [ n second g value? ] [ <cow> ] }
        [ f ]
    } cond ;

: add-to-score ( arr -- score )
   <score> [ bull? [ inc-bulls ] [ inc-cows ] if ] reduce ;

: check-win ( score -- ? ) bulls>> 4 = ;

: sum-score ( n g -- score ? )
    '[ _ cow-or-bull ] map sift add-to-score dup check-win ;

: print-sum ( score -- str )
    dup bulls>> number>string "Bulls: " swap append swap cows>> number>string
    " Cows: " swap 3append "\n" append ;

: (validate-readln) ( str -- ? ) dup length 4 = not swap [ letter? ] all? or ;

: validate-readln ( -- str )
    readln dup (validate-readln)
    [ "Invalid input.\nPlease enter a valid 4 digit number: "
      write flush drop validate-readln ]
    when ;

: win ( -- ) "\nYou've won! Good job. You're so smart." print flush ;

: main-loop ( x -- )
    "Enter a 4 digit number: " write flush validate-readln num>hash swap
    [ sum-score swap print-sum print flush ] keep swap not
    [ main-loop ] [ drop win ] if ;

: main ( -- ) new-number drop narr>nhash main-loop ;


**
** Bulls and cows. A game pre-dating, and similar to, Mastermind.
**
class BullsAndCows
{

  Void main()
  {
    digits := [1,2,3,4,5,6,7,8,9]
    size := 4
    chosen := [,]
    size.times { chosen.add(digits.removeAt(Int.random(0..<digits.size))) }

    echo("I've chosen $size unique digits from 1 to 9 at random.
          Try to guess my number!")
    guesses := 0
    while (true) // game loop
    {
      guesses += 1
      guess := Int[,]
      while (true) // input loop
      {
        // get a good guess
        Sys.out.print("\nNext guess [$guesses]: ")
        Sys.out.flush
        inString := Sys.in.readLine?.trim ?: ""
        inString.each |ch|
        { if (ch >= '1' && ch <= '9' && !guess.contains(ch)) guess.add(ch-'0') }
        if (guess.size == 4)
          break // input loop
        echo("Oops, try again. You need to enter $size unique digits from 1 to 9")
      }
      if (guess.all |v, i->Bool| { return v == chosen[i] })
      {
        echo("\nCongratulations! You guessed correctly in $guesses guesses")
        break // game loop
      }
      bulls := 0
      cows  := 0
      (0 ..< size).each |i|
      {
        if (guess[i] == chosen[i])
          bulls += 1
        else if (chosen.contains(guess[i]))
          cows += 1
      }
      echo("\n  $bulls Bulls\n  $cows Cows")
    }
  }
}


Declare x bit(1);
x='1'b; /* True */
x='0'b; /* False */


IF 0 THEN /* THIS WON'T RUN */;
IF 1 THEN /* THIS WILL */;
IF 2 THEN /* THIS WON'T */;
IF 3 THEN /* THIS WILL */;


using System;
class Program {

  static bool sameDigits(int n, int b) {
    int f = n % b;
    while ((n /= b) > 0) if (n % b != f) return false;
    return true;
  }

  static bool isBrazilian(int n) {
    if (n < 7) return false;
    if (n % 2 == 0) return true;
    for (int b = 2; b < n - 1; b++) if (sameDigits(n, b)) return true;
    return false;
  }

  static bool isPrime(int n) {
    if (n < 2) return false;
    if (n % 2 == 0) return n == 2;
    if (n % 3 == 0) return n == 3;
    int d = 5;
    while (d * d <= n) {
      if (n % d == 0) return false; d += 2;
      if (n % d == 0) return false; d += 4;
    }
    return true;
  }

  static void Main(string[] args) {
    foreach (string kind in ",odd ,prime ".Split(',')) {
      bool quiet = false; int BigLim = 99999, limit = 20;
      Console.WriteLine("First {0} {1}Brazilian numbers:", limit, kind);
      int c = 0, n = 7;
      while (c < BigLim) {
        if (isBrazilian(n)) {
          if (!quiet) Console.Write("{0:n0} ", n);
          if (++c == limit) { Console.Write("\n\n"); quiet = true; }
        }
        if (quiet && kind != "") continue;
        switch (kind) {
          case "": n++; break;
          case "odd ": n += 2; break;
          case "prime ":
            while (true) {
              n += 2;
              if (isPrime(n)) break;
            } break;
        }
      }
      if (kind == "") Console.WriteLine("The {0:n0}th Brazilian number is: {1:n0}\n", BigLim + 1, n);
    }
  }
}


class BraceExpansion {
    static void main(String[] args) {
        for (String s : [
                "It{{em,alic}iz,erat}e{d,}, please.",
                "~/{Downloads,Pictures}/*.{jpg,gif,png}",
                "{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
                "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"
        ]) {
            println()
            expand(s)
        }
    }

    static void expand(String s) {
        expandR("", s, "")
    }

    private static void expandR(String pre, String s, String suf) {
        int i1 = -1, i2 = 0
        String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", "  ")
        StringBuilder sb = null

        outer:
        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {
            i2 = i1 + 1
            sb = new StringBuilder(s)
            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {
                char c = noEscape.charAt(i2)
                depth = (c == ('{' as char)) ? ++depth : depth
                depth = (c == ('}' as char)) ? --depth : depth
                if (c == (',' as char) && depth == 1) {
                    sb.setCharAt(i2, '\u0000' as char)
                } else if (c == ('}' as char) && depth == 0 && sb.indexOf("\u0000") != -1) {
                    break outer
                }
            }
        }
        if (i1 == -1) {
            if (suf.length() > 0) {
                expandR(pre + s, suf, "")
            } else {
                printf("%s%s%s%n", pre, s, suf)
            }
        } else {
            for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1)) {
                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf)
            }
        }
    }
}


>>> True
True
>>> not True
False
>>> # As numbers
>>> False + 0
0
>>> True + 0
1
>>> False + 0j
0j
>>> True * 3.141
3.141
>>> # Numbers as booleans
>>> not 0
True
>>> not not 0
False
>>> not 1234
False
>>> bool(0.0)
False
>>> bool(0j)
False
>>> bool(1+2j)
True
>>> # Collections as booleans
>>> bool([])
False
>>> bool([None])
True
>>> 'I contain something' if (None,) else 'I am empty'
'I contain something'
>>> bool({})
False
>>> bool("")
False
>>> bool("False")
True


#include <iostream>

bool sameDigits(int n, int b) {
    int f = n % b;
    while ((n /= b) > 0) {
        if (n % b != f) {
            return false;
        }
    }
    return true;
}

bool isBrazilian(int n) {
    if (n < 7) return false;
    if (n % 2 == 0)return true;
    for (int b = 2; b < n - 1; b++) {
        if (sameDigits(n, b)) {
            return true;
        }
    }
    return false;
}

bool isPrime(int n) {
    if (n < 2)return false;
    if (n % 2 == 0)return n == 2;
    if (n % 3 == 0)return n == 3;
    int d = 5;
    while (d * d <= n) {
        if (n % d == 0)return false;
        d += 2;
        if (n % d == 0)return false;
        d += 4;
    }
    return true;
}

int main() {
    for (auto kind : { "", "odd ", "prime " }) {
        bool quiet = false;
        int BigLim = 99999;
        int limit = 20;
        std::cout << "First " << limit << ' ' << kind << "Brazillian numbers:\n";
        int c = 0;
        int n = 7;
        while (c < BigLim) {
            if (isBrazilian(n)) {
                if (!quiet)std::cout << n << ' ';
                if (++c == limit) {
                    std::cout << "\n\n";
                    quiet = true;
                }
            }
            if (quiet && kind != "") continue;
            if (kind == "") {
                n++;
            }
            else if (kind == "odd ") {
                n += 2;
            }
            else if (kind == "prime ") {
                while (true) {
                    n += 2;
                    if (isPrime(n)) break;
                }
            } else {
                throw new std::runtime_error("Unexpected");
            }
        }
        if (kind == "") {
            std::cout << "The " << BigLim + 1 << "th Brazillian number is: " << n << "\n\n";
        }
    }

    return 0;
}


import qualified Text.Parsec as P

showExpansion :: String -> String
showExpansion =
  (<>) . (<> "\n-->\n") <*> (either show unlines . P.parse parser [])

parser :: P.Parsec String u [String]
parser = expansion P.anyChar

expansion :: P.Parsec String u Char -> P.Parsec String u [String]
expansion =
  fmap expand .
  P.many .
  ((P.try alts P.<|> P.try alt1 P.<|> escape) P.<|>) . fmap (pure . pure)

expand :: [[String]] -> [String]
expand = foldr ((<*>) . fmap (<>)) [[]]

alts :: P.Parsec String u [String]
alts = concat <$> P.between (P.char '{') (P.char '}') (alt `sepBy2` P.char ',')

alt :: P.Parsec String u [String]
alt = expansion (P.noneOf ",}")

alt1 :: P.Parsec String u [String]
alt1 =
  (\x -> ['{' : (x <> "}")]) <$>
  P.between (P.char '{') (P.char '}') (P.many $ P.noneOf ",{}")

sepBy2 :: P.Parsec String u a -> P.Parsec String u b -> P.Parsec String u [a]
p `sepBy2` sep = (:) <$> p <*> P.many1 (sep >> p)

escape :: P.Parsec String u [String]
escape = pure <$> sequence [P.char '\\', P.anyChar]

main :: IO ()
main =
  mapM_
    (putStrLn . showExpansion)
    [ "~/{Downloads,Pictures}/*.{jpg,gif,png}"
    , "It{{em,alic}iz,erat}e{d,}, please."
    , "{,{,gotta have{ ,\\, again\\, }}more }cowbell!"
    , "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"
    ]


include random.fs

create hidden 4 allot

: ok? ( str -- ? )
  dup 4 <> if 2drop false exit then
  1 9 lshift 1- -rot
  bounds do
    i [email protected] '1 -
    dup 0 9 within 0= if 2drop false leave then
    1 swap lshift over and
    dup 0= if nip leave then
    xor
  loop 0<> ;

: init
  begin
    hidden 4 bounds do 9 random '1 + i c! loop
    hidden 4 ok?
  until ;

: check? ( addr -- solved? )
  0
  4 0 do
    over i + [email protected]
    4 0 do
      dup hidden i + [email protected] = if     swap
        i j = if 8 else 1 then + swap
      then
    loop drop
  loop nip
  8 /mod tuck . ." bulls, " . ." cows"
  4 = ;

: guess: ( "1234" -- )
  bl parse 2dup ok? 0= if 2drop ." Bad guess! (4 unique digits, 1-9)" exit then
  drop check? if cr ." You guessed it!" then ;


module bac
  implicit none

contains

  subroutine Gennum(n)
    integer, intent(out) :: n(4)
    integer :: i, j
    real :: r

    call random_number(r)
    n(1) = int(r * 9.0) + 1
    i = 2

outer: do while (i <= 4)
         call random_number(r)
         n(i) = int(r * 9.0) + 1
inner:   do j = i-1 , 1, -1
           if (n(j) == n(i)) cycle outer
         end do inner
         i = i + 1
       end do outer

  end subroutine Gennum

  subroutine Score(n, guess, b, c)
    character(*), intent(in) :: guess
    integer, intent(in) :: n(0:3)
    integer, intent(out) :: b, c
    integer :: digit, i, j, ind

    b = 0; c = 0
    do i = 1, 4
      read(guess(i:i), "(i1)") digit
      if (digit == n(i-1)) then
        b = b + 1
      else
        do j = i, i+2
          ind = mod(j, 4)
          if (digit == n(ind)) then
            c = c + 1
            exit
          end if
        end do
      end if
    end do

 end subroutine Score

end module bac

program Bulls_and_Cows
   use bac
   implicit none

   integer :: n(4)
   integer :: bulls=0, cows=0, tries=0
   character(4) :: guess

   call random_seed
   call Gennum(n)

   write(*,*) "I have selected a number made up of 4 digits (1-9) without repetitions."
   write(*,*) "You attempt to guess this number."
   write(*,*) "Every digit in your guess that is in the correct position scores 1 Bull"
   write(*,*) "Every digit in your guess that is in an incorrect position scores 1 Cow"
   write(*,*)

   do while (bulls /= 4)
     write(*,*) "Enter a 4 digit number"
     read*, guess
     if (verify(guess, "123456789") /= 0) then
       write(*,*) "That is an invalid entry. Please try again."
       cycle
     end if
     tries = tries + 1
     call Score (n, guess, bulls, cows)
     write(*, "(a, i1, a, i1, a)") "You scored ", bulls, " bulls and ", cows, " cows"
     write(*,*)
   end do

   write(*,"(a,i0,a)") "Congratulations! You correctly guessed the correct number in ", tries, " attempts"

end program Bulls_and_Cows


(cond ([(< 4 3) 'apple]
       ['bloggle 'pear]
       [else 'nectarine])


my Bool $crashed = False;
my $val = 0 but True;


TRUE print
FALSE print
2 1 > print   # TRUE (-1)
3 2 < print   # FALSE (0)
42 FALSE !=   # TRUE (-1)


import std.stdio;

bool sameDigits(int n, int b) {
    int f = n % b;
    while ((n /= b) > 0) {
        if (n % b != f) {
            return false;
        }
    }
    return true;
}

bool isBrazilian(int n) {
    if (n < 7) return false;
    if (n % 2 == 0) return true;
    for (int b = 2; b < n - 1; ++b) {
        if (sameDigits(n, b)) {
            return true;
        }
    }
    return false;
}

bool isPrime(int n) {
    if (n < 2) return false;
    if (n % 2 == 0) return n == 2;
    if (n % 3 == 0) return n == 3;
    int d = 5;
    while (d * d <= n) {
        if (n % d == 0) return false;
        d += 2;
        if (n % d == 0) return false;
        d += 4;
    }
    return true;
}

void main() {
    foreach (kind; ["", "odd ", "prime "]) {
        bool quiet = false;
        int BigLim = 99999;
        int limit = 20;
        writefln("First %s %sBrazillion numbers:", limit, kind);
        int c = 0;
        int n = 7;
        while (c < BigLim) {
            if (isBrazilian(n)) {
                if (!quiet) write(n, ' ');
                if (++c == limit) {
                    writeln("\n");
                    quiet = true;
                }
            }
            if (quiet && kind != "") continue;
            switch (kind) {
                case "": n++; break;
                case "odd ": n += 2; break;
                case "prime ":
                    while (true) {
                        n += 2;
                        if (isPrime(n)) break;
                    }
                    break;
                default: assert(false);
            }
        }
        if (kind == "") writefln("The %sth Brazillian number is: %s\n", BigLim + 1, n);
    }
}


NB. legit { , and } do not follow a legit backslash:
legit=: 1,_1}.4>(3;(_2[\"1".;._2]0 :0);('\';a.);0 _1 0 1)&;:&.(' '&,)
 2 1   1 1 NB. result 0 or 1: initial state
 2 2   1 2 NB. result 2 or 3: after receiving a non backslash
 1 2   1 2 NB. result 4 or 5: after receiving a backslash
)

expand=:3 :0
  Ch=. u:inv y
  M=. N=. 1+>./ Ch
  Ch=. Ch*-_1^legit y
  delim=. 'left comma right'=. u:inv '{,}'
  J=. i.K=. #Ch
  while. M=. M+1 do.
    candidates=. i.0 2
    for_check.I. comma=Ch do.
      begin=. >./I. left=check{. Ch
      end=. check+<./I. right=check}. Ch
      if. K>:end-begin do.
        candidates=. candidates,begin,end
      end.
    end.
    if. 0=#candidates do. break. end.
    'begin end'=. candidates{~(i.>./) -/"1 candidates
    ndx=. I.(begin<:J)*(end>:J)*Ch e. delim
    Ch=. M ndx} Ch
  end.
  T=. ,<Ch
  for_mark. |.N}.i.M  do.
    T=. ; mark divide each T
  end.
  u: each |each T
)

divide=:4 :0
  if. -.x e. y do. ,<y return. end.
  mask=. x=y
  prefix=. < y #~ -.+./\ mask
  suffix=. < y #~ -.+./\. mask
  options=. }:mask <;._1 y
  prefix,each options,each suffix
)


public class BraceExpansion {

    public static void main(String[] args) {
        for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.",
            "~/{Downloads,Pictures}/*.{jpg,gif,png}",
            "{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
            "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"}) {
            System.out.println();
            expand(s);
        }
    }

    public static void expand(String s) {
        expandR("", s, "");
    }

    private static void expandR(String pre, String s, String suf) {
        int i1 = -1, i2 = 0;
        String noEscape = s.replaceAll("([\\\\]{2}|[\\\\][,}{])", "  ");
        StringBuilder sb = null;

        outer:
        while ((i1 = noEscape.indexOf('{', i1 + 1)) != -1) {
            i2 = i1 + 1;
            sb = new StringBuilder(s);
            for (int depth = 1; i2 < s.length() && depth > 0; i2++) {
                char c = noEscape.charAt(i2);
                depth = (c == '{') ? ++depth : depth;
                depth = (c == '}') ? --depth : depth;
                if (c == ',' && depth == 1) {
                    sb.setCharAt(i2, '\u0000');
                } else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1)
                    break outer;
            }
        }
        if (i1 == -1) {
            if (suf.length() > 0)
                expandR(pre + s, suf, "");
            else
                System.out.printf("%s%s%s%n", pre, s, suf);
        } else {
            for (String m : sb.substring(i1 + 1, i2).split("\u0000", -1))
                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf);
        }
    }
}


open System

let generate_number targetSize =
    let rnd = Random()
    let initial = Seq.initInfinite (fun _ -> rnd.Next(1,9))
    initial |> Seq.distinct |> Seq.take(targetSize) |> Seq.toList

let countBulls guess target =
    let hits = List.map2 (fun g t -> if g = t then true else false) guess target
    List.filter (fun x -> x = true) hits |> List.length

let countCows guess target =
    let mutable score = 0
    for g in guess do
        for t in target do
            if g = t then
                score <- score + 1
            else
                score <- score
    score

let countScore guess target =
    let bulls = countBulls guess target
    let cows = countCows guess target
    (bulls, cows)

let playRound guess target =
    countScore guess target

let inline ctoi c : int =
    int c - int '0'

let lineToList (line: string) =
    let listc = Seq.map(fun c -> c |> string) line |> Seq.toList
    let conv = List.map(fun x -> Int32.Parse x) listc
    conv

let readLine() =
    let line = Console.ReadLine()
    if line <> null then
        if line.Length = 4 then
            Ok (lineToList line)
        else
            Error("Input guess must be 4 characters!")
    else
        Error("Input guess cannot be empty!")

let rec handleInput() =
    let line = readLine()
    match line with
    | Ok x -> x
    | Error s ->
        printfn "%A" s
        handleInput()

[<EntryPoint>]
let main argv =
    let target = generate_number 4
    let mutable shouldEnd = false
    while shouldEnd = false do
        let guess = handleInput()
        let (b, c) = playRound guess target
        printfn "Bulls: %i | Cows: %i" b c
        if b = 4 then
            shouldEnd <- true
        else
            shouldEnd <- false
    0


x = True
y = False
see "x and y : " + (x and y) + nl
see "x or y : " + (x or y) + nl
see "not x : " + (not x) + nl


program Brazilian_numbers;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  TBrazilianNumber = record
  private
    FValue: Integer;
    FIsBrazilian: Boolean;
    FIsPrime: Boolean;
    class function SameDigits(a, b: Integer): Boolean; static;
    class function CheckIsBrazilian(a: Integer): Boolean; static;
    class function CheckIsPrime(a: Integer): Boolean; static;
    constructor Create(const Number: Integer);
    procedure SetValue(const Value: Integer);
  public
    property Value: Integer read FValue write SetValue;
    property IsBrazilian: Boolean read FIsBrazilian;
    property IsPrime: Boolean read FIsPrime;
  end;

{ TBrazilianNumber }

class function TBrazilianNumber.CheckIsBrazilian(a: Integer): Boolean;
var
  b: Integer;
begin
  if (a < 7) then
    Exit(false);

  if (a mod 2 = 0) then
    Exit(true);

  for b := 2 to a - 2 do
  begin
    if (sameDigits(a, b)) then
      exit(True);
  end;
  Result := False;
end;

constructor TBrazilianNumber.Create(const Number: Integer);
begin
  SetValue(Number);
end;

class function TBrazilianNumber.CheckIsPrime(a: Integer): Boolean;
var
  d: Integer;
begin
  if (a < 2) then
    exit(False);

  if (a mod 2) = 0 then
    exit(a = 2);

  if (a mod 3) = 0 then
    exit(a = 3);

  d := 5;

  while (d * d <= a) do
  begin
    if (a mod d = 0) then
      Exit(false);
    inc(d, 2);

    if (a mod d = 0) then
      Exit(false);
    inc(d, 4);
  end;

  Result := True;
end;

class function TBrazilianNumber.SameDigits(a, b: Integer): Boolean;
var
  f: Integer;
begin
  f := a mod b;
  a := a div b;
  while a > 0 do
  begin
    if (a mod b) <> f then
      exit(False);
    a := a div b;
  end;
  Result := True;
end;

procedure TBrazilianNumber.SetValue(const Value: Integer);
begin
  if Value < 0 then
    FValue := 0
  else
    FValue := Value;
  FIsBrazilian := CheckIsBrazilian(FValue);
  FIsPrime := CheckIsPrime(FValue);
end;

const
  TextLabel: array[0..2] of string = ('', 'odd', 'prime');

var
  Number: TBrazilianNumber;
  Count: array[0..2] of Integer;
  i, j, left, Num: Integer;
  data: array[0..2] of string;

begin
  left := 3;
  for i := 0 to 99999 do
  begin
    if Number.Create(i).IsBrazilian then
      for j := 0 to 2 do
      begin

        if (Count[j] >= 20) and (j > 0) then
          continue;

        case j of
          0:
            begin
              inc(Count[j]);
              Num := i;
              if (Count[j] <= 20) then
                data[j] := data[j] + i.ToString + ' '
              else
                Continue;
            end;
          1:
            begin
              if Odd(i) then
              begin
                inc(Count[j]);
                data[j] := data[j] + i.ToString + ' ';
              end;
            end;
          2:
            begin
              if Number.IsPrime then
              begin
                inc(Count[j]);
                data[j] := data[j] + i.ToString + ' ';
              end;
            end;
        end;
        if Count[j] = 20 then
          dec(left);
      end;
    if left = 0 then
      Break;
  end;

  while Count[0] < 100000 do
  begin
    inc(Num);
    if Number.Create(Num).IsBrazilian then
      inc(Count[0]);
  end;

  for i := 0 to 2 do
  begin
    Writeln(#10'First 20 ' + TextLabel[i] + ' Brazilian numbers:');
    Writeln(data[i]);
  end;

  Writeln('The 100,000th Brazilian number: ', Num);
  readln;
end.


(function () {
    'use strict'

    // Index of any closing brace matching the opening
    // brace at iPosn,
    // with the indices of any immediately-enclosed commas.
    function bracePair(tkns, iPosn, iNest, lstCommas) {
        if (iPosn >= tkns.length || iPosn < 0) return null;

        var t = tkns[iPosn],
            n = (t === '{') ? (
                iNest + 1
            ) : (t === '}' ? (
                iNest - 1
            ) : iNest),
            lst = (t === ',' && iNest === 1) ? (
                lstCommas.concat(iPosn)
            ) : lstCommas;

        return n ? bracePair(tkns, iPosn + 1, n, lst) : {
            close: iPosn,
            commas: lst
        };
    }

    // Parse of a SYNTAGM subtree
    function andTree(dctSofar, tkns) {
        if (!tkns.length) return [dctSofar, []];

        var dctParse = dctSofar ? dctSofar : {
                fn: and,
                args: []
            },

            head = tkns[0],
            tail = head ? tkns.slice(1) : [],

            dctBrace = head === '{' ? bracePair(
                tkns, 0, 0, []
            ) : null,

            lstOR = dctBrace && (
                dctBrace.close
            ) && dctBrace.commas.length ? (
                splitAt(dctBrace.close + 1, tkns)
            ) : null;

        return andTree({
            fn: and,
            args: dctParse.args.concat(
                lstOR ? (
                    orTree(dctParse, lstOR[0], dctBrace.commas)
                ) : head
            )
        }, lstOR ? (
            lstOR[1]
        ) : tail);
    }

    // Parse of a PARADIGM subtree
    function orTree(dctSofar, tkns, lstCommas) {
        if (!tkns.length) return [dctSofar, []];
        var iLast = lstCommas.length;

        return {
            fn: or,
            args: splitsAt(
                lstCommas, tkns
            ).map(function (x, i) {
                var ts = x.slice(
                    1, i === iLast ? (
                        -1
                    ) : void 0
                );

                return ts.length ? ts : [''];
            }).map(function (ts) {
                return ts.length > 1 ? (
                    andTree(null, ts)[0]
                ) : ts[0];
            })
        };
    }

    // List of unescaped braces and commas, and remaining strings
    function tokens(str) {
        // Filter function excludes empty splitting artefacts
        var toS = function (x) {
            return x.toString();
        };

        return str.split(/(\\\\)/).filter(toS).reduce(function (a, s) {
            return a.concat(s.charAt(0) === '\\' ? s : s.split(
                /(\\*[{,}])/
            ).filter(toS));
        }, []);
    }

    // PARSE TREE OPERATOR (1 of 2)
    // Each possible head * each possible tail
    function and(args) {
        var lng = args.length,
            head = lng ? args[0] : null,
            lstHead = "string" === typeof head ? (
                [head]
            ) : head;

        return lng ? (
            1 < lng ? lstHead.reduce(function (a, h) {
                return a.concat(
                    and(args.slice(1)).map(function (t) {
                        return h + t;
                    })
                );
            }, []) : lstHead
        ) : [];
    }

    // PARSE TREE OPERATOR (2 of 2)
    // Each option flattened
    function or(args) {
        return args.reduce(function (a, b) {
            return a.concat(b);
        }, []);
    }

    // One list split into two (first sublist length n)
    function splitAt(n, lst) {
        return n < lst.length + 1 ? [
            lst.slice(0, n), lst.slice(n)
        ] : [lst, []];
    }

    // One list split into several (sublist lengths [n])
    function splitsAt(lstN, lst) {
        return lstN.reduceRight(function (a, x) {
            return splitAt(x, a[0]).concat(a.slice(1));
        }, [lst]);
    }

    // Value of the parse tree
    function evaluated(e) {
        return typeof e === 'string' ? e :
            e.fn(e.args.map(evaluated));
    }

    // JSON prettyprint (for parse tree, token list etc)
    function pp(e) {
        return JSON.stringify(e, function (k, v) {
            return typeof v === 'function' ? (
                '[function ' + v.name + ']'
            ) : v;
        }, 2)
    }

    // ----------------------- MAIN ------------------------

    // s -> [s]
    function expansions(s) {
        // BRACE EXPRESSION PARSED
        var dctParse = andTree(null, tokens(s))[0];

        // ABSTRACT SYNTAX TREE LOGGED
        console.log(pp(dctParse));

        // AST EVALUATED TO LIST OF STRINGS
        return evaluated(dctParse);
    }

    // Sample expressions,
    // double-escaped for quotation in source code.
    var lstTests = [
        '~/{Downloads,Pictures}/*.{jpg,gif,png}',
        'It{{em,alic}iz,erat}e{d,}, please.',
        '{,{,gotta have{ ,\\, again\\, }}more }cowbell!',
        '{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}'
    ];

    // 1. Return each expression with an indented list of its expansions, while
    // 2. logging each parse tree to the console.log() stream

    return lstTests.map(function (s) {
        return s + '\n\n' + expansions(s).map(function (x) {
            return '   ' + x;
        }).join('\n');
    }).join('\n\n');

})();


function get_digit( num as uinteger, ps as uinteger ) as uinteger
    return (num mod 10^(ps+1))\10^ps
end function

function is_malformed( num as uinteger ) as boolean
    if num > 9876 then return true
    dim as uinteger i, j
    for i = 0 to 2
        for j = i+1 to 3
            if get_digit( num, j ) = get_digit( num, i ) then return true
        next j
    next i
    return false
end function

function make_number() as uinteger
    dim as uinteger num = 0
    while is_malformed(num)
        num = int(rnd*9877)
    wend
    return num
end function

randomize timer

dim as uinteger count=0, num=make_number(), guess=0
dim as uinteger cows, bulls, i, j

while guess <> num
    count += 1
    do
        print "Guess a number. "
        input guess
    loop while is_malformed(guess)

    cows = 0
    bulls = 0

    for i = 0 to 3
        for j = 0 to 3
            if get_digit( num, i ) = get_digit( guess, j ) then
                if i= j then bulls += 1
                if i<>j then cows  += 1
            end if
        next j
    next i
    print using "You scored # bulls and # cows."; bulls; cows
wend

print using "Correct. That took you ### guesses."; count


// Bulls and Cows - Written in Frink
println["Welcome to Bulls and Cows!"]

// Put 4 random digits into target array
digits = array[1 to 9]
target = new array
for i = 0 to 3
{
   [email protected] = digits.removeRandom[]
}

// Game variables
guessCount = 0
solved = 0

while solved == 0
{
   // Round variables
   bulls = 0
   cows = 0

   // Input guess from player
   guess = input["Guess a 4 digit number with numbers 1 to 9: "]

   // Valid Guess Tests. Set validGuess to 1. If any test fails it will be set to 0
   validGuess = 1
   // Test for exactly 4 digits
   if length[guess] != 4
   {
      println["$guess is invalid. Your guess must be 4 digits."]
      validGuess = 0
   }
   // Test for any characters not in 1 - 9 using regex
   if guess =~ %r/[^1-9]/
   {
      println["$guess is invalid. Your guess can only contain the digits 1 through 9."]
      validGuess = 0
   }
   // Check for duplicate digits in guess
   comboCheck = 1
   guessArr = charList[guess] // Split guess string into array of characters.
   guessArrCombos = guessArr.combinations[2] // Divide the array into all possible 2 digits combinations.
   for geussCombo = guessArrCombos
   {
      if [email protected] == [email protected] // If the two digits in the combinations are the same mark the comboCheck as failed.
         comboCheck = 0
   }
   if comboCheck == 0
   {
      println["$guess is invalid. Each digit in your guess should be unique."]
      validGuess = 0
   }

   // If all tests pass, continue with the game.
   if validGuess == 1
   {
      guessCount = guessCount + 1
      for i = 0 to 3
      {
         if parseInt[[email protected]] == [email protected] // Convert guess from string to int. Frink imports all input as strings.
         {
            bulls = bulls + 1
            next // If bull is found, skip the contains check.
         }
         if target.contains[parseInt[[email protected]]]
         {
            cows = cows + 1
         }
      }
      if bulls == 4
      {
         solved = 1 // Exit from While loop.
      } else
      {
         // Print the results of the guess. Formatting for plurals.
         bullsPlural = bulls == 1 ? "bull" : "bulls"
         cowsPlural = cows == 1 ? "cow" : "cows"
         println["Your guess of $guess had $bulls $bullsPlural and $cows $cowsPlural."]
      }
   }
}
guessPlural = guessCount == 1 ? "guess" : "guesses"
println["Congratulations! Your guess of $guess was correct! You solved this in $guessCount $guessPlural."]


fn main() {
    // Rust contains a single boolean type: `bool`, represented by the keywords `true` and `false`.
    // Expressions inside `if` and `while` statements must result in type `bool`. There is no
    // automatic conversion to the boolean type.

    let true_value = true;
    if true_value {
        println!("foo is {}.", true_value);
    }

    let false_value = false;
    if !false_value {
        println!("bar is {}.", false_value);
    }
}


v:BOOL := true; -- ok
i:INT := 1;
v := 1; -- wrong
if i then ... end; -- wrong: if requires a bool!
-- BUT
v := 1.bool; -- ok
if i.bool then ... end; -- ok


repeat with each item of [True, False, Yes, No, On, Off, ""]
	put it & " is " & (it is true)
end repeat


// Generate Brazilian sequence. Nigel Galloway: August 13th., 2019
let isBraz α=let mutable n,i,g=α,α+1,1 in (fun β->(while (i*g)<β do if g<α-1 then g<-g+1 else (n<-n*α; i<-n+i; g<-1)); β=i*g)

let Brazilian()=let rec fN n g=seq{if List.exists(fun α->α n) g then yield n
                                   yield! fN (n+1) ((isBraz (n-1))::g)}
                fN 4 [isBraz 2]


USING: combinators grouping io kernel lists lists.lazy math
math.parser math.primes.lists math.ranges namespaces prettyprint
prettyprint.config sequences ;

: (brazilian?) ( n -- ? )
    2 over 2 - [a,b] [ >base all-equal? ] with find nip >boolean ;

: brazilian? ( n -- ? )
    {
        { [ dup 7 < ] [ drop f ] }
        { [ dup even? ] [ drop t ] }
        [ (brazilian?) ]
    } cond ;

: .20-brazilians ( list -- )
    [ 20 ] dip [ brazilian? ] lfilter ltake list>array . ;

100 margin set
1 lfrom "First 20 Brazilian numbers:"
1 [ 2 + ] lfrom-by "First 20 odd Brazilian numbers:"
lprimes "First 20 prime Brazilian numbers:"
[ print .20-brazilians nl ] [email protected]


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

: same_digits? ( n b -- ? )
  2dup mod >r
  begin
    tuck / swap
    over 0 >
  while
    2dup mod [email protected] <> if
      2drop rdrop false exit
    then
  repeat
  2drop rdrop true ;

: brazilian? ( n -- ? )
  dup 7 < if drop false exit then
  dup 1 and 0= if drop true exit then
  dup 1- 2 do
    dup i same_digits? if
      unloop drop true exit
    then
  loop
  drop false ;

: next_prime ( n -- n )
  begin 2 + dup prime? until ;

: print_brazilian ( n1 n2 -- )
  >r 7
  begin
    [email protected] 0 >
  while
    dup brazilian? if
      dup .
      r> 1- >r
    then
    over 0= if
      next_prime
    else
      over +
    then
  repeat
  2drop rdrop cr ;

." First 20 Brazilian numbers:" cr
1 20 print_brazilian
cr

." First 20 odd Brazilian numbers:" cr
2 20 print_brazilian
cr

." First 20 prime Brazilian numbers:" cr
0 20 print_brazilian

bye


 function getitem(s, depth=0)
    out = [""]
    while s != ""
        c = s[1]
        if depth > 0 && (c == ',' || c == '}')
            return out, s
        elseif c == '{'
            x = getgroup(s[2:end], depth+1)
            if x != ""
                out, s = [a * b for a in out, b in x[1]], x[2]
                continue
            end
        elseif c == '\\' && length(s) > 1
            s, c = s[2:end], c * s[2]
        end
        out, s = [a * c for a in out], s[2:end]
    end
    return out, s
end

function getgroup(s, depth)
    out, comma = "", false
    while s != ""
        g, s = getitem(s, depth)
        if s == ""
            break
        end
        out = vcat([out...], [g...])
        if s[1] == '}'
            if comma
                return out, s[2:end]
            end
            return ["{" * a * "}" for a in out], s[2:end]
        end
        if s[1] == ','
            comma, s = true, s[2:end]
        end
    end
    return ""
end

const teststrings = [raw"~/{Downloads,Pictures}/*.{jpg,gif,png}",
                    raw"It{{em,alic}iz,erat}e{d,}, please.",
                    raw"{,{,gotta have{ ,\, again\, }}more }cowbell!",
                    raw"{}} some }{,{\\\\{ edge, edge} \,}{ cases, {here} \\\\\\\\\}'''"]

for s in teststrings
    println("\n", s, "\n--------------------------------------------")
    for ans in getitem(s)[1]
        println(ans)
    end
end


// version 1.1.2

object BraceExpansion {
    fun expand(s: String) = expandR("", s, "")

    private val r = Regex("""([\\]{2}|[\\][,}{])""")

    private fun expandR(pre: String, s: String, suf: String) {
        val noEscape = s.replace(r, "  ")
        var sb = StringBuilder("")
        var i1 = noEscape.indexOf('{')
        var i2 = 0

        outer@ while (i1 != -1) {
            sb = StringBuilder(s)
            var depth = 1
            i2 = i1 + 1
            while (i2 < s.length && depth > 0) {
                val c = noEscape[i2]

                if (c == '{') depth++
                else if (c == '}') depth--

                if (c == ',' && depth == 1) sb[i2] = '\u0000'
                else if (c == '}' && depth == 0 && sb.indexOf("\u0000") != -1) break@outer
                i2++
            }
            i1 = noEscape.indexOf('{', i1 + 1)
        }
        if (i1 == -1) {
            if (suf.isNotEmpty()) expandR(pre + s, suf, "")
            else println("$pre$s$suf")
        } else {
            for (m in sb.substring(i1 + 1, i2).split('\u0000')) {
                expandR(pre + s.substring(0, i1), m, s.substring(i2 + 1) + suf)
            }
        }
    }
}

fun main(args: Array<String>) {
    val strings = arrayOf(
        """~/{Downloads,Pictures}/*.{jpg,gif,png}""",
        """It{{em,alic}iz,erat}e{d,}, please.""",
        """{,{,gotta have{ ,\, again\, }}more }cowbell!""",
        """{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"""
    )
    for (s in strings) {
        println()
        BraceExpansion.expand(s)
    }
}


package main

import (
    "bufio"
    "bytes"
    "fmt"
    "math/rand"
    "os"
    "strings"
    "time"
)

func main() {
    fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`)
    // generate pattern
    pat := make([]byte, 4)
    rand.Seed(time.Now().Unix())
    r := rand.Perm(9)
    for i := range pat {
        pat[i] = '1' + byte(r[i])
    }

    // accept and score guesses
    valid := []byte("123456789")
guess:
    for in := bufio.NewReader(os.Stdin); ; {
        fmt.Print("Guess: ")
        guess, err := in.ReadString('\n')
        if err != nil {
            fmt.Println("\nSo, bye.")
            return
        }
        guess = strings.TrimSpace(guess)
        if len(guess) != 4 {
            // malformed:  not four characters
            fmt.Println("Please guess a four digit number.")
            continue
        }
        var cows, bulls int
        for ig, cg := range guess {
            if strings.IndexRune(guess[:ig], cg) >= 0 {
                // malformed:  repeated digit
                fmt.Printf("Repeated digit: %c\n", cg)
                continue guess
            }
            switch bytes.IndexByte(pat, byte(cg)) {
            case -1:
                if bytes.IndexByte(valid, byte(cg)) == -1 {
                    // malformed:  not a digit
                    fmt.Printf("Invalid digit: %c\n", cg)
                    continue guess
                }
            default: // I just think cows should go first
                cows++
            case ig:
                bulls++
            }
        }
        fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
        if bulls == 4 {
            fmt.Println("You got it.")
            return
        }
    }
}


!Constructs a sieve of Brazilian numbers from the definition.
!From the Algol W algorithm, somewhat "Fortranized"
      PROGRAM BRAZILIAN
      IMPLICIT NONE
!
! PARAMETER definitions
!
      INTEGER , PARAMETER  ::  MAX_NUMBER = 2000000 , NUMVARS = 20
!
! Local variables
!
      LOGICAL , DIMENSION(1:MAX_NUMBER)  ::  b
      INTEGER  ::  bcount
      INTEGER  ::  bpos
      CHARACTER(15)  ::  holder
      CHARACTER(100)  ::  outline
      LOGICAL , DIMENSION(1:MAX_NUMBER)  ::  p
!
!     find some Brazilian numbers - numbers N whose representation in some !
!     base B ( 1 < B < N-1 ) has all the same digits                       !
!     set b( 1 :: n ) to a sieve of Brazilian numbers where b( i ) is true   !
!     if i is Brazilian and false otherwise - n must be at least 8           !
!     sets p( 1 :: n ) to a sieve of primes up to n
      CALL BRAZILIANSIEVE(b , MAX_NUMBER)
      WRITE(6 , 34)"The first 20 Brazilian numbers:"
      bcount = 0
      outline = ''
      holder = ''
      bpos = 1
      DO WHILE ( bcount<NUMVARS )
         IF( b(bpos) )THEN
            bcount = bcount + 1
            WRITE(holder , *)bpos
            outline = TRIM(outline) // " " // ADJUSTL(holder)
         END IF
         bpos = bpos + 1
      END DO

      WRITE(6 , 34)outline
      WRITE(6 , 34)"The first 20 odd Brazilian numbers:"
      outline = ''
      holder = ''
      bcount = 0
      bpos = 1
      DO WHILE ( bcount<NUMVARS )
         IF( b(bpos) )THEN
            bcount = bcount + 1
            WRITE(holder , *)bpos
            outline = TRIM(outline) // " " // ADJUSTL(holder)
         END IF
         bpos = bpos + 2
      END DO
      WRITE(6 , 34)outline
      WRITE(6 , 34)"The first 20 prime Brazilian numbers:"
      CALL ERATOSTHENES(p , MAX_NUMBER)
      bcount = 0
      outline = ''
      holder = ''
      bpos = 1
      DO WHILE ( bcount<NUMVARS )
         IF( b(bpos) .AND. p(bpos) )THEN
            bcount = bcount + 1
            WRITE(holder , *)bpos
            outline = TRIM(outline) // " " // ADJUSTL(holder)
         END IF
         bpos = bpos + 1
      END DO
      WRITE(6 , 34)outline
      WRITE(6 , 34)"Various Brazilian numbers:"
      bcount = 0
      bpos = 1
      DO WHILE ( bcount<1000000 )
         IF( b(bpos) )THEN
            bcount = bcount + 1
            IF( (bcount==100) .OR. (bcount==1000) .OR. (bcount==10000) .OR.               &
              & (bcount==100000) .OR. (bcount==1000000) )WRITE(* , *)bcount ,             &
               &"th Brazilian number: " , bpos
         END IF
         bpos = bpos + 1
      END DO
      STOP
 34   FORMAT(/ , a)
      END PROGRAM BRAZILIAN
!
      SUBROUTINE BRAZILIANSIEVE(B , N)
      IMPLICIT NONE
!
! Dummy arguments
!
      INTEGER  ::  N
      LOGICAL , DIMENSION(*)  ::  B
      INTENT (IN) N
      INTENT (OUT) B
!
! Local variables
!
      INTEGER  ::  b11
      INTEGER  ::  base
      INTEGER  ::  bn
      INTEGER  ::  bnn
      INTEGER  ::  bpower
      INTEGER  ::  digit
      INTEGER  ::  i
      LOGICAL  ::  iseven
      INTEGER  ::  powermax
!
      iseven = .FALSE.
      B(1:6) = .FALSE.                 ! numbers below 7 are not Brazilian (see task notes)
      DO i = 7 , N
         B(i) = iseven
         iseven = .NOT.iseven
      END DO
      DO base = 2 , (N/2)
         b11 = base + 1
         bnn = b11
         DO digit = 3 , base - 1 , 2
            bnn = bnn + b11 + b11
            IF( bnn>N )EXIT
            B(bnn) = .TRUE.
         END DO
      END DO
      DO base = 2 , INT(SQRT(FLOAT(N)))
         powermax = HUGE(powermax)/base             ! avoid 32 bit     !
         IF( powermax>N )powermax = N               ! integer overflow !
         DO digit = 1 , base - 1 , 2
            bpower = base*base
            bn = digit*(bpower + base + 1)
            DO WHILE ( (bn<=N) .AND. (bpower<=powermax) )
               IF( bn<=N )B(bn) = .TRUE.
               bpower = bpower*base
               bn = bn + (digit*bpower)
            END DO
         END DO
      END DO
      RETURN
      END SUBROUTINE BRAZILIANSIEVE
!
      SUBROUTINE ERATOSTHENES(P , N)
      IMPLICIT NONE
!
! Dummy arguments
!
      INTEGER  ::  N
      LOGICAL , DIMENSION(*)  ::  P
      INTENT (IN) N
      INTENT (INOUT) P
!
! Local variables
!
      INTEGER  ::  i
      INTEGER  ::  ii
      LOGICAL  ::  oddeven
      INTEGER  ::  pr
!
      P(1) = .FALSE.
      P(2) = .TRUE.
      oddeven = .TRUE.
      DO i = 3 , N
         P(i) = oddeven
         oddeven = .NOT.oddeven
      END DO
      DO i = 2 , INT(SQRT(FLOAT(N)))
         ii = i + i
         IF( P(i) )THEN
            DO pr = i*i , N , ii
               P(pr) = .FALSE.
            END DO
         END IF
      END DO
      RETURN
      END SUBROUTINE ERATOSTHENES


local function wrapEachItem(items, prefix, suffix)
	local itemsWrapped = {}

	for i, item in ipairs(items) do
		itemsWrapped[i] = prefix .. item .. suffix
	end

	return itemsWrapped
end

local function getAllItemCombinationsConcatenated(aItems, bItems)
	local combinations = {}

	for _, a in ipairs(aItems) do
		for _, b in ipairs(bItems) do
			table.insert(combinations, a..b)
		end
	end

	return combinations
end

local getItems -- Forward declaration.

local function getGroup(s, pos, depth)
	local groupItems = {}
	local foundComma = false

	while pos <= #s do
		local items
		items, pos = getItems(s, pos, depth)
		if pos > #s then  break  end

		for _, item in ipairs(items) do
			table.insert(groupItems, item)
		end

		local c = s:sub(pos, pos)

		if c == "}" then -- Possibly end of group.
			if foundComma then  return groupItems, pos+1  end
			return wrapEachItem(groupItems, "{", "}"), pos+1 -- No group.

		elseif c == "," then
			foundComma, pos = true, pos+1
		end
	end

	return nil -- No group.
end

function getItems(s, pos, depth)
	local items = {""}

	while pos <= #s do
		local c = s:sub(pos, pos)

		if depth > 0 and (c == "," or c == "}") then -- End of item in surrounding group.
			return items, pos
		end

		local groupItems, nextPos = nil
		if c == "{" then -- Possibly start of a group.
			groupItems, nextPos = getGroup(s, pos+1, depth+1)
		end

		if groupItems then
			items, pos = getAllItemCombinationsConcatenated(items, groupItems), nextPos
		else
			if c == "\\" and pos < #s then -- Escaped character.
				pos = pos + 1
				c   = c .. s:sub(pos, pos)
			end
			items, pos = wrapEachItem(items, "", c), pos+1
		end
	end

	return items, pos
end

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

for test in tests:gmatch"[^\n]+" do
	print(test)
	for _, item in ipairs(getItems(test, 1, 0)) do
		print("\t"..item)
	end
	print()
end


#!/usr/bin/env golosh
----
This module is the Bulls and Cows game.
----
module Bullsandcows

import gololang.Decorators
import gololang.Functions
import gololang.IO
import java.util

function main = |args| {
  while true {
    let secret = create4RandomNumbers()
    println("Welcome to Bulls And Cows")
    while true {
      println("Please enter a 4 digit number")
      println("(with only the digits 1 to 9 and no repeated digits, for example 2537)")
      let guess = readln("guess: ")
      let result = validateGuess(guess)
      if result: isValid() {
        let bulls, cows = bullsAndOrCows(result: digits(), secret)
        if bulls is 4 {
          println("You win!")
          break
        }
        println("bulls: " + bulls)
        println("cows:  " + cows)
      } else {
        println(result: message())
      }
    }
  }
}

function create4RandomNumbers = {
  let numbers = vector[1, 2, 3, 4, 5, 6, 7, 8, 9]
  Collections.shuffle(numbers)
  let shuffled = numbers: subList(0, 4)
  return shuffled
}

union Result = {
  Valid = { digits }
  Invalid = { message }
}

@checkArguments(isString())
function validateGuess = |guess| {
  var digits = []
  try {
    let number = guess: toInt()
    digits = number: digits()
    if digits: exists(|d| -> d is 0) {
      return Result.Invalid("No zeroes please")
    }
    if digits: size() isnt 4  {
      return Result.Invalid("Four digits please")
    }
    let digitSet = set[ digit foreach digit in digits ]
    if digitSet: size() < digits: size() {
      return Result.Invalid("No duplicate numbers please")
    }
  } catch(e) {
    return Result.Invalid("Numbers only please")
  }
  return Result.Valid(digits)
}

let is4Vector = |arg| -> arg oftype java.util.List.class and arg: size() is 4

@checkArguments(is4Vector, is4Vector)
function bullsAndOrCows = |guess, secret| {
  var bulls = 0
  var cows = 0
  foreach i in [0..4] {
    let guessNum = guess: get(i)
    let secretNum = secret: get(i)
    if guessNum is secretNum {
      bulls = bulls + 1
    } else if secret: exists(|num| -> guessNum is num) {
      cows = cows + 1
    }
  }
  return [bulls, cows]
}

augment java.lang.Integer {

  function digits = |this| {
    var remaining = this
    let digits = vector[]
    while remaining > 0 {
      digits: prepend(remaining % 10)
      remaining = remaining / 10
    }
    return digits
  }
}


class BullsAndCows {
    static void main(args) {
        def inputReader = System.in.newReader()
        def numberGenerator = new Random()
        def targetValue
        while (targetValueIsInvalid(targetValue = numberGenerator.nextInt(9000) + 1000)) continue
        def targetStr = targetValue.toString()
        def guessed = false
        def guesses = 0
        while (!guessed) {
            def bulls = 0, cows = 0
            print 'Guess a 4-digit number with no duplicate digits: '
            def guess = inputReader.readLine()
            if (guess.length() != 4 || !guess.isInteger() || targetValueIsInvalid(guess.toInteger())) {
                continue
            }
            guesses++
            4.times {
                if (targetStr[it] == guess[it]) {
                    bulls++
                } else if (targetStr.contains(guess[it])) {
                    cows++
                }
            }
            if (bulls == 4) {
                guessed = true
            } else {
                println "$cows Cows and $bulls Bulls."
            }
        }
        println "You won after $guesses guesses!"
    }

    static targetValueIsInvalid(value) {
        def digitList = []
        while (value > 0) {
            if (digitList[value % 10] == 0 || digitList[value % 10]) {
                return true
            }
            digitList[value % 10] = true
            value = value.intdiv(10)
        }
        false
    }
}


Function sameDigits(Byval n As Integer, Byval b As Integer) As Boolean
    Dim f As Integer = n Mod b : n \= b
    While n > 0
        If n Mod b <> f Then Return False Else n \= b
    Wend
    Return True
End Function

Function isBrazilian(Byval n As Integer) As Boolean
    If n < 7 Then Return False
    If n Mod 2 = 0 Then Return True
    For b As Integer = 2 To n - 2
        If sameDigits(n, b) Then Return True
    Next b
    Return False
End Function

Function isPrime(Byval n As Integer) As Boolean
    If n < 2 Then Return False
    If n Mod 2 = 0 Then Return n = 2
    If n Mod 3 = 0 Then Return n = 3
    Dim d As Integer = 5
    While d * d <= n
        If n Mod d = 0 Then Return False Else d += 2
        If n Mod d = 0 Then Return False Else d += 4
    Wend
    Return True
End Function

Dim kind(2) As String ={"", "odd", "prime"}
For i As Integer = 0 To 2
    Print Using "First 20 & Brazilian numbers: "; kind(i)
    Dim Limit As Integer = 20, n As Integer = 7
    Do
        If isBrazilian(n) Then Print Using "& "; n; : Limit -= 1
        Select Case kind(i)
        Case "" : n += 1
        Case "odd" : n += 2
        Case "prime" : Do : n += 2 : Loop Until isPrime(n)
        End Select
    Loop While Limit > 0
Next i
Sleep


package main

import "fmt"

func sameDigits(n, b int) bool {
    f := n % b
    n /= b
    for n > 0 {
        if n%b != f {
            return false
        }
        n /= b
    }
    return true
}

func isBrazilian(n int) bool {
    if n < 7 {
        return false
    }
    if n%2 == 0 && n >= 8 {
        return true
    }
    for b := 2; b < n-1; b++ {
        if sameDigits(n, b) {
            return true
        }
    }
    return false
}

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func main() {
    kinds := []string{" ", " odd ", " prime "}
    for _, kind := range kinds {
        fmt.Printf("First 20%sBrazilian numbers:\n", kind)
        c := 0
        n := 7
        for {
            if isBrazilian(n) {
                fmt.Printf("%d ", n)
                c++
                if c == 20 {
                    fmt.Println("\n")
                    break
                }
            }
            switch kind {
            case " ":
                n++
            case " odd ":
                n += 2
            case " prime ":
                for {
                    n += 2
                    if isPrime(n) {
                        break
                    }
                }
            }
        }
    }

    n := 7
    for c := 0; c < 100000; n++ {
        if isBrazilian(n) {
            c++
        }
    }
    fmt.Println("The 100,000th Brazilian number:", n-1)
}


(*The strategy is to first capture all special sub-expressions and reformat them so they are semantically clear. The built in function Distribute could then do the work of creating the alternatives, but the order wouldn't match that given in the instructions (although as a set the alternatives would be correct). I'll take a more complicated route so as to follow the instructions exactly.*)

(*A few named constants for readability.*)
EscapeToken="\\";(*In Mathematica, backslash is an escape character when inputing a string, so we need to escape it.*)
LeftBraceToken="{";
RightBraceToken="}";

(*This basically sequesters escaped substrings so that they don't get matched during later processing.*)
CaptureEscapes[exp:{___String}]:=SequenceReplace[exp,{EscapeToken,x_}:>EscapeToken<>x];

(*Any remaining braces are un-escaped. I'm "unstringifying" them to more easily pick them out during later processing.*)
CaptureBraces[exp:{___String}]:=ReplaceAll[exp,{LeftBraceToken->LeftBrace,RightBraceToken->RightBrace}];

(*Building up trees for the braced expressions. Extra braces are just raw data, so transform them back to strings.*)
CaptureBraceTrees[exp:{(_String|LeftBrace|RightBrace)...}]:=ReplaceAll[FixedPoint[SequenceReplace[{LeftBrace,seq:(_String|_BraceTree)...,RightBrace}:>BraceTree[seq]],exp],{LeftBrace->LeftBraceToken,RightBrace->RightBraceToken}];

(*At thie point, we should have an expression with well-braced substructures representing potential alternatives. We must expand brace trees to alternatives in the correct order.*)
ExpandBraceTrees[exp:Expr[head___String,bt_BraceTree,tail___]]:=ReplaceAll[Thread[Expr[head,ToAlternatives[bt],tail]],alt_Alt:>[email protected]@alt];
ExpandBraceTrees[exp:Expr[___String]]:={exp};
ExpandBraceTrees[exps:{__Expr}]:=Catenate[ExpandBraceTrees/@exps];

(*If there are no commas, then it's a literal sub-expression. Otherwise, it's a set of alternatives.*)
ToAlternatives[bt_BraceTree]:={LeftBraceToken<>[email protected]@bt<>RightBraceToken}/;FreeQ[bt,","];
ToAlternatives[BraceTree[","]]=ToAlternatives[BraceTree["",",",""]];
ToAlternatives[bt:BraceTree[",",__]]:=ToAlternatives[Prepend[bt,""]];
ToAlternatives[bt:BraceTree[__,","]]:=ToAlternatives[Append[bt,""]];
ToAlternatives[bt_BraceTree]:[email protected]@@SequenceSplit[[email protected]@bt,{","}];

NormalizeExpression=Apply[Expr]@*[email protected]*[email protected]*[email protected]*Characters;

BraceExpand[str_String]:=ReplaceAll[FixedPoint[ExpandBraceTrees,NormalizeExpression[str]],Expr->StringJoin];

(*Data was stored in a local file.*)
BraceTestData=ReadList[FileNameJoin[{NotebookDirectory[],"BraceTestData.txt"}],String];BraceTestData//TableForm


proc expandBraces(str: string) =

  var
    escaped = false
    depth = 0
    bracePoints: seq[int]
    bracesToParse: seq[int]

  for idx, ch in str:
    case ch
    of '\\':
      escaped = not escaped
    of '{':
      inc depth
      if not escaped and depth == 1:
        bracePoints = @[idx]
    of ',':
      if not escaped and depth == 1:
        bracePoints &= idx
    of '}':
      if not escaped and depth == 1 and bracePoints.len >= 2:
        bracesToParse = bracePoints & idx
      dec depth
    else:
      discard
    if ch != '\\':
      escaped = false

  if bracesToParse.len > 0:
    let prefix = str[0..<bracesToParse[0]]
    let suffix = str[(bracesToParse[^1] + 1)..^1]
    for idx in 1..bracesToParse.high:
      let option = str[(bracesToParse[idx - 1] + 1)..(bracesToParse[idx] - 1)]
      expandBraces(prefix & option & suffix)

  else:
    echo "  ", str

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

when isMainModule:

  for str in ["It{{em,alic}iz,erat}e{d,}, please.",
              "~/{Downloads,Pictures}/*.{jpg,gif,png}",
              "{,{,gotta have{ ,\\, again\\, }}more }cowbell!",
              "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"]:
    echo "\nExpansions of \"", str, "\":"
    expandBraces(str)


sub brace_expand {
    my $input = shift;
    my @stack = ([my $current = ['']]);

    while ($input =~ /\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx) {
        if ($1 eq '{') {
            push @stack, [$current = ['']];
        }
        elsif ($1 eq ',' && @stack > 1) {
            push @{$stack[-1]}, ($current = ['']);
        }
        elsif ($1 eq '}' && @stack > 1) {
            my $group = pop @stack;
            $current = $stack[-1][-1];

            # handle the case of brace pairs without commas:
            @{$group->[0]} = map { "{$_}" } @{$group->[0]} if @$group == 1;

            @$current = map {
                my $c = $_;
                map { map { $c . $_ } @$_ } @$group;
            } @$current;
        }
        else { $_ .= $1 for @$current; }
    }

    # handle the case of missing closing braces:
    while (@stack > 1) {
        my $right = pop @{$stack[-1]};
        my $sep;
        if (@{$stack[-1]}) { $sep = ',' }
        else               { $sep = '{'; pop @stack }
        $current = $stack[-1][-1];
        @$current = map {
            my $c = $_;
            map { $c . $sep . $_ } @$right;
        } @$current;
    }

    return @$current;
}


import Data.List (partition, intersect, nub)
import Control.Monad
import System.Random (StdGen, getStdRandom, randomR)
import Text.Printf

numberOfDigits = 4 :: Int

main = bullsAndCows

bullsAndCows :: IO ()
bullsAndCows = do
    digits <- getStdRandom $ pick numberOfDigits ['1' .. '9']
    putStrLn "Guess away!"
    loop digits

  where loop digits = do
            input <- getLine
            if okay input
              then
                  let (bulls, cows) = score digits input in
                  if bulls == numberOfDigits then
                      putStrLn "You win!"
                  else do
                      printf "%d bulls, %d cows.\n" bulls cows
                      loop digits
              else do
                  putStrLn "Malformed guess; try again."
                  loop digits

        okay :: String -> Bool
        okay input =
            length input == numberOfDigits &&
            input == nub input &&
            all legalchar input
          where legalchar c = '1' <= c && c <= '9'

        score :: String -> String -> (Int, Int)
        score secret guess = (length bulls, cows)
          where (bulls, nonbulls) = partition (uncurry (==)) $
                    zip secret guess
                cows = length $ uncurry intersect $ unzip nonbulls

pick :: Int -> [a] -> StdGen -> ([a], StdGen)
{- Randomly selects items from a list without replacement. -}
pick n l g = f n l g (length l - 1) []
  where  f 0 _ g _   ps = (ps, g)
         f n l g max ps =
             f (n - 1) (left ++ right) g' (max - 1) (picked : ps)
          where (i, g') = randomR (0, max) g
                (left, picked : right) = splitAt i l


% if {""} then {puts true} else {puts false}
expected boolean value but got ""


if
  echo 'Looking for file'  # This is the evaluation block
  test -e foobar.fil       # The exit code from this statement determines whether the branch runs
then
  echo 'The file exists'   # This is the optional branch
  echo 'I am going to delete it'
  rm foobar.fil
fi


-- demo\rosetta\Brace_expansion.exw
with javascript_semantics
function pair(sequence stems, sequence brest)
    sequence res = {}
    for i=1 to length(stems) do
        for j=1 to length(brest) do
            res = append(res,stems[i]&brest[j])
        end for
    end for
    return res
end function

function brarse(string s)
    integer idx = 1
    while idx<=length(s) do
        integer ch = s[idx]
        if ch='{' then
            sequence alts = {idx}
            idx += 1
            integer l0 = idx
            bool nest = false, bl0 = false
            integer level = 1
            while idx<=length(s) do
                switch s[idx] do
                    case '{': level += 1
                              nest = true
                    case '}': level -= 1
                              bl0 = (level=0)
                    case ',': if level=1 then
                                alts = append(alts,idx)
                              end if
                    case '\\': idx += 1
                end switch
                if bl0 then exit end if
                idx += 1
            end while
            if length(alts)>1 and level=0 then
                alts &= idx
                sequence stems = {}
                string stem = s[1..alts[1]-1]
                for i=2 to length(alts) do
                    string rest = s[alts[i-1]+1..alts[i]-1]
                    if nest then
                        sequence inners = brarse(rest)
                        for j=1 to length(inners) do
                            stems = append(stems,stem&inners[j])
                        end for
                    else
                        stems = append(stems,stem&rest)
                    end if
                end for
                return pair(stems,brarse(s[idx+1..$]))
            elsif nest then
                return pair({s[1..l0-1]},brarse(s[l0..$]))
            end if
        end if
        idx += 1
    end while
    return {s}
end function

-- (since ? and pp() add their own backslash escapes:)
procedure edump(sequence x)
    for i=1 to length(x) do
        printf(1,"%s\n",{x[i]})
    end for
end procedure

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


(import random)

(def +size+ 4)
(def +digits+ "123456789")
(def +secret+ (random.sample +digits+ +size+))

(while True
  (while True
    (setv guess (list (distinct (raw-input "Enter a guess: "))))
    (when (and
        (= (len guess) +size+)
        (all (map (fn [c] (in c +digits+)) guess)))
      (break))
    (print "Malformed guess; try again"))
  (setv bulls 0)
  (setv cows 0)
  (for [i (range +size+)] (cond
    [(= (get guess i) (get +secret+ i)) (setv bulls (inc bulls))]
    [(in (get guess i) +secret+) (setv cows (inc cows))]))
  (when (= bulls +size+)
    (break))
  (print (.format "{} bull{}, {} cows"
    bulls (if (= bulls 1) "" "s")
    cows (if (= cows 1) "" "s"))))

(print "A winner is you!")


Dim a As Integer
Dim b As Boolean
Debug.Print b
a = b
Debug.Print a
b = True
Debug.Print b
a = b
Debug.Print a


a = True
b = False
Randomize Timer
x = Int(Rnd * 2) <> 0
y = Int(Rnd * 2) = 0
MsgBox a & " " & b & " " & x & " " & y


if "foo"
    echo "true"
else
    echo "false"
endif


// Boolean Value, in V
// Tectonics: v run boolean-value.v
module main

// V bool type, with values true or false are the V booleans.
// true and false are V keywords, and display as true/false
// Numeric values are not booleans in V, 0 is not boolean false
pub fn main() {
    t := true
    f := false

    if t { println(t) }

    // this code would fail to compile
    // if 1 { println(t) }

    if 0 == 1 { println("bad result") } else { println(f) }
}


import Data.Numbers.Primes (primes)

isBrazil :: Int -> Bool
isBrazil n = 7 <= n && (even n || any (monoDigit n) [2 .. n - 2])

monoDigit :: Int -> Int -> Bool
monoDigit n b =
  let (q, d) = quotRem n b
  in d ==
     snd
       (until
          (uncurry (flip ((||) . (d /=)) . (0 ==)))
          ((`quotRem` b) . fst)
          (q, d))

main :: IO ()
main =
  mapM_
    (\(s, xs) ->
        (putStrLn . concat)
          [ "First 20 "
          , s
          , " Brazilians:\n"
          , show . take 20 $ filter isBrazil xs
          , "\n"
          ])
    [([], [1 ..]), ("odd", [1,3 ..]), ("prime", primes)]


theory Brazilian
imports Main
begin

function (sequential) base :: "nat ⇒ nat ⇒ nat list" where
  "base n 0 = undefined"
| "base n (Suc 0) = replicate n 1"
| "base n b = (if n < b then [n]
               else (base (n div b) b) @ [n mod b]
              )"
  by pat_completeness auto
termination base
  apply(relation "measure (λ(n,b). n div b)", simp)
  using div_greater_zero_iff by auto

lemma base_simps:
  "b > 1 ⟹ base n b = (if n < b then [n] else base (n div b) b @ [n mod b])"
  by (metis One_nat_def base.elims nat_neq_iff not_less_zero)

lemma "base 123 10 = [1, 2, 3]"
  and "base 65536 2 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"
  and "base 65535 2 =    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]"
  and "base 123 100 = [1, 23]"
  and "base 69 100 = [69]"
  and "base 255 16 = [15, 15]"
  by(simp add: base_simps)+

lemma "base 5 1 = [1, 1, 1, 1, 1]"
  by (simp add: eval_nat_numeral(3) numeral_Bit0)

lemma base_2_numbers: "a < b ⟹ c < b ⟹ a > 0 ⟹ base (a * b + c) b = [a, c]"
  apply(simp add: base_simps)
  using mult_eq_if by auto

lemma base_half_minus_one: "even n ⟹ n ≥ 8 ⟹ base n (n div 2 - 1) = [2, 2]"
proof -
  assume "even n" and "n ≥ 8"
  have n: "(2 * (n div 2 - 1) + 2) = n"
    using ‹n ≥ 8› ‹even n› add.commute dvd_mult_div_cancel le_0_eq by auto
  from ‹n ≥ 8› base_2_numbers[where b="n div 2 - 1" and a=2 and c=2] have
    "base (2 * (n div 2 - 1) + 2) (n div 2 - 1) = [2, 2]" by simp
  with n show ?thesis by simp
qed

lemma base_rs_numbers: "r > 0 ⟹ s - 1 > r ⟹ base (r*s) (s - 1) = [r, r]"
proof -
  assume "r > 0" and "s - 1 > r"
  from ‹s - 1 > r› have "r*s = r*(s - 1) + r"
    by (metis add.commute gr_implies_not0 less_diff_conv mult.commute mult_eq_if)
  from base_2_numbers[where a=r and b="s - 1" and c=r] have
    "s - 1 > r ⟹ 0 < r ⟹ base (r * (s - 1) + r) (s - 1) = [r, r]" .
  with ‹s - 1 > r› ‹r > 0› have "base (r * (s - 1) + r) (s - 1) = [r, r]" by(simp)
  with ‹r * s = r * (s - 1) + r› show "base (r*s) (s - 1) = [r, r]" by (simp)
qed

definition all_equal :: "nat list ⇒ bool" where
  "all_equal xs ≡ ∀x∈set xs. ∀y∈set xs. x = y"

lemma all_equal_alt:
  "all_equal xs ⟷ replicate (length xs) (hd xs) = xs"
  unfolding all_equal_def
  apply(induction xs)
   apply(simp)
  apply(simp)
  by (metis in_set_replicate replicate_eqI)

definition brazilian :: "nat set" where
  "brazilian ≡ {n. ∃b. 1 < b ∧ Suc b < n ∧ all_equal (base n b)}"

lemma "0 ∉ brazilian"
  and "1 ∉ brazilian"
  and "2 ∉ brazilian"
  and "3 ∉ brazilian"
  by (simp add: brazilian_def)+

lemma "4 ∉ brazilian"
  apply (simp add: brazilian_def all_equal_def)
  apply(intro allI impI)
  apply(case_tac "b = 1", simp)
  apply(case_tac "b = 2", simp add: base_simps, blast)
  by(simp)

lemma "5 ∉ brazilian"
  apply (simp add: brazilian_def all_equal_def)
  apply(intro allI impI)
  apply(case_tac "b = 1", simp)
  apply(case_tac "b = 2", simp add: base_simps, blast)
  apply(case_tac "b = 3", simp add: base_simps, blast)
  by(simp)

lemma "6 ∉ brazilian"
  apply (simp add: brazilian_def all_equal_def)
  apply(intro allI impI)
  apply(case_tac "b = 1", simp)
  apply(case_tac "b = 2", simp add: base_simps, blast)
  apply(case_tac "b = 3", simp add: base_simps, blast)
  apply(case_tac "b = 4", simp add: base_simps, blast)
  by(simp)

lemma "7 ∈ brazilian"
  apply(simp add: brazilian_def)
  apply(rule exI[where x=2])
  by(simp add: base_simps all_equal_def)

lemma "8 ∈ brazilian"
  apply(simp add: brazilian_def)
  apply(rule exI[where x=3])
  by(simp add: base_simps all_equal_def)

lemma "9 ∉ brazilian"
  apply (simp add: brazilian_def all_equal_def)
  apply(intro allI impI)
  apply(case_tac "b = 1", simp)
  apply(case_tac "b = 2", simp add: base_simps, blast)
  apply(case_tac "b = 3", simp add: base_simps, blast)
  apply(case_tac "b = 4", simp add: base_simps, blast)
  apply(case_tac "b = 5", simp add: base_simps, blast)
  apply(case_tac "b = 6", simp add: base_simps, blast)
  apply(case_tac "b = 7", simp add: base_simps, blast)
  by(simp)

theorem "even n ⟹ n ≥ 8 ⟹ n ∈ brazilian"
  apply(simp add: brazilian_def)
  apply(rule_tac x="n div 2 - 1" in exI)
  by(simp add: base_half_minus_one[simplified] all_equal_def)

(*
The problem description on Rosettacode was broken.
Fortunately, we found the error when proving it correct with Isabelle.
Rosettacode claimed:
"all integers, that factor decomposition is R*S >= 8, with S+1 > R,
 are Brazilian because R*S = R(S-1) + R, which is RR in base S-1"
This is wrong. Here are some counterexamples:

r = 3
s = 3
r*s = 9 ≥ 8
s+1 = 4 > 3 = r
But (s*r) = 9 ∉ brazilian

The correct precondition would be s-1>r instead of s+1>r.

But this is not enough.

Also, r > 1 is needed additionally, because
r=1
s=9
r*s = 9 ≥ 8
s+1 = 10 > 1 = r or s-1 = 8 > 1 = r
But (s*r) = 9 ∉ brazilian

Doing the proof, we also learn that the precondition r*s ≥ 8 is not required.
*)
theorem "r > 1 ⟹ s-1 > r ⟹ r*s ∈ brazilian"
  apply(simp add: brazilian_def)
  apply(rule_tac x="s - 1" in exI)
  apply(subst base_rs_numbers[of r s])
    using not_numeral_le_zero apply fastforce
   apply(simp; fail)
    by(simp add: all_equal_def)

fun is_brazilian_for_base :: "nat ⇒ nat ⇒ bool" where
  "is_brazilian_for_base n 0 ⟷ False"
| "is_brazilian_for_base n (Suc 0) ⟷ False"
| "is_brazilian_for_base n (Suc b) ⟷ all_equal (base n (Suc b)) ∨ is_brazilian_for_base n b"

lemma "is_brazilian_for_base 7 2" and "is_brazilian_for_base 8 3" by code_simp+

lemma is_brazilian_for_base_Suc_simps:
  "is_brazilian_for_base n (Suc b) ⟷ b ≠ 0 ∧ (all_equal (base n (Suc b)) ∨ is_brazilian_for_base n b)"
  by(cases b)(simp)+

lemma is_brazilian_for_base:
  "is_brazilian_for_base n b ⟷ (∃w ∈ {2..b}. all_equal (base n w))"
proof(induction b)
  case 0
  show "is_brazilian_for_base n 0 = (∃w∈{2..0}. all_equal (base n w))" by simp
next
  case (Suc b)
  assume IH: "is_brazilian_for_base n b = (∃w∈{2..b}. all_equal (base n w))"
  show "is_brazilian_for_base n (Suc b) = (∃w∈{2..Suc b}. all_equal (base n w))"
    apply(simp add: is_brazilian_for_base_Suc_simps IH)
    using le_Suc_eq by fastforce
qed

lemma is_brazilian_for_base_is:
  "Suc (Suc n) ∈ brazilian ⟷ is_brazilian_for_base (Suc (Suc n)) n"
  apply(simp add: brazilian_def is_brazilian_for_base)
  using less_Suc_eq_le by force

definition brazilian_executable :: "nat ⇒ bool" where
  "brazilian_executable n ≡ n > 1 ∧ is_brazilian_for_base n (n - 2)"

lemma brazilian_executable[code_unfold]:
  "n ∈ brazilian ⟷ brazilian_executable n"
  apply(simp add: brazilian_executable_def)
  apply(cases "n = 0 ∨ n = 1")
   apply(simp add: brazilian_def)
   apply(blast)
  apply(simp)
  apply(case_tac n, simp, simp, rename_tac n2)
  apply(case_tac n2, simp, simp, rename_tac n3)
  apply(subst is_brazilian_for_base_is[symmetric])
  apply(simp)
  done

text‹
In Isabelle/HOl, functions must be total, i.e. they must terminate.
Therefore, we cannot simply write a function which enumerates the infinite
set of natural numbers and stops when we found 20 Brazilian numbers,
since it is not guaranteed that 20 Brazilian numbers exist and that the
function will terminate.
We could prove that and then write that function, but here is the lazy solution:
›

lemma "[n ← upt 0 34. n ∈ brazilian] =
       [7,8,10,12,13,14,15,16,18,20,21,22,24,26,27,28,30,31,32,33]"
  by(code_simp)
lemma "[n ← upt 0 80. odd n ∧ n ∈ brazilian] =
       [7,13,15,21,27,31,33,35,39,43,45,51,55,57,63,65,69,73,75,77]"
  by code_simp

(*TODO: the first 20 prime Brazilian numbers*)

end


function getitem($s,$depth=0) {
    $out = [''];
    while ($s) {
        $c = $s[0];
        if ($depth && ($c == ',' || $c == '}')) {
            return [$out, $s];
        }
        if ($c == '{') {
            $x = getgroup(substr($s, 1), $depth + 1);
            if($x) {
                $tmp = [];
                foreach($out as $a) {
                    foreach($x[0] as $b) {
                        $tmp[] = $a . $b;
                    }
                }
                $out = $tmp;
                $s = $x[1];
                continue;
            }
        }
        if ($c == '\\' && strlen($s) > 1) {
            list($s, $c) = [substr($s, 1), ($c . $s[1])];
        }

        $tmp = [];
        foreach($out as $a) {
            $tmp[] = $a . $c;
        }
        $out = $tmp;
        $s = substr($s, 1);

    }
    return [$out, $s];
}
function getgroup($s,$depth) {
    list($out, $comma) = [[], false];
    while ($s) {
        list($g, $s) = getitem($s, $depth);
        if (!$s) {
            break;
        }
        $out = array_merge($out, $g);
        if ($s[0] == '}') {
            if ($comma) {
                return [$out, substr($s, 1)];
            }

            $tmp = [];
            foreach($out as $a) {
                $tmp[] = '{' . $a . '}';
            }
            return [$tmp, substr($s, 1)];
        }
        if ($s[0] == ',') {
            list($comma, $s) = [true, substr($s, 1)];
        }
    }
    return null;
}

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

foreach( explode("\n", $lines) as $line ) {
    printf("\n%s\n", $line);
    foreach( getitem($line)[0] as $expansion ) {
        printf("    %s\n", $expansion);
    }
}


procedure main()
    digits := "123456789"
    every !digits :=: ?digits
    num := digits[1+:4]
    repeat if score(num, getGuess(num)) then break
    write("Good job.")
end

procedure getGuess(num)
    repeat {
        writes("Enter a guess: ")
        guess := read() | stop("Quitter!")
        if *(guess ** '123456789') == *num then return guess
        write("Malformed guess: ",guess,". Try again.")
        }
end

procedure score(num, guess)
    bulls := 0
    cows := *(num ** guess)
    every (num[i := 1 to *num] == guess[i], bulls +:= 1, cows -:= 1)
    write("\t",bulls," bulls and ",cows," cows")
    return (bulls = *num)
end


let io => import 'io';
let ex => switch 'this is irrelevant for this example' {
  false => 'This is, obviously, not returned.';
  'a string' => 'This is also not returned.';
  true => 'This is returned.';
};
ex -- io.writeln io.stdout;


var embed = true
System.printAll([embed, ", ", !embed, ", ", "Is Wren embeddable? " + embed.toString])


<xsl:if test="true() or false()">
  True and false are returned by built-in XPath functions.
</xsl:if>
<xsl:if test="@myAttribute='true'">
  Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans.
</xsl:if>
<xsl:if test="@myAttribute or not($nodeSet)">
  Test an attribute for its presence (empty or not), or whether a node set is empty.
</xsl:if>


(de braceExpand (Str)
   (let Lst
      (make
         (for (Lst (chop Str)  Lst)
            (case (pop 'Lst)
               ("\\" (link (pop 'Lst)))
               ("{"
                  (recur ()
                     (let L
                        (make
                           (while
                              (case (pop 'Lst)
                                 ("\\" (link (pop 'Lst)) Lst)
                                 ("{" (recurse) Lst)
                                 ("}" NIL)
                                 ("," (link 0) Lst)  # Replace commata with '0'
                                 (T (link @) Lst) ) ) )
                        (if (= "}" @)  # Was closing brace
                           (if (member 0 L)  # Has comma(ta)
                              (link (split L 0))
                              (chain (list "{") (replace L 0 ",") (list "}")))
                           (chain (list "{") (replace L 0 ",")) ) ) ) )
               (T (link @)) ) ) )
      (recur (Lst)
         (ifn (find pair Lst)
            (list (pack Lst))
            (let R (recurse (cdr Lst))
               (mapcan
                  '((A) (mapcar '((B) (pack A B)) R))
                  (if (pair (car Lst))
                     (mapcan recurse (car Lst))
                     (list (car Lst)) ) ) ) ) ) ) )


function Expand-Braces ( [string]$String )
    {
    $Escaped = $False
    $Stack = New-Object System.Collections.Stack
    $ClosedBraces = $BracesToParse = $Null

    ForEach ( $i in 0..($String.Length-1) )
        {
        Switch ( $String[$i] )
            {
            '\' {
                $Escaped = -not $Escaped
                break
                }

            '{' {
                If ( -not $Escaped ) { $Stack.Push( [pscustomobject]@{ Delimiters = @( $i ) } ) }
                }

            ',' {
                If ( -not $Escaped -and $Stack.Count ) { $Stack.Peek().Delimiters += $i }
                }

            '}' {
                If ( -not $Escaped -and $Stack.Count )
                    {
                    $Stack.Peek().Delimiters += $i
                    $ClosedBraces = $Stack.Pop()
                    If ( $ClosedBraces.Delimiters.Count -gt 2 )
                        {
                        $BracesToParse = $ClosedBraces
                        }
                    }
                }

            default { $Escaped = $False }
            }
        }

        If ( $BracesToParse )
            {
            $Start = $String.Substring( 0, $BracesToParse.Delimiters[0] )
            $End   = $String.Substring( $BracesToParse.Delimiters[-1] + 1 )

            ForEach ( $i in 0..($BracesToParse.Delimiters.Count-2) )
                {
                $Option = $String.Substring( $BracesToParse.Delimiters[$i] + 1, $BracesToParse.Delimiters[$i+1] - $BracesToParse.Delimiters[$i] - 1 )
                Expand-Braces ( $Start + $Option + $End )
                }
            }
        Else
            {
            $String
            }
    }


require 'misc'

plural=: conjunction define
 (":m),' ',n,'s'#~1~:m
)

bullcow=:monad define
  number=. 1+4?9
  whilst. -.guess-:number do.
    guess=. 0 "."0 prompt 'Guess my number: '
    if. (4~:#guess)+.(4~:#~.guess)+.0 e.guess e.1+i.9 do.
      if. 0=#guess do.
        smoutput 'Giving up.'
        return.
      end.
      smoutput 'Guesses must be four different non-zero digits'
      continue.
    end.
    bulls=. +/guess=number
    cows=. (+/guess e.number)-bulls
    smoutput bulls plural 'bull',' and ',cows plural 'cow','.'
  end.
  smoutput 'you win'
)


import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class BullsAndCows{
	public static void main(String[] args){
		Random gen= new Random();
		int target;
		while(hasDupes(target= (gen.nextInt(9000) + 1000)));
		String targetStr = target +"";
		boolean guessed = false;
		Scanner input = new Scanner(System.in);
		int guesses = 0;
		do{
			int bulls = 0;
			int cows = 0;
			System.out.print("Guess a 4-digit number with no duplicate digits: ");
			int guess;
			try{
				guess = input.nextInt();
				if(hasDupes(guess) || guess < 1000) continue;
			}catch(InputMismatchException e){
				continue;
			}
			guesses++;
			String guessStr = guess + "";
			for(int i= 0;i < 4;i++){
				if(guessStr.charAt(i) == targetStr.charAt(i)){
					bulls++;
				}else if(targetStr.contains(guessStr.charAt(i)+"")){
					cows++;
				}
			}
			if(bulls == 4){
				guessed = true;
			}else{
				System.out.println(cows+" Cows and "+bulls+" Bulls.");
			}
		}while(!guessed);
		System.out.println("You won after "+guesses+" guesses!");
	}

	public static boolean hasDupes(int num){
		boolean[] digs = new boolean[10];
		while(num > 0){
			if(digs[num%10]) return true;
			digs[num%10] = true;
			num/= 10;
		}
		return false;
	}
}


var
	a,b,c: boolean;
begin
	a := false;
	b := true;
	c := 1 > 2;
...


# Output: a stream of digits, least significant digit first
def to_base($base):
  def butlast(s):
    label $out
    | foreach (s,null) as $x ({};
        if $x == null then break $out else .emit = .prev | .prev = $x end;
        select(.emit).emit);

  if . == 0 then 0
  else butlast(recurse( if . == 0 then empty else ./$base | floor end ) % $base)
  end ;

def sameDigits($n; $b):
  ($n % $b) as $f
  | all( ($n | to_base($b)); . == $f)  ;

def isBrazilian:
  . as $n
  | if . < 7 then false
    elif (.%2 == 0 and . >= 8) then true
    else any(range(2; $n-1); sameDigits($n; .) )
    end;

def brazilian_numbers($m; $n; $step):
  range($m; $n; $step)
  | select(isBrazilian);

def task($n):
  "First \($n) Brazilian numbers:",
   limit($n; brazilian_numbers(7; infinite; 1)),
  "First \($n) odd Brazilian numbers:",
   limit($n; brazilian_numbers(7; infinite; 2)),
  "First \($n) prime Brazilian numbers:",
   limit($n; brazilian_numbers(7; infinite; 2) | select(is_prime)) ;

task(20)


using Primes, Lazy

function samedigits(n, b)
    n, f = divrem(n, b)
    while n > 0
        n, f2 = divrem(n, b)
        if f2 != f
            return false
        end
    end
    true
end

isbrazilian(n) = n >= 7 && (iseven(n) || any(b -> samedigits(n, b), 2:n-2))
brazilians = filter(isbrazilian, Lazy.range())
oddbrazilians = filter(n -> isodd(n) && isbrazilian(n), Lazy.range())
primebrazilians = filter(n -> isprime(n) && isbrazilian(n), Lazy.range())

println("The first 20 Brazilian numbers are: ", take(20, brazilians))

println("The first 20 odd Brazilian numbers are: ", take(20, oddbrazilians))

println("The first 20 prime Brazilian numbers are: ", take(20, primebrazilians))


fun sameDigits(n: Int, b: Int): Boolean {
    var n2 = n
    val f = n % b
    while (true) {
        n2 /= b
        if (n2 > 0) {
            if (n2 % b != f) {
                return false
            }
        } else {
            break
        }
    }
    return true
}

fun isBrazilian(n: Int): Boolean {
    if (n < 7) return false
    if (n % 2 == 0) return true
    for (b in 2 until n - 1) {
        if (sameDigits(n, b)) {
            return true
        }
    }
    return false
}

fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2
    if (n % 3 == 0) return n == 3
    var d = 5
    while (d * d <= n) {
        if (n % d == 0) return false
        d += 2
        if (n % d == 0) return false
        d += 4
    }
    return true
}

fun main() {
    val bigLim = 99999
    val limit = 20
    for (kind in ",odd ,prime".split(',')) {
        var quiet = false
        println("First $limit ${kind}Brazilian numbers:")
        var c = 0
        var n = 7
        while (c < bigLim) {
            if (isBrazilian(n)) {
                if (!quiet) print("%,d ".format(n))
                if (++c == limit) {
                    print("\n\n")
                    quiet = true
                }
            }
            if (quiet && kind != "") continue
            when (kind) {
                "" -> n++
                "odd " -> n += 2
                "prime" -> {
                    while (true) {
                        n += 2
                        if (isPrime(n)) break
                    }
                }
            }
        }
        if (kind == "") println("The %,dth Brazilian number is: %,d".format(bigLim + 1, n))
    }
}