BEGIN
    INTEGER WIDTH, YEAR;
    INTEGER COLS, LEAD, GAP;
    TEXT ARRAY WDAYS(0:6);
    CLASS MONTH(MNAME); TEXT MNAME;
    BEGIN INTEGER DAYS, START_WDAY, AT_POS;
    END MONTH;
    REF(MONTH) ARRAY MONTHS(0:11);
    WIDTH := 80; YEAR := 1969;

    BEGIN
        TEXT T;
        INTEGER I, M;
        FOR T :- "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" DO BEGIN
            WDAYS(I) :- T; I := I+1;
        END;
        I := 0;
        FOR T :- "January", "February", "March",
                 "April", "May", "June",
                 "July", "August", "September",
                 "October", "November", "December" DO BEGIN
            MONTHS(I) :- NEW MONTH(T); I := I+1;
        END;
        I := 0;
        FOR M := 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 DO BEGIN
            MONTHS(I).DAYS := M; I := I+1;
        END;
    END;

    BEGIN

        PROCEDURE SPACE(N); INTEGER N;
        BEGIN
            WHILE N > 0 DO BEGIN
                OUTCHAR(' '); N := N-1;
            END;
        END SPACE;

        PROCEDURE INIT_MONTHS;
        BEGIN
            INTEGER I;

            IF MOD(YEAR,4) = 0 AND MOD(YEAR,100) <> 0 OR MOD(YEAR,400) = 0 THEN
                MONTHS(1).DAYS := 29;

            YEAR := YEAR-1;
            MONTHS(0).START_WDAY
                := MOD(YEAR * 365 + YEAR//4 - YEAR//100 + YEAR//400 + 1, 7);

            FOR I := 1 STEP 1 UNTIL 12-1 DO
                MONTHS(I).START_WDAY :=
                    MOD(MONTHS(I-1).START_WDAY + MONTHS(I-1).DAYS, 7);

            COLS := (WIDTH + 2) // 22;
            WHILE MOD(12,COLS) <> 0 DO
                COLS := COLS-1;
            GAP := IF COLS - 1 <> 0 THEN (WIDTH - 20 * COLS) // (COLS - 1) ELSE 0;
            IF GAP > 4 THEN
                GAP := 4;
            LEAD := (WIDTH - (20 + GAP) * COLS + GAP + 1) // 2;
            YEAR := YEAR+1;
        END INIT_MONTHS;

        PROCEDURE PRINT_ROW(ROW); INTEGER ROW;
        BEGIN
            INTEGER C, I, FROM, UP_TO;
            INTEGER PROCEDURE PREINCREMENT(I); NAME I; INTEGER I;
            BEGIN I := I+1; PREINCREMENT := I;
            END PREINCREMENT;
            INTEGER PROCEDURE POSTINCREMENT(I); NAME I; INTEGER I;
            BEGIN POSTINCREMENT := I; I := I+1;
            END POSTINCREMENT;
            FROM := ROW * COLS;
            UP_TO := FROM + COLS;
            SPACE(LEAD);
            FOR C := FROM STEP 1 UNTIL UP_TO-1 DO BEGIN
                I := MONTHS(C).MNAME.LENGTH;
                SPACE((20 - I)//2);
                OUTTEXT(MONTHS(C).MNAME);
                SPACE(20 - I - (20 - I)//2 + (IF C = UP_TO - 1 THEN 0 ELSE GAP));
            END;
            OUTIMAGE;

            SPACE(LEAD);
            FOR C := FROM STEP 1 UNTIL UP_TO-1 DO BEGIN
                FOR I := 0 STEP 1 UNTIL 7-1 DO BEGIN
                    OUTTEXT(WDAYS(I)); OUTTEXT(IF I = 6 THEN "" ELSE " ");
                END;
                IF C < UP_TO - 1 THEN
                    SPACE(GAP)
                ELSE
                    OUTIMAGE;
            END;

            WHILE TRUE DO BEGIN
                FOR C := FROM STEP 1 UNTIL UP_TO-1 DO
                    IF MONTHS(C).AT_POS < MONTHS(C).DAYS THEN
                        GO TO IBREAK;
            IBREAK:
                IF C = UP_TO THEN
                    GO TO OBREAK;

                SPACE(LEAD);
                FOR C := FROM STEP 1 UNTIL UP_TO-1 DO BEGIN
                    FOR I := 0 STEP 1 UNTIL MONTHS(C).START_WDAY-1 DO
                        SPACE(3);
                    WHILE POSTINCREMENT(I) < 7 AND MONTHS(C).AT_POS < MONTHS(C).DAYS DO BEGIN
                        OUTINT(PREINCREMENT(MONTHS(C).AT_POS),2);
                        IF I < 7 OR C < UP_TO - 1 THEN
                            SPACE(1);
                    END;
                    WHILE POSTINCREMENT(I) <= 7 AND C < UP_TO-1 DO
                        SPACE(3);
                    IF C < UP_TO - 1 THEN
                        SPACE(GAP - 1);
                    MONTHS(C).START_WDAY := 0;
                END;
                OUTIMAGE;
            END;
        OBREAK:
            OUTIMAGE;
        END PRINT_ROW;

        PROCEDURE PRINT_YEAR;
        BEGIN
            INTEGER ROW;
            TEXT BUF;
            INTEGER STRLEN;
            BUF :- BLANKS(32); BUF.PUTINT(YEAR); BUF.SETPOS(1);
            WHILE BUF.MORE AND THEN BUF.GETCHAR = ' ' DO
                STRLEN := STRLEN+1;
            BUF :- BUF.SUB(STRLEN+1, 32-STRLEN);
            SPACE((WIDTH - BUF.LENGTH) // 2);
            OUTTEXT(BUF); OUTIMAGE; OUTIMAGE;
            WHILE ROW * COLS < 12 DO BEGIN
                PRINT_ROW(ROW);
                ROW := ROW+1;
            END;
        END PRINT_YEAR;

        INIT_MONTHS;
        PRINT_YEAR;
    END;
END;


      TYPE MIXED
       LOGICAL*1 LIVE
       REAL*8    VALUE
      END TYPE MIXED
      TYPE(MIXED) STUFF(100)


{$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}
const
  true = 'true';
  false = 'false';
begin
  writeln(true);
  writeln(false);
end.


Public Sub Main()
Dim bX As Boolean

Print bX
bX = True
Print bX

End


:: Bulls and Cows Task from Rosetta Code
:: Batch File Implementation

@echo off
setlocal enabledelayedexpansion

:: initialization
:begin
set "list_chars=123456789"
set "list_length=9"
set "code="
set "code_length=4"   %== this should be less than 10 ==%
set "tries=0"   %== number of tries ==%

:: generate the code to be guessed by player
set "chars_left=%list_chars%"
for /l %%c in (1, 1, %code_length%) do (
    set /a "rnd=!random! %% (%list_length% + 1 - %%c)"
    for %%? in (!rnd!) do set "pick_char=!chars_left:~%%?,1!"
    set "code=!code!!pick_char!"
    for %%? in (!pick_char!) do set "chars_left=!chars_left:%%?=!"
)

:: get the min and max allowable guess for input validation
set "min=!list_chars:~0,%code_length%!"
set "max="
for /l %%c in (1, 1, %code_length%) do set "max=!max!!list_chars:~-%%c,1!"

:: display game
:display
cls
echo(
echo(Bulls and Cows Game
echo(Batch File Implementation
echo(
echo(Gameplay:
echo(
echo(I have generated a %code_length%-digit code from digits 1-9 without duplication.
echo(Your objective is to guess it. If your guess is equal to my code,
echo(then you WIN. If not, I will score your guess:
echo(
echo(** A score of one BULL is accumulated for each digit in your guess
echo(that equals the corresponding digit in my code.
echo(
echo(** A score of one COW is accumulated for each digit in your guess
echo(that also appears in my code, but in the WRONG position.
echo(
echo(Now, start guessing^^!

:: input guess
:guess
echo(
set "guess="   %== clear input ==%
set /p "guess=Your Guess: "

:: validate input
if "!guess!" gtr "%max%" goto invalid
if "!guess!" lss "%min%" goto invalid
set /a "last_idx=%code_length% - 1"
for /l %%i in (0, 1, %last_idx%) do (
    set /a "next_idx=%%i + 1"
    for /l %%j in (!next_idx!, 1, %last_idx%) do (
        if "!guess:~%%i,1!" equ "!guess:~%%j,1!" goto invalid
    )
)
goto score

:: display that input is invalid
:invalid
echo(Please input a valid guess.
goto guess

:: scoring section
:score
set /a "tries+=1"
if "%guess%" equ "%code%" goto win
set "cow=0"
set "bull=0"
for /l %%i in (0, 1, %last_idx%) do (
    for /l %%j in (0, 1, %last_idx%) do (
        if "!guess:~%%i,1!" equ "!code:~%%j,1!" (
            if "%%i" equ "%%j" (
                set /a "bull+=1"
            ) else (
                set /a "cow+=1"
            )
        )
    )
)
:: display score and go back to user input
echo(BULLS = %bull%; COWS = %cow%.
goto guess

:: player wins!
:win
echo(
echo(After %tries% tries, YOU CRACKED IT^^! My code is %code%.
echo(
set /p "opt=Play again? "
if /i "!opt!" equ "y" goto begin
exit /b 0


1 < 2;
# true

2 < 1;
# false

# GAP has also the value fail, which cannot be used as a boolean but may be used i$

1 = fail;
# false

fail = fail;
# true


package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	var n bool = true
	fmt.Println(n)        // prt true
	fmt.Printf("%T\n", n) // prt bool
	n = !n
	fmt.Println(n) // prt false

	x := 5
	y := 8
	fmt.Println("x == y:", x == y) // prt x == y: false
	fmt.Println("x < y:", x < y)   // prt x < y: true

	fmt.Println("\nConvert String into Boolean Data type\n")
	str1 := "japan"
	fmt.Println("Before :", reflect.TypeOf(str1)) // prt Before : string
	bolStr, _ := strconv.ParseBool(str1)
	fmt.Println("After :", reflect.TypeOf(bolStr)) // prt After : bool
}


      secret$ = ""
      REPEAT
        c$ = CHR$(&30 + RND(9))
        IF INSTR(secret$, c$) = 0 secret$ += c$
      UNTIL LEN(secret$) = 4

      PRINT "Guess a four-digit number with no digit used twice."'
      guesses% = 0
      REPEAT

        REPEAT
          INPUT "Enter your guess: " guess$
          IF LEN(guess$) <> 4 PRINT "Must be a four-digit number"
        UNTIL LEN(guess$) = 4
        guesses% += 1

        IF guess$ = secret$ PRINT "You won after "; guesses% " guesses!" : END

        bulls% = 0
        cows% = 0
        FOR i% = 1 TO 4
          c$ = MID$(secret$, i%, 1)
          IF MID$(guess$, i%, 1) = c$ THEN
            bulls% += 1
          ELSE IF INSTR(guess$, c$) THEN
              cows% += 1
            ENDIF
          ENDIF
        NEXT i%
        PRINT "You got " ;bulls% " bull(s) and " ;cows% " cow(s)."

      UNTIL FALSE


get "libhdr"

static $( randstate = ? $)

let randdigit() = valof
$(  let x = ?
    $(  randstate := random(randstate)
        x := (randstate >> 7) & 15
    $) repeatuntil 0 < x <= 9
    resultis x
$)

let gensecret(s) be
    for i=0 to 3
        s!i := randdigit() repeatuntil valof
        $(  for j=0 to i-1 if s!i = s!j then resultis false
            resultis true
        $)

let bulls(secret, guess) = valof
$(  let x = 0
    for i=0 to 3 if secret!i = guess!i then x := x + 1
    resultis x
$)

let cows(secret, guess) = valof
$(  let x = 0
    for i=0 to 3
        for j=0 to 3
            unless i=j
                if secret!i = guess!j then x := x + 1
    resultis x
$)

let readguess(guess) be
$(  let g, v = ?, true
    writes("Enter a guess, or 0 to quit: ")
    g := readn()
    if g=0 then finish
    for i=3 to 0 by -1
    $(  guess!i := g rem 10
        g := g / 10
    $)
    for i=0 to 2 for j = i+1 to 3
        v := v & guess!i ~= 0 & guess!j ~= 0 & guess!i ~= guess!j
    if v then return
    writes("Invalid guess.*N")
$) repeat

let play(secret) be
$(  let tries, b, c = 0, ?, ?
    let guess = vec 3
    $(  readguess(guess)
        b := bulls(secret, guess)
        c := cows(secret, guess)
        writef("Bulls: %N, cows: %N*N", b, c);
        tries := tries + 1
    $) repeatuntil b = 4
    writef("You win in %N tries.*N", tries)
$)

let start() be
$(  let secret = vec 3
    writes("Bulls and cows*N----- --- ----*N")
    writes("Please enter a random seed: ")
    randstate := readn()
    wrch('*N')
    gensecret(secret)
    play(secret)
$)


year = 1969
#.output(#.str(year,">68<"))
> row, 0..3
  > col, 1..3
    cal[col] = mcal(row*3+col,year)
    size = #.size(cal[col],1)
  <
  > i, 1..8
    str = ""
    > col, 1..3
      ? col>1, str += "    "
      line = ""
      ? #.size(cal[col],1)!<i, line = cal[col][i]
      str += #.str(line,"<20<")
    <
    #.output(str)
  <
<
mcal(m,y)=
  months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
  days = [31,28,31,30,31,30,31,31,30,31,30,31]
  ? y%4=0, days[2] = 29
  lines = #.array(0)
  lines[1] = #.str(months[m],">20<")
  lines[2] = "Mo Tu We Th Fr Sa Su"
  n = 3
  > i, 1..#.weekday(1,m,y)-1
    lines[n] += "   "
  <
  > d, 1..days[m]
    wd = #.weekday(d,m,y)
    lines[n] += #.str(d,">2>")
    ? wd<7, lines[n] += " "
    ? wd=7, n += 1
  <
  <= lines
.


data Bool = False | True    deriving (Eq, Ord, Enum, Read, Show, Bounded)


main
	//Bits aka Booleans.
	b $= bit()

	b $= true
	print(b)

	b $= false
	print(b)

	//Non-zero values are true.
	b $= bit(1)
	print(b)

	b $= -1
	print(b)

	//Zero values are false
	b $= 0
	print(b)
}


secret_length = 4

secret = [1 2 3 4 5 6 7 8 9].shuffle.pop secret_length

score = { guess |
  cows = 0
  bulls = 0

  guess.each_with_index { digit, index |
    true? digit == secret[index]
      { bulls = bulls + 1 }
      { true? secret.include?(digit)
        { cows = cows + 1 }
      }
  }

  [cows: cows, bulls: bulls]
}

won = false
guesses = 1

p "I have chosen a number with four unique digits from 1 through 9. Can you guess it?"

while { not won }
  {
    print "Guess #{guesses}: "
    guess = g.strip.dice.map { d | d.to_i }

    when { guess == secret }  { p "You won in #{guesses} guesses!"; won = true }
      { guess.include?(0) || guess.include?(null) } { p "Your guess should only include digits 1 through 9." }
      { guess.length != secret.length } { p "Your guess was not the correct length. The number has exactly #{secret.length} digits." }
      { guess.unique.length != secret.length } { p "Each digit should only appear once in your guess." }
      { true } {
        result = score guess
        p "Score: #{result[:bulls]} bulls, #{result[:cows]} cows."
        guesses = guesses + 1
      }
  }


#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdbool.h>
#include <curses.h>
#include <string.h>

#define MAX_NUM_TRIES 72
#define LINE_BEGIN 7
#define LAST_LINE 18

int yp=LINE_BEGIN, xp=0;

char number[5];
char guess[5];

#define MAX_STR 256
void mvaddstrf(int y, int x, const char *fmt, ...)
{
  va_list args;
  char buf[MAX_STR];

  va_start(args, fmt);
  vsprintf(buf, fmt, args);
  move(y, x);
  clrtoeol();
  addstr(buf);
  va_end(args);
}

void ask_for_a_number()
{
  int i=0;
  char symbols[] = "123456789";

  move(5,0); clrtoeol();
  addstr("Enter four digits: ");
  while(i<4) {
    int c = getch();
    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {
      addch(c);
      symbols[c-'1'] = 0;
      guess[i++] = c;
    }
  }
}

void choose_the_number()
{
  int i=0, j;
  char symbols[] = "123456789";

  while(i<4) {
    j = rand() % 9;
    if ( symbols[j] != 0 ) {
      number[i++] = symbols[j];
      symbols[j] = 0;
    }
  }
}


import Foundation

let monthWidth = 20
let monthGap = 2
let dayNames = "Su Mo Tu We Th Fr Sa"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"

func rpad(string: String, width: Int) -> String {
    return string.count >= width ? string
        : String(repeating: " ", count: width - string.count) + string
}

func lpad(string: String, width: Int) -> String {
    return string.count >= width ? string
        : string + String(repeating: " ", count: width - string.count)
}

func centre(string: String, width: Int) -> String {
    if string.count >= width {
        return string
    }
    let c = (width - string.count)/2
    return String(repeating: " ", count: c) + string
        + String(repeating: " ", count: width - string.count - c)
}

func formatMonth(year: Int, month: Int) -> [String] {
    let calendar = Calendar.current
    let dc = DateComponents(year: year, month: month, day: 1)
    let date = calendar.date(from: dc)!
    let firstDay = calendar.component(.weekday, from: date) - 1
    let range = calendar.range(of: .day, in: .month, for: date)!
    let daysInMonth = range.count
    var lines: [String] = []
    lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth))
    lines.append(dayNames)
    var padWidth = 2
    var line = String(repeating: " ", count: 3 * firstDay)
    for day in 1...daysInMonth {
        line += rpad(string: String(day), width: padWidth)
        padWidth = 3
        if (firstDay + day) % 7 == 0 {
            lines.append(line)
            line = ""
            padWidth = 2
        }
    }
    if line.count > 0 {
        lines.append(lpad(string: line, width: monthWidth))
    }
    return lines
}

func printCentred(string: String, width: Int) {
    print(rpad(string: string, width: (width + string.count)/2))
}

public func printCalendar(year: Int, width: Int) {
    let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap)))
    let lineWidth = monthWidth * months + monthGap * (months - 1)
    printCentred(string: "[Snoopy]", width: lineWidth)
    printCentred(string: String(year), width: lineWidth)
    var firstMonth = 1
    while firstMonth <= 12 {
        if firstMonth > 1 {
            print()
        }
        let lastMonth = min(12, firstMonth + months - 1)
        let monthCount = lastMonth - firstMonth + 1
        var lines: [[String]] = []
        var lineCount = 0
        for month in firstMonth...lastMonth {
            let monthLines = formatMonth(year: year, month: month)
            lineCount = max(lineCount, monthLines.count)
            lines.append(monthLines)
        }
        for i in 0..<lineCount {
            var line = ""
            for month in 0..<monthCount {
                if month > 0 {
                    line.append(String(repeating: " ", count: monthGap))
                }
                line.append(i < lines[month].count ? lines[month][i]
                            : String(repeating: " ", count: monthWidth))
            }
            print(line)
        }
        firstMonth = lastMonth + 1
    }
}

printCalendar(year: 1969, width: 80)


Idris> :doc Bool
Data type Prelude.Bool.Bool : Type
    Boolean Data Type

Constructors:
    False : Bool

    True : Bool


let B be whether or not 123 is greater than 100;


using System;

namespace BullsnCows
{
    class Program
    {

        static void Main(string[] args)
        {
            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            KnuthShuffle<int>(ref nums);
            int[] chosenNum = new int[4];
            Array.Copy(nums, chosenNum, 4);

            Console.WriteLine("Your Guess ?");
            while (!game(Console.ReadLine(), chosenNum))
            {
                Console.WriteLine("Your next Guess ?");
            }

            Console.ReadKey();
        }

        public static void KnuthShuffle<T>(ref T[] array)
        {
            System.Random random = new System.Random();
            for (int i = 0; i < array.Length; i++)
            {
                int j = random.Next(array.Length);
                T temp = array[i]; array[i] = array[j]; array[j] = temp;
            }
        }

        public static bool game(string guess, int[] num)
        {
            char[] guessed = guess.ToCharArray();
            int bullsCount = 0, cowsCount = 0;

            if (guessed.Length != 4)
            {
                Console.WriteLine("Not a valid guess.");
                return false;
            }

            for (int i = 0; i < 4; i++)
            {
                int curguess = (int) char.GetNumericValue(guessed[i]);
                if (curguess < 1 || curguess > 9)
                {
                    Console.WriteLine("Digit must be ge greater 0 and lower 10.");
                    return false;
                }
                if (curguess == num[i])
                {
                    bullsCount++;
                }
                else
                {
                    for (int j = 0; j < 4; j++)
                    {
                        if (curguess == num[j])
                            cowsCount++;
                    }
                }
            }

            if (bullsCount == 4)
            {
                Console.WriteLine("Congratulations! You have won!");
                return true;
            }
            else
            {
                Console.WriteLine("Your Score is {0} bulls and {1} cows", bullsCount, cowsCount);
                return false;
            }
        }
    }
}


package require Tcl 8.5

# Produce information about the days in a month, without any assumptions about
# what those days actually are.
proc calMonthDays {timezone locale year month} {
    set days {}
    set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \
	    -timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"]
    while 1 {
	set moment [clock add $moment 1 day]
	lassign [clock format $moment -timezone $timezone -locale $locale \
		-format "%m %d %u"] m d dow
	if {[scan $m %d] != $month} {
	    return $days
	}
	lappend days $moment [scan $d %d] $dow
    }
}

proc calMonth {year month timezone locale} {
    set dow 0
    set line ""
    set lines {}
    foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] {
	if {![llength $lines]} {lappend lines $t}
	if {$dow > $dayofweek} {
	    lappend lines [string trimright $line]
	    set line ""
	    set dow 0
	}
	while {$dow < $dayofweek-1} {
	    append line "   "
	    incr dow
	}
	append line [format "%2d " $day]
	set dow $dayofweek
    }
    lappend lines [string trimright $line]
}

proc cal3Month {year month timezone locale} {
    # Extract the month data
    set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month
    set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month
    set d3 [lassign [calMonth $year $month $timezone $locale] t3]
    # Print the header line of month names
    foreach t [list $t1 $t2 $t3] {
	set m [clock format $t -timezone $timezone -locale $locale -format "%B"]
	set l [expr {10 + [string length $m]/2}]
	puts -nonewline [format "%-25s" [format "%*s" $l $m]]
    }
    puts ""
    # Print the month days
    foreach l1 $d1 l2 $d2 l3 $d3 {
	puts [format "%-25s%-25s%s" $l1 $l2 $l3]
    }
}

proc cal {{year ""} {timezone :localtime} {locale en}} {
    if {$year eq ""} {
	set year [clock format [clock seconds] -format %Y]
    }
    puts [format "%40s" "-- $year --"]
    foreach m {1 4 7 10} {
	puts ""
	cal3Month $year $m $timezone $locale
    }
}

proc snoopy {} {
    puts [format "%43s\n" {[Snoopy Picture]}]
}

snoopy
cal


$ jq type
true
"boolean"
false
"boolean"


julia> if 1
         println("true")
       end
ERROR: type: non-boolean (Int64) used in boolean context


#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>

bool contains_duplicates(std::string s)
{
  std::sort(s.begin(), s.end());
  return std::adjacent_find(s.begin(), s.end()) != s.end();
}

void game()
{
  typedef std::string::size_type index;

  std::string symbols = "0123456789";
  unsigned int const selection_length = 4;

  std::random_shuffle(symbols.begin(), symbols.end());
  std::string selection = symbols.substr(0, selection_length);
  std::string guess;
  while (std::cout << "Your guess? ", std::getline(std::cin, guess))
  {
    if (guess.length() != selection_length
        || guess.find_first_not_of(symbols) != std::string::npos
        || contains_duplicates(guess))
    {
      std::cout << guess << " is not a valid guess!";
      continue;
    }

    unsigned int bulls = 0;
    unsigned int cows = 0;
    for (index i = 0; i != selection_length; ++i)
    {
      index pos = selection.find(guess[i]);
      if (pos == i)
        ++bulls;
      else if (pos != std::string::npos)
        ++cows;
    }
    std::cout << bulls << " bulls, " << cows << " cows.\n";
    if (bulls == selection_length)
    {
      std::cout << "Congratulations! You have won!\n";
      return;
    }
  }
  std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
  std::exit(EXIT_FAILURE);
}

int main()
{
  std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
  std::string answer;
  while (true)
  {
    while (true)
    {
      if (!std::getline(std::cin, answer))
      {
        std::cout << "I can't get an answer. Exiting.\n";
        return EXIT_FAILURE;
      }
      if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
        break;
      if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
      {
        std::cout << "Ok. Goodbye.\n";
        return EXIT_SUCCESS;
      }
      std::cout << "Please answer yes or no: ";
    }
    game();
    std::cout << "Another game? ";
  }
}


Print "                      XXXX"
Print "                     X    XX"
Print "                    X  ***  X                XXXXX"
Print "                   X  *****  X            XXX     XX"
Print "                XXXX ******* XXX      XXXX          XX"
Print "              XX   X ******  XXXXXXXXX                XX XXX"
Print "            XX      X ****  X                           X** X"
Print "           X        XX    XX     X                      X***X"
Print "          X         //XXXX       X                      XXXX"
Print "         X         //   X                             XX"
Print "        X         //    X          XXXXXXXXXXXXXXXXXX/"
Print "        X     XXX//    X          X"
Print "        X    X   X     X         X"
Print "        X    X    X    X        X"
Print "         X   X    X    X        X                    XX"
Print "         X    X   X    X        X                 XXX  XX"
Print "          X    XXX      X        X               X  X X  X"
Print "          X             X         X              XX X  XXXX"
Print "           X             X         XXXXXXXX\\     XX   XX  X"
Print "            XX            XX              X     X    X  XX"
Print "              XX            XXXX   XXXXXX/     X     XXXX"
Print "                XXX             XX***         X     X"
Print "                   XXXXXXXXXXXXX *   *       X     X"
Print "                                *---* X     X     X"
Print "                               *-* *   XXX X     X"
Print "                               *- *       XXX   X"
Print "                              *- *X          XXX"
Print "                              *- *X  X          XXX"
Print "                             *- *X    X            XX"
Print "                             *- *XX    X             X"
Print "                            *  *X* X    X             X"
Print "                            *  *X * X    X             X"
Print "                           *  * X**  X   XXXX          X"
Print "                           *  * X**  XX     X          X"
Print "                          *  ** X** X     XX          X"
Print "                          *  **  X*  XXX   X         X"
Print "                         *  **    XX   XXXX       XXX"
Print "                        *  * *      XXXX      X     X"
Print "                       *   * *          X     X     X"
Print "         =======*******   * *           X     X      XXXXXXXX\\"
Print "                *         * *      /XXXXX      XXXXXXXX\\      )"
Print "           =====**********  *     X                     )  \\  )"
Print "             ====*         *     X               \\  \\   )XXXXX"
Print "        =========**********       XXXXXXXXXXXXXXXXXXXXXX"


{if true then YES else NO}
-> YES
{if false then YES else NO}
-> NO


import ceylon.random {
    DefaultRandom
}

shared void run() {

    value random = DefaultRandom();

    function generateDigits() =>
            random.elements(1..9).distinct.take(4).sequence();

    function validate(String guess) {
        variable value ok = true;
        if (!guess.every((Character element) => element.digit)) {
            print("numbers only, please");
            ok = false;
        }
        if ('0' in guess) {
            print("only 1 to 9, please");
            ok = false;
        }
        if (guess.distinct.shorterThan(guess.size)) {
            print("no duplicates, please");
            ok = false;
        }
        if (guess.size != 4) {
            print("4 digits please");
            ok = false;
        }
        return ok;
    }

    function score({Integer*} target, {Integer*} guess) {
        variable value bulls = 0;
        variable value cows = 0;
        for ([a, b] in zipPairs(target, guess)) {
            if (a == b) {
                bulls++;
            } else if (target.contains(b)) {
                cows++;
            }
        }
        return [bulls, cows];
    }

    while (true) {
        value digits = generateDigits();
        print("I have chosen my four digits, please guess what they are.
               Use only the digits 1 to 9 with no duplicates and enter them with no spaces. eg 1234
               Enter q or Q to quit.");
        while (true) {
            if (exists line = process.readLine()) {
                if (line.uppercased == "Q") {
                    return;
                }
                if (validate(line)) {
                    value guessDigits = line.map((Character element) => Integer.parse(element.string)).narrow<Integer>();
                    value [bulls, cows] = score(digits, guessDigits);
                    if (bulls == 4) {
                        print("You win!");
                        break;
                    }
                    else {
                        print("Bulls: ``bulls``, Cows:  ``cows``");
                    }
                }
            }
        }
    }
}


(ns bulls-and-cows)

(defn bulls [guess solution]
  (count (filter true? (map = guess solution))))

(defn cows [guess solution]
  (-
   (count (filter (set solution) guess))
   (bulls guess solution)))

(defn valid-input?
  "checks whether the string is a 4 digit number with unique digits"
  [user-input]
  (if (re-seq #"^(?!.*(\d).*\1)\d{4}$" user-input)
    true
    false))

(defn enter-guess []
  "Let the user enter a guess. Verify the input. Repeat until valid.
returns a list of digits enters by the user (# # # #)"
    (println "Enter your guess: ")
    (let [guess (read-line)]
      (if (valid-input? guess)
        (map #(Character/digit % 10) guess)
        (recur))))

(defn bulls-and-cows []
  "generate a random 4 digit number from the list of (1 ... 9): no repeating digits
player tries to guess the number with bull and cows rules gameplay"
  (let [solution ( take 4 (shuffle (range 1 10)))]
    (println "lets play some bulls and cows!")
    (loop [guess (enter-guess)]
      (println (bulls guess solution) " bulls and " (cows guess solution) " cows.")
      (if (not= guess solution)
        (recur (enter-guess))
        (println "You have won!")))))

(bulls-and-cows)


#!/bin/sh
echo "Snoopy goes here"
cal 1969


!true
// => false

not false
// => true

var(x = true)
$x // => true

$x = false
$x // => false


> 'true
true
> 'false
false
> (or 'false 'false)
false
> (or 'false 'true)
true


put TRUE
-- 1
put FALSE
-- 0
if 23 then put "Hello"
-- "Hello"


int a = 0;
int b = 1;
int c;
string str1 = "initialized string";
string str2; //  "uninitialized string";

if (a) {puts("first test a is false");}         // This should not print
if (b) {puts("second test b is true");}         // This should print
if (c) {puts("third test b is false");}         // This should not print
if (!defined(c)) {puts("fourth test is true");} // This should print
if (str1) {puts("fifth test str1 is true");}    // This should print
if (str2) {puts("sixth test str2 is false");}   // This should not print


% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
%
% pclu -merge $CLUHOME/lib/misc.lib -compile bulls_cows.clu

% Seed the random number generator with the current time
init_rng = proc ()
    d: date := now()
    seed: int := ((d.hour*60) + d.minute)*60 + d.second
    random$seed(seed)
end init_rng

% Generate a secret
make_secret = proc () returns (sequence[int])
    secret: array[int] := array[int]$[0,0,0,0]
    for i: int in int$from_to(1,4) do
        digit: int
        valid: bool := false
        while ~valid do
            digit := 1+random$next(9)
            valid := true
            for j: int in int$from_to(1, i-1) do
                if secret[i] = digit then
                    valid := false
                    break
                end
            end
        end
        secret[i] := digit
    end
    return(sequence[int]$a2s(secret))
end make_secret

% Count the bulls
bulls = proc (secret, input: sequence[int]) returns (int)
    n_bulls: int := 0
    for i: int in int$from_to(1,4) do
        if secret[i] = input[i] then n_bulls := n_bulls + 1 end
    end
    return(n_bulls)
end bulls

% Count the cows
cows = proc (secret, input: sequence[int]) returns (int)
    n_cows: int := 0
    for i: int in int$from_to(1,4) do
        for j: int in int$from_to(1,4) do
            if i ~= j cand secret[i] = input[j] then
                n_cows := n_cows + 1
            end
        end
    end
    return(n_cows)
end cows

% Read a guess
player_guess = proc () returns (sequence[int])
    pi: stream := stream$primary_input()
    po: stream := stream$primary_output()

    while true do       % we will keep reading until the guess is valid
        stream$puts(po, "Guess? ")
        guess: string := stream$getl(pi)

        % check length
        if string$size(guess) ~= 4 then
            stream$putl(po, "Invalid guess: need four digits.")
            continue
        end

        % get and check digits
        valid: bool := true
        digits: sequence[int] := sequence[int]$[]
        for c: char in string$chars(guess) do
            i: int := char$c2i(c) - 48
            if ~(i>=1 & i<=9) then
                valid := false
                break
            end
            digits := sequence[int]$addh(digits,i)
        end
        if ~valid then
            stream$putl(po, "Invalid guess: each position needs to be a digit 1-9.")
            continue
        end

        % check that there are no duplicates
        valid := true
        for i: int in int$from_to(1,4) do
            for j: int in int$from_to(i+1,4) do
                if digits[i] = digits[j] then
                    valid := false
                    break
                end
            end
        end
        if ~valid then
            stream$putl(po, "Invalid guess: there must be no duplicate digits.")
            continue
        end

        return(digits)
    end
end player_guess

% Play a game
play_game = proc (secret: sequence[int])
    po: stream := stream$primary_output()
    n_guesses: int := 0
    while true do
        n_guesses := n_guesses + 1
        guess: sequence[int] := player_guess()

        n_bulls: int := bulls(secret, guess)
        n_cows: int := cows(secret, guess)

        stream$putl(po, "Bulls: " || int$unparse(n_bulls)
                    || ", cows: " || int$unparse(n_cows))
        if n_bulls = 4 then
            stream$putl(po, "Congratulations! You won in "
                     || int$unparse(n_guesses) || " tries.")
            break
        end
    end
end play_game

start_up = proc ()
    po: stream := stream$primary_output()
    init_rng()
    stream$putl(po, "Bulls and cows\n----- --- ----\n")
    play_game(make_secret())
end start_up


say = print
prompt = (str) ->
    putstr str
    readline! ? quit!


Buf_Switch(Buf_Free)
Config_Tab(5,30,55)
#9 = 1                  // first day of week: 0=Su, 1=Mo
#3 = 3                  // number of months per line
#2 = 1969               // year
#1 = 1                  // starting month
Repeat(12/#3) {
    Repeat (#3) {
        Buf_Switch(Buf_Free)
        Call_File(122, "calendar.vdm", "DRAW_CALENDAR")
        Reg_Copy_Block(10, 1, EOB_Pos, COLSET, 1, 21)
        Buf_Quit(OK)
        EOL Ins_Char(9)
        #5 = Cur_Pos
        Reg_Ins(10)
        Goto_Pos(#5)
        #1++
    }
    EOF
    Ins_Newline(2)
}


print 1 < 0    ; false
print 1 > 0    ; true
if "true [print "yes]    ; yes
if not "false [print "no]  ; no


if 0 then print "0" end             -- This prints
if "" then print"empty string" end  -- This prints
if {} then print"empty table" end   -- This prints
if nil then print"this won't print" end
if true then print"true" end
if false then print"false" end      -- This does not print


Module CheckBoolean {
      A=True
      Print Type$(A)="Double"
      B=1=1
      Print Type$(B)="Boolean"
      Print A=B  ' true
      Print A, B   ' -1   True
      Def boolean C=True, D=False
      Print C, D , 1>-3 ' True False True
      K$=Str$(C)
      Print K$="True"  ' True
      Function ShowBoolean$(&x) {
           x=false
           Try {
                        if keypress(32) then x=true : exit
                        If Keypress(13) then exit
                        loop
            }
            =str$(x, locale)
      }
      Wait 100
      Print "C (space for true, enter for false)="; : Print ShowBoolean$(&c)
      Print C
}
CheckBoolean

Print str$(True, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="true"
Print str$(False, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="false"
Print str$(2, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="true"


(defun get-number ()
  (do ((digits '()))
      ((>= (length digits) 4) digits)
    (pushnew (1+ (random 9)) digits)))

(defun compute-score (guess number)
  (let ((cows  0)
        (bulls 0))
    (map nil (lambda (guess-digit number-digit)
               (cond ((= guess-digit number-digit) (incf bulls))
                     ((member guess-digit number)  (incf cows))))
         guess number)
    (values cows bulls)))

(defun number->guess (number)
  (when (integerp number)
    (do ((digits '()))
        ((zerop number) digits)
      (multiple-value-bind (quotient remainder) (floor number 10)
        (push remainder digits)
        (setf number quotient)))))

(defun valid-guess-p (guess)
  (and (= 4 (length guess))
       (every (lambda (digit) (<= 1 digit 9)) guess)
       (equal guess (remove-duplicates guess))))

(defun play-game (&optional (stream *query-io*))
  (do ((number (get-number))
       (cows   0)
       (bulls  0))
      ((= 4 bulls))
    (format stream "~&Guess a 4-digit number: ")
    (let ((guess (number->guess (read stream))))
      (cond ((not (valid-guess-p guess))
             (format stream "~&Malformed guess."))
            (t
             (setf (values cows bulls) (compute-score guess number))
             (if (= 4 bulls)
               (format stream "~&Correct, you win!")
               (format stream "~&Score: ~a cows, ~a bulls."
                       cows bulls)))))))


Option Compare Binary
Option Explicit On
Option Infer On
Option Strict On

Imports System.Globalization
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices


>> islogical(true)

ans =

     1

>> islogical(false)

ans =

     1

>> islogical(logical(1))

ans =

     1

>> islogical(logical(0))

ans =

     1

>> islogical(1)

ans =

     0

>> islogical(0)

ans =

     0


size = 4
secret = ('1'..'9').to_a.sample(size)
guess = [] of Char

i = 0
loop do
  i += 1
  loop do
    print "Guess #{i}: "
    guess = gets.not_nil!.chomp.chars
    exit if guess.empty?

    break if guess.size == size &&
             guess.all? { |x| ('1'..'9').includes? x } &&
             guess.uniq.size == size

    puts "Problem, try again. You need to enter #{size} unique digits from 1 to 9"
  end

  if guess == secret
    puts "Congratulations you guessed correctly in #{i} attempts"
    break
  end

  bulls = cows = 0
  size.times do |j|
    if guess[j] == secret[j]
      bulls += 1
    elsif secret.includes? guess[j]
      cows += 1
    end
  end

  puts "Bulls: #{bulls}; Cows: #{cows}"
end


'call it with year, number of months per row (1,2,3,4,6) and locale ("" for default)

docal 1969,6,""

function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function

sub print(x) wscript.stdout.writeline x : end sub

function iif(a,b,c) :if a then iif=b else iif =c end if : end function

sub docal (yr,nmonth,sloc)
dim ld(6)
dim d(6)
if nmonth=5 or nmonth>6 then wscript.stderr.writeline "Can't use width " & nmonth :exit sub
if sloc<>"" then Setlocale sloc

for i=1 to 7
  wday=wday &" "&left(weekdayname(i,true,vbUseSystemDayOfWeek),2)
next

ncols=nmonth*21+(nmonth-1)*1
print center("[Snoopy]",ncols)
print center(yr,ncols)
print string(ncols,"=")

for i=1 to 12\nmonth

  s="": s1="":esp=""
  for j=1 to nmonth
    s=s & esp & center(monthname(m+j),21)
    s1=s1 & esp & wday
    d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2
    ld(j)=day(dateserial(yr,m+j+1,0))
    esp=" "
  next
  print s:  print s1

  while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))
    s=""
    for j=1 to nmonth
      for k=1 to 7
        s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3)
        d(j)=d(j)+1
      next
      s=s&" "
    next
    print s
  wend

  m=m+nmonth
  if i<>12\nmonth then print ""
next
print string(ncols,"=")
end sub


is(1 < 2);
/* true */

is(2 < 1);
/* false */

not true;
/* false */

not false;
/* true */


boolTrue = true
boolFalse = false

if boolTrue then print "boolTrue is true, and its value is: " + boolTrue

if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse

mostlyTrue = 0.8
kindaTrue = 0.4
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue)


import java.util.ArrayList
import java.util.HashMap

# booleans
puts 'true is true' if true
puts 'false is false' if (!false)

# lists treated as booleans
x = ArrayList.new
puts "empty array is true" if x
x.add("an element")
puts "full array is true" if x
puts "isEmpty() is false" if !x.isEmpty()

# maps treated as booleans
map = HashMap.new
puts "empty map is true" if map
map.put('a', '1')
puts "full map is true" if map
puts "size() is 0 is false" if !(map.size() == 0)

# these things do not compile
# value = nil   # ==> cannot assign nil to Boolean value
# puts 'nil is false' if false == nil  # ==> cannot compare boolean to nil
# puts '0 is false' if (0 == false)    # ==> cannot compare int to false

#puts 'TRUE is true' if TRUE   # ==> TRUE does not exist
#puts 'FALSE is false' if !FALSE   # ==> FALSE does not exist


F getitem(=s, depth = 0)
   V out = [‘’]
   L s != ‘’
      V c = String(s[0])
      I depth & (c == ‘,’ | c == ‘}’)
         R (out, s)
      I c == ‘{’
         V x = getgroup(s[1..], depth + 1)
         I !x[0].empty
            out = multiloop(out, x[0], (a, b) -> a‘’b)
            s = x[1]
            L.continue
      I c == "\\" & s.len > 1
         (s, c) = (s[1..], c‘’s[1])
      out = out.map(a -> a‘’@c)
      s = s[1..]
   R (out, s)

F getgroup(=s, depth)
   [String] out
   V comma = 0B
   L s != ‘’
      V gs = getitem(s, depth)
      s = gs[1]
      I s == ‘’
         L.break
      out [+]= gs[0]

      I s[0] == ‘}’
         I comma
            R (out, s[1..])
         R (out.map(a -> ‘{’a‘}’), s[1..])

      I s[0] == ‘,’
         (comma, s) = (1B, s[1..])
   R ([‘’] * 0, ‘’)

L(s) |‘~/{Downloads,Pictures}/*.{jpg,gif,png}
       It{{em,alic}iz,erat}e{d,}, please.
       {,{,gotta have{ ,\, again\, }}more }cowbell!
       {}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}’.split("\n")
   print(([s] [+] getitem(s)[0]).join("\n\t")"\n")


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

    immutable hidden = "123456789"d.randomCover.take(4).array;
    while (true) {
        "Next guess: ".write;
        const d = readln.strip.array.sort().release;
        if (d.count == 4 && d.all!isDigit && d.uniq.count == 4) {
            immutable bulls = d.zip(hidden).count!q{ a[0] == a[1] },
                      cows = d.count!(g => hidden.canFind(g)) - bulls;
            if (bulls == 4)
                return " You guessed it!".writeln;
            writefln("bulls %d, cows %d", bulls, cows);
        }
        " Bad guess! (4 unique digits, 1-9)".writeln;
    }
}


 Any Year Calendar
--------------------
S  M  T  W  T  F  S


MODULE boo;

IMPORT  InOut;

VAR     result, done            : BOOLEAN;
        A, B                    : INTEGER;

BEGIN
   result := (1 = 2);
   result := NOT result;
   done := FALSE;
   REPEAT
     InOut.ReadInt (A);
     InOut.ReadInt (B);
     done := A > B
   UNTIL done
END boo.


def example(input :boolean):
    if input:
        return "Input was true!"
    return "Input was false."


a = true
b = false

if a
    println "a is true"
else if b
    println "b is true"
end


use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions

on braceExpansion(textForExpansion)
    -- Massage the text to pass to a shell script: -
    -- Single-quote it to render everything in it initially immune from brace and file-system expansion.
    -- Include a return at the end to get a new line at the end of each eventual expansion.
    set textForExpansion to quoted form of (textForExpansion & return)
    -- Switch to ASObjC text for a couple of regex substitutions.
    set textForExpansion to current application's class "NSMutableString"'s stringWithString:(textForExpansion)
    -- Increase the escape level of every instance of /two/ backslashes (represented by eight in the
    -- AppleScript string for the search regex) and isolate each result inside its own quote marks.
    tell textForExpansion to replaceOccurrencesOfString:("\\\\\\\\") withString:("''$0$0''") ¬
        options:(current application's NSRegularExpressionSearch) range:({0, its |length|()})
    -- UNquote every run of braces and/or commas not now immediately preceded by a backslash.
    tell textForExpansion to replaceOccurrencesOfString:("(?<!\\\\)[{,}]++") withString:("'$0'") ¬
        options:(current application's NSRegularExpressionSearch) range:({0, its |length|()})

    -- Pass the massaged text to a shell script to be 'echo'-ed. Since a space will still be inserted
    -- between each expansion, also delete the space after each return in the result.
    -- Return a list of the individual expansions.
    return (do shell script ("echo " & textForExpansion & " | sed -E 's/([[:cntrl:]]) /\\1/g'"))'s paragraphs
end braceExpansion

-- Test:
set output to braceExpansion("~/{Downloads,Pictures}/*.{jpg,gif,png}") & ¬
    braceExpansion("It{{em,alic}iz,erat}e{d,}, please.") & ¬
    braceExpansion("{,{,gotta have{ ,\\, again\\, }}more }cowbell!") & ¬
    braceExpansion("{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}")
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid

log output -- To see the result without the backslash-escaping.


;This one is a lot more simpler than the rest
BraceExp(string, del:="`n") {
	Loop, Parse, string
		if (A_LoopField = "{")
			break
		else
		substring .= A_LoopField
	substr := SubStr(string, InStr(string, "{")+1, InStr(string, "}")-InStr(string, "{")-1)
	Loop, Parse, substr, `,
		toreturn .= substring . A_LoopField . del
	return toreturn
}

Msgbox, % BraceExp("enable_{video,audio}")
Msgbox, % BraceExp("apple {bush,tree}")
Msgbox, % BraceExp("h{i,ello}")
Msgbox, % BraceExp("rosetta{code,stone}")


def Digit := 1..9
def Number := Tuple[Digit,Digit,Digit,Digit]

/** Choose a random number to be guessed. */
def pick4(entropy) {
    def digits := [1,2,3,4,5,6,7,8,9].diverge()

    # Partial Fisher-Yates shuffle
    for i in 0..!4 {
        def other := entropy.nextInt(digits.size() - i) + i
        def t := digits[other]
        digits[other] := digits[i]
        digits[i] := t
    }
    return digits(0, 4)
}

/** Compute the score of a guess. */
def scoreGuess(actual :Number, guess :Number) {
    var bulls := 0
    var cows := 0
    for i => digit in guess {
        if (digit == actual[i]) {
            bulls += 1
        } else if (actual.indexOf1(digit) != -1) {
            cows += 1
        }
    }
    return [bulls, cows]
}

/** Parse a guess string into a list of digits (Number). */
def parseGuess(guessString, fail) :Number {
    if (guessString.size() != 4) {
        return fail(`I need four digits, not ${guessString.size()} digits.`)
    } else {
        var digits := []
        for c in guessString {
            if (('1'..'9')(c)) {
                digits with= c - '0'
            } else {
                return fail(`I need a digit from 1 to 9, not "$c".`)
            }
        }
        return digits
    }
}

/** The game loop: asking for guesses and reporting scores and win conditions.
    The return value is null or a broken reference if there was a problem. */
def bullsAndCows(askUserForGuess, tellUser, entropy) {
    def actual := pick4(entropy)

    def gameTurn() {
        return when (def guessString := askUserForGuess <- ()) -> {
            escape tellAndContinue {

                def guess := parseGuess(guessString, tellAndContinue)
                def [bulls, cows] := scoreGuess(actual, guess)

                if (bulls == 4) {
                    tellUser <- (`You got it! The number is $actual!`)
                    null
                } else {
                    tellAndContinue(`Your score for $guessString is $bulls bulls and $cows cows.`)
                }

            } catch message {
                # The parser or scorer has something to say, and the game continues afterward
                when (tellUser <- (message)) -> {
                    gameTurn()
                }
            }
        } catch p {
            # Unexpected problem of some sort
            tellUser <- ("Sorry, game crashed.")
            throw(p)
        }
    }

    return gameTurn()
}


import "/date" for Date
import "/fmt" for Fmt
import "/seq" for Lst

var calendar = Fn.new { |year|
    var snoopy = "🐶"
    var days = "Su Mo Tu We Th Fr Sa"
    var months = [
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    ]
    Fmt.print("$70m", snoopy)
    var yearStr = "--- %(year) ---"
    Fmt.print("$70m\n", yearStr)
    var first = List.filled(3, 0)
    var mlen = List.filled(3, 0)
    var c = 0
    for (chunk in Lst.chunks(months, 3)) {
        for (i in 0..2) Fmt.write("$20m     ", chunk[i])
        System.print()
        for (i in 0..2) System.write("%(days)     ")
        System.print()
        first[0] = Date.new(year, c*3 + 1, 1).dayOfWeek % 7
        first[1] = Date.new(year, c*3 + 2, 1).dayOfWeek % 7
        first[2] = Date.new(year, c*3 + 3, 1).dayOfWeek % 7
        mlen[0]  = Date.monthLength(year, c*3 + 1)
        mlen[1]  = Date.monthLength(year, c*3 + 2)
        mlen[2]  = Date.monthLength(year, c*3 + 3)
        for (i in 0..5) {
            for (j in 0..2) {
                var start = 1 + 7 * i - first[j]
                for (k in start..start+6) {
                    if (k >= 1 && k <= mlen[j]) {
                        Fmt.write("$2d ", k)
                    } else {
                        System.write("   ")
                    }
                }
                System.write("    ")
            }
            System.print()
        }
        System.print()
        c = c + 1
    }
}

calendar.call(1969)


/* boolean values */
$print(true, "\n");
$print(false, "\n");

if 0 {
  $print("literal 0 tests true\n");
} else {
  $print("literal 0 tests false\n");
}

if 1 {
  $print("literal 1 tests true\n");
} else {
  $print("literal 1 tests false\n");
}

if $istrue(0) {
  $print("$istrue(0) tests true\n");
} else {
  $print("$istrue(0) tests false\n");
}

if $istrue(1) {
  $print("$istrue(1) tests true\n");
} else {
  $print("$istrue(1) tests false\n");
}


/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

bval = [1, 0, 5, 'a', 1 == 1, 1 \= 1, isTrue, isFalse]

loop b_ = 0 for bval.length
  select case bval[b_]
    when isTrue  then say bval[b_] 'is true'
    when isFalse then say bval[b_] 'is false'
    otherwise         say bval[b_] 'is not boolean'
    end
  end b_

method isTrue public static returns boolean
  return (1 == 1)

method isFalse public static returns boolean
  return \isTrue


#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 128

typedef unsigned char character;
typedef character *string;

typedef struct node_t node;
struct node_t {
    enum tag_t {
        NODE_LEAF,
        NODE_TREE,
        NODE_SEQ,
    } tag;

    union {
        string str;
        node *root;
    } data;

    node *next;
};

node *allocate_node(enum tag_t tag) {
    node *n = malloc(sizeof(node));
    if (n == NULL) {
        fprintf(stderr, "Failed to allocate node for tag: %d\n", tag);
        exit(1);
    }
    n->tag = tag;
    n->next = NULL;
    return n;
}

node *make_leaf(string str) {
    node *n = allocate_node(NODE_LEAF);
    n->data.str = str;
    return n;
}

node *make_tree() {
    node *n = allocate_node(NODE_TREE);
    n->data.root = NULL;
    return n;
}

node *make_seq() {
    node *n = allocate_node(NODE_SEQ);
    n->data.root = NULL;
    return n;
}

void deallocate_node(node *n) {
    if (n == NULL) {
        return;
    }

    deallocate_node(n->next);
    n->next = NULL;

    if (n->tag == NODE_LEAF) {
        free(n->data.str);
        n->data.str = NULL;
    } else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {
        deallocate_node(n->data.root);
        n->data.root = NULL;
    } else {
        fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag);
        exit(1);
    }

    free(n);
}

void append(node *root, node *elem) {
    if (root == NULL) {
        fprintf(stderr, "Cannot append to uninitialized node.");
        exit(1);
    }
    if (elem == NULL) {
        return;
    }

    if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {
        if (root->data.root == NULL) {
            root->data.root = elem;
        } else {
            node *it = root->data.root;
            while (it->next != NULL) {
                it = it->next;
            }
            it->next = elem;
        }
    } else {
        fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag);
        exit(1);
    }
}

size_t count(node *n) {
    if (n == NULL) {
        return 0;
    }

    if (n->tag == NODE_LEAF) {
        return 1;
    }
    if (n->tag == NODE_TREE) {
        size_t sum = 0;
        node *it = n->data.root;
        while (it != NULL) {
            sum += count(it);
            it = it->next;
        }
        return sum;
    }
    if (n->tag == NODE_SEQ) {
        size_t prod = 1;
        node *it = n->data.root;
        while (it != NULL) {
            prod *= count(it);
            it = it->next;
        }
        return prod;
    }

    fprintf(stderr, "Cannot count node with tag: %d\n", n->tag);
    exit(1);
}

void expand(node *n, size_t pos) {
    if (n == NULL) {
        return;
    }

    if (n->tag == NODE_LEAF) {
        printf(n->data.str);
    } else if (n->tag == NODE_TREE) {
        node *it = n->data.root;
        while (true) {
            size_t cnt = count(it);
            if (pos < cnt) {
                expand(it, pos);
                break;
            }
            pos -= cnt;
            it = it->next;
        }
    } else if (n->tag == NODE_SEQ) {
        size_t prod = pos;
        node *it = n->data.root;
        while (it != NULL) {
            size_t cnt = count(it);

            size_t rem = prod % cnt;
            expand(it, rem);

            it = it->next;
        }
    } else {
        fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag);
        exit(1);
    }
}

string allocate_string(string src) {
    size_t len = strlen(src);
    string out = calloc(len + 1, sizeof(character));
    if (out == NULL) {
        fprintf(stderr, "Failed to allocate a copy of the string.");
        exit(1);
    }
    strcpy(out, src);
    return out;
}

node *parse_seq(string input, size_t *pos);

node *parse_tree(string input, size_t *pos) {
    node *root = make_tree();

    character buffer[BUFFER_SIZE] = { 0 };
    size_t bufpos = 0;
    size_t depth = 0;
    bool asSeq = false;
    bool allow = false;

    while (input[*pos] != 0) {
        character c = input[(*pos)++];
        if (c == '\\') {
            c = input[(*pos)++];
            if (c == 0) {
                break;
            }
            buffer[bufpos++] = '\\';
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
        } else if (c == '{') {
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
            asSeq = true;
            depth++;
        } else if (c == '}') {
            if (depth-- > 0) {
                buffer[bufpos++] = c;
                buffer[bufpos] = 0;
            } else {
                if (asSeq) {
                    size_t new_pos = 0;
                    node *seq = parse_seq(buffer, &new_pos);
                    append(root, seq);
                } else {
                    append(root, make_leaf(allocate_string(buffer)));
                }
                break;
            }
        } else if (c == ',') {
            if (depth == 0) {
                if (asSeq) {
                    size_t new_pos = 0;
                    node *seq = parse_seq(buffer, &new_pos);
                    append(root, seq);
                    bufpos = 0;
                    buffer[bufpos] = 0;
                    asSeq = false;
                } else {
                    append(root, make_leaf(allocate_string(buffer)));
                    bufpos = 0;
                    buffer[bufpos] = 0;
                }
            } else {
                buffer[bufpos++] = c;
                buffer[bufpos] = 0;
            }
        } else {
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
        }
    }

    return root;
}

node *parse_seq(string input, size_t *pos) {
    node *root = make_seq();

    character buffer[BUFFER_SIZE] = { 0 };
    size_t bufpos = 0;

    while (input[*pos] != 0) {
        character c = input[(*pos)++];
        if (c == '\\') {
            c = input[(*pos)++];
            if (c == 0) {
                break;
            }
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
        } else if (c == '{') {
            node *tree = parse_tree(input, pos);
            if (bufpos > 0) {
                append(root, make_leaf(allocate_string(buffer)));
                bufpos = 0;
                buffer[bufpos] = 0;
            }
            append(root, tree);
        } else {
            buffer[bufpos++] = c;
            buffer[bufpos] = 0;
        }
    }

    if (bufpos > 0) {
        append(root, make_leaf(allocate_string(buffer)));
        bufpos = 0;
        buffer[bufpos] = 0;
    }

    return root;
}

void test(string input) {
    size_t pos = 0;
    node *n = parse_seq(input, &pos);
    size_t cnt = count(n);
    size_t i;

    printf("Pattern: %s\n", input);

    for (i = 0; i < cnt; i++) {
        expand(n, i);
        printf("\n");
    }
    printf("\n");

    deallocate_node(n);
}

int main() {
    test("~/{Downloads,Pictures}/*.{jpg,gif,png}");
    test("It{{em,alic}iz,erat}e{d,}, please.");
    test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!");

    //not sure how to parse this one
    //test("{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}");

    return 0;
}


(defun calendar (year)
    (define months-list '(("JANUARY" 31) ("FEBRUARY" 28) ("MARCH" 31) ("APRIL" 30) ("MAY" 31) ("JUNE" 30) ("JULY" 31) ("AUGUST" 31) ("SEPTEMBER" 30) ("OCTOBER" 31) ("NOVEMBER" 30) ("DECEMBER" 31)))
    (define days #("      Sunday            " "Monday            " "Tuesday           " "Wednesday         " "Thursday          " "Friday            " "Saturday"))
    (defun gauss-algorithm (a)
        (rem (+ 1 (+ (* 5 (rem (- a 1) 4)) (* 4 (rem (- a 1) 100)) (* 6 (rem (- a 1) 400)))) 7))
    (defun range (start end)
        (if (<= start end)
            (cons start (range (+ start 1) end))))
    (defun string-repeat (s n)
        (if (= n 0)
            ""
            (string-append s (string-repeat s (- n 1)))))
    (defun print-month (number-of-days start-day)
        (defun print-days (day day-of-week end-day)
            (if (= day-of-week 7)
                (begin
                    (newline)
                    (define day-of-week 0)))
            (display (string-repeat " " 8))
            (if (= day-of-week 0)
                (display (string-repeat " " 6)))
            (if (< day 10)
                (display " "))
            (display day)
            (display (string-repeat " " 8))
            (if (= day end-day)
                (begin
                    (fresh-line)
                    (+ day-of-week 1))
                (print-days (+ day 1) (+ day-of-week 1) end-day)))
        (mapcar (lambda (n) (display (vector-ref days n))) (range 0 6))
        (newline)
        (display (string-repeat (string-repeat " " 18) start-day))
        (print-days 1 start-day number-of-days))
    (defun leap-yearp (y)
        (and (= (mod year 4) 0) (or (/= (mod year 100) 0) (= (mod year 400) 0))))
    (define months (make-table))
    (mapcar (lambda (month) (table-set! months (car month) (cadr month))) months-list)
    (if (leap-yearp year)
        (table-set! months "FEBRUARY" 29))
    (defun print-calendar (calendar-months weekday)
        (newline)
        (newline)
        (display (string-repeat " " 60))
        (display (caar calendar-months))
        (newline)
        (define next-month-starts (print-month (table-ref months (caar calendar-months)) weekday))
        (if (cdr calendar-months)
            (print-calendar (cdr calendar-months) next-month-starts)))
    (display (string-repeat " " 60))
    (display "******** SNOOPY CALENDAR ")
    (display year)
    (display " ********")
    (newline)
    (newline)
    (print-calendar months-list (gauss-algorithm year)))

(calendar 1969)


if true: echo "yes"
if false: echo "no"

# Other objects never represent true or false:
if 2: echo "compile error"


VAR
  a,b,c: BOOLEAN;
...
  a := TRUE;
  b := FALSE;
  c := 1 > 2;


#include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>

namespace detail {

template <typename ForwardIterator>
class tokenizer
{

	ForwardIterator _tbegin, _tend, _end;

public:

	tokenizer(ForwardIterator begin, ForwardIterator end)
		: _tbegin(begin), _tend(begin), _end(end)
	{ }

	template <typename Lambda>
	bool next(Lambda istoken)
	{
		if (_tbegin == _end) {
			return false;
		}
		_tbegin = _tend;
		for (; _tend != _end && !istoken(*_tend); ++_tend) {
			if (*_tend == '\\' && std::next(_tend) != _end) {
				++_tend;
			}
		}
		if (_tend == _tbegin) {
			_tend++;
		}
		return _tbegin != _end;
	}

	ForwardIterator begin() const { return _tbegin; }
	ForwardIterator end()   const { return _tend; }
	bool operator==(char c) { return *_tbegin == c; }

};

template <typename List>
void append_all(List & lista, const List & listb)
{
	if (listb.size() == 1) {
		for (auto & a : lista) {
			a += listb.back();
		}
	} else {
		List tmp;
		for (auto & a : lista) {
			for (auto & b : listb) {
				tmp.push_back(a + b);
			}
		}
		lista = std::move(tmp);
	}
}

template <typename String, typename List, typename Tokenizer>
List expand(Tokenizer & token)
{

	std::vector<List> alts{ { String() } };

	while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {

		if (token == '{') {
			append_all(alts.back(), expand<String, List>(token));
		} else if (token == ',') {
			alts.push_back({ String() });
		} else if (token == '}') {
			if (alts.size() == 1) {
				for (auto & a : alts.back()) {
					a = '{' + a + '}';
				}
				return alts.back();
			} else {
				for (std::size_t i = 1; i < alts.size(); i++) {
					alts.front().insert(alts.front().end(),
						std::make_move_iterator(std::begin(alts[i])),
						std::make_move_iterator(std::end(alts[i])));
				}
				return std::move(alts.front());
			}
		} else {
			for (auto & a : alts.back()) {
				a.append(token.begin(), token.end());
			}
		}

	}

	List result{ String{ '{' } };
	append_all(result, alts.front());
	for (std::size_t i = 1; i < alts.size(); i++) {
		for (auto & a : result) {
			a += ',';
		}
		append_all(result, alts[i]);
	}
	return result;
}

} // namespace detail

template <
	typename ForwardIterator,
	typename String = std::basic_string<
		typename std::iterator_traits<ForwardIterator>::value_type
	>,
	typename List = std::vector<String>
>
List expand(ForwardIterator begin, ForwardIterator end)
{
	detail::tokenizer<ForwardIterator> token(begin, end);
	List list{ String() };
	while (token.next([](char c) { return c == '{'; })) {
		if (token == '{') {
			detail::append_all(list, detail::expand<String, List>(token));
		} else {
			for (auto & a : list) {
				a.append(token.begin(), token.end());
			}
		}
	}
	return list;
}

template <
	typename Range,
	typename String = std::basic_string<typename Range::value_type>,
	typename List = std::vector<String>
>
List expand(const Range & range)
{
	using Iterator = typename Range::const_iterator;
	return expand<Iterator, String, List>(std::begin(range), std::end(range));
}

int main()
{

	for (std::string string : {
		R"(~/{Downloads,Pictures}/*.{jpg,gif,png})",
		R"(It{{em,alic}iz,erat}e{d,}, please.)",
		R"({,{,gotta have{ ,\, again\, }}more }cowbell!)",
		R"({}} some {\\{edge,edgy} }{ cases, here\\\})",
		R"(a{b{1,2}c)",
		R"(a{1,2}b}c)",
		R"(a{1,{2},3}b)",
		R"(a{b{1,2}c{}})",
		R"(more{ darn{ cowbell,},})",
		R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)",
		R"({a,{\,b}c)",
		R"(a{b,{{c}})",
		R"({a{\}b,c}d)",
		R"({a,b{{1,2}e}f)",
		R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})",
		R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)",
	}) {
		std::cout << string << '\n';
		for (auto expansion : expand(string)) {
			std::cout << "    " << expansion << '\n';
		}
		std::cout << '\n';
	}

	return 0;
}


dig[] = [ 1 2 3 4 5 6 7 8 9 ]
for i range 4
  h = i + random (9 - i)
  swap dig[i] dig[h]
.
# print dig[]
len g[] 4
attempts = 0
repeat
  repeat
    ok = 0
    s$[] = strchars input
    if len s$[] = 4
      ok = 1
      for i range 4
        g[i] = number s$[i]
        if g[i] = 0
          ok = 0
        .
      .
    .
    until ok = 1
  .
  print g[]
  attempts += 1
  bulls = 0
  cows = 0
  for i range 4
    if g[i] = dig[i]
      bulls += 1
    else
      for j range 4
        if dig[j] = g[i]
          cows += 1
        .
      .
    .
  .
  print "bulls:" & bulls & " cows:" & cows
  until bulls = 4
.
print "Well done! " & attempts & " attempts needed."


class
	BULLS_AND_COWS

create
	execute

feature

	execute
			-- Initiate game.
		do
			io.put_string ("Let's play bulls and cows.%N")
			create answer.make_empty
			play
		end

feature {NONE}

	play
			-- Plays bulls ans cows.
		local
			count, seed: INTEGER
			guess: STRING
		do
			from
			until
				seed > 0
			loop
				io.put_string ("Enter a positive integer.%NYour play will be generated from it.%N")
				io.read_integer
				seed := io.last_integer
			end
			generate_answer (seed)
			io.put_string ("Your game has been created.%N Try to guess the four digit number.%N")
			create guess.make_empty
			from
			until
				guess ~ answer
			loop
				io.put_string ("Guess: ")
				io.read_line
				guess := io.last_string
				if guess.count = 4 and guess.is_natural and not guess.has ('0') then
					io.put_string (score (guess) + "%N")
					count := count + 1
				else
					io.put_string ("Your input does not have the correct format.")
				end
			end
			io.put_string ("Congratulations! You won with " + count.out + " guesses.")
		end

	answer: STRING

	generate_answer (s: INTEGER)
			-- Answer with 4-digits between 1 and 9 stored in 'answer'.
		require
			positive_seed: s > 0
		local
			random: RANDOM
			ran: INTEGER
		do
			create random.set_seed (s)
			from
			until
				answer.count = 4
			loop
				ran := (random.double_item * 10).floor
				if ran > 0 and not answer.has_substring (ran.out) then
					answer.append (ran.out)
				end
				random.forth
			end
		ensure
			answer_not_void: answer /= Void
			correct_length: answer.count = 4
		end

	score (g: STRING): STRING
			-- Score for the guess 'g' depending on 'answer'.
		require
			same_length: answer.count = g.count
		local
			k: INTEGER
			a, ge: STRING
		do
			Result := ""
			a := answer.twin
			ge := g.twin
			across
				1 |..| a.count as c
			loop
				if a [c.item] ~ ge [c.item] then
					Result := Result + "BULL "
					a [c.item] := ' '
					ge [c.item] := ' '
				end
			end
			across
				1 |..| a.count as c
			loop
				if a [c.item] /= ' ' then
					k := ge.index_of (a [c.item], 1)
					if k > 0 then
						Result := Result + "COW "
						ge [k] := ' '
					end
				end
			end
		end

end


include c:\cxpl\codes;          \intrinsic 'code' declarations

func WeekDay(Year, Month, Day); \Return day of week (0=Sun 1=Mon..6=Sat)
int  Year, Month, Day;          \Works for years from 1583 onward
[if Month<=2 then [Month:= Month+12;  Year:= Year-1];
return rem((Day-1 + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400)/7);
];

proc Space(N);                  \Display N space characters
int  N;
while N do [ChOut(0, ^ );  N:= N-1];

proc Calendar(Year);            \Display calendar for specified year
int  Year;
int  Month, Col, C, Line, MoName, Days, DayMax, Day(3);
[MoName:= [
  " January ", " February", "  March  ", "  April  ", "   May   ", "   June  ",
  "   July  ", "  August ", "September", "  October", " November", " December"];
Space(35);  Text(0, "[Snoopy]");  CrLf(0);
Space(37);  IntOut(0, Year);  CrLf(0);
CrLf(0);
for Month:= 1 to 12 do
  [for Col:= 0 to 3-1 do
    [Space(5);  Text(0, MoName(Month+Col-1));  Space(7);
    if Col<2 then Space(8);
    ];
  CrLf(0);
  for Col:= 0 to 3-1 do
    [Text(0, "Su Mo Tu We Th Fr Sa");
    if Col<2 then Space(9);
    ];
  CrLf(0);
  for Col:= 0 to 3-1 do         \day of first Sunday of month (can be negative)
    Day(Col):= 1 - WeekDay(Year, Month+Col, 1);
  for Line:= 0 to 6-1 do
    [for Col:= 0 to 3-1 do
      [Days:= [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      DayMax:= Days(Month+Col);
      if Month+Col=2 & (rem(Year/4)=0 & rem(Year/100)#0 ! rem(Year/400)=0) then
        DayMax:= DayMax+1;      \if February and leap year then add a day
      for C:= 0 to 7-1 do
        [if Day(Col)>=1 & Day(Col)<=DayMax then
          [IntOut(0, Day(Col));
          if Day(Col)<10 then Space(1); \left justify
          ]
        else Space(2);          \suppress out of range days
        Space(1);
        Day(Col):= Day(Col)+1;
        ];
      if Col<2 then Space(8);
      ];
    CrLf(0);
    ];
  CrLf(0);
  Month:= Month+2;              \2+1 months per Col(umn)
  ];
];

Calendar(1969)


my $x = 0.0;
my $true_or_false = $x ? 'true' : 'false';     # false


F isPrime(n)
   I n % 2 == 0
      R n == 2
   I n % 3 == 0
      R n == 3
   V d = 5
   L d * d <= n
      I n % d == 0
         R 0B
      I n % (d + 2) == 0
         R 0B
      d += 6
   R 1B

F sameDigits(=n, b)
   V d = n % b
   n I/= b
   I d == 0
      R 0B
   L n > 0
      I n % b != d
         R 0B
      n I/= b
   R 1B

F isBrazilian(n)
   I n < 7
      R 0B
   I (n [&] 1) == 0
      R 1B
   L(b) 2 .. n - 2
      I sameDigits(n, b)
         R 1B
   R 0B

F printList(title, check)
   print(title)
   V n = 7
   [Int] l
   L
      I check(n) & isBrazilian(n)
         l.append(n)
         I l.len == 20 {L.break}
      n++
   print(l.join(‘, ’))
   print()

printList(‘First 20 Brazilian numbers:’, n -> 1B)
printList(‘First 20 odd Brazilian numbers:’, n -> (n [&] 1) != 0)
printList(‘First 20 prime Brazilian numbers:’, n -> isPrime(n))


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

public static class BraceExpansion
{
    enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat }
    const char L = '{', R = '}', S = ',';

    public static void Main() {
        string[] input = {
            "It{{em,alic}iz,erat}e{d,}, please.",
            "~/{Downloads,Pictures}/*.{jpg,gif,png}",
            @"{,{,gotta have{ ,\, again\, }}more }cowbell!",
            @"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"
        };
        foreach (string text in input) Expand(text);
    }

    static void Expand(string input) {
        Token token = Tokenize(input);
        foreach (string value in token) Console.WriteLine(value);
        Console.WriteLine();
    }

    static Token Tokenize(string input) {
        var tokens = new List<Token>();
        var buffer = new StringBuilder();
        bool escaping = false;
        int level = 0;

        foreach (char c in input) {
            (escaping, level, tokens, buffer) = c switch {
                _ when escaping => (false, level, tokens, buffer.Append(c)),
                '\\' => (true, level, tokens, buffer.Append(c)),
                L => (escaping, level + 1,
                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer),
                S when level > 0 => (escaping, level,
                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer),
                R when level > 0 => (escaping, level - 1,
                    tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer),
                _ => (escaping, level, tokens, buffer.Append(c))
            };
        }
        if (buffer.Length > 0) tokens.Add(buffer.Flush());
        for (int i = 0; i < tokens.Count; i++) {
            if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) {
                tokens[i] = tokens[i].Value; //Change to text
            }
        }
        return new Token(tokens, TokenType.Concat);
    }

    static List<Token> Merge(this List<Token> list) {
        int separators = 0;
        int last = list.Count - 1;
        for (int i = list.Count - 3; i >= 0; i--) {
            if (list[i].Type == TokenType.Separator) {
                separators++;
                Concat(list, i + 1, last);
                list.RemoveAt(i);
                last = i;
            } else if (list[i].Type == TokenType.OpenBrace) {
                Concat(list, i + 1, last);
                if (separators > 0) {
                    list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate);
                    list.RemoveRange(i+1, list.Count - i - 1);
                } else {
                    list[i] = L.ToString();
                    list[^1] = R.ToString();
                    Concat(list, i, list.Count);
                }
                break;
            }
        }
        return list;
    }

    static void Concat(List<Token> list, int s, int e) {
        for (int i = e - 2; i >= s; i--) {
            (Token a, Token b) = (list[i], list[i+1]);
            switch (a.Type, b.Type) {
                case (TokenType.Text, TokenType.Text):
                    list[i] = a.Value + b.Value;
                    list.RemoveAt(i+1);
                    break;
                case (TokenType.Concat, TokenType.Concat):
                    a.SubTokens.AddRange(b.SubTokens);
                    list.RemoveAt(i+1);
                    break;
                case (TokenType.Concat, TokenType.Text) when b.Value == "":
                    list.RemoveAt(i+1);
                    break;
                case (TokenType.Text, TokenType.Concat) when a.Value == "":
                    list.RemoveAt(i);
                    break;
                default:
                    list[i] = new Token(new [] { a, b }, TokenType.Concat);
                    list.RemoveAt(i+1);
                    break;
            }
        }
    }

    private struct Token : IEnumerable<string>
    {
        private List<Token>? _subTokens;

        public string Value { get; }
        public TokenType Type { get; }
        public List<Token> SubTokens => _subTokens ??= new List<Token>();

        public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null);
        public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList());

        public static implicit operator Token(string value) => new Token(value, TokenType.Text);

        public IEnumerator<string> GetEnumerator() => (Type switch
        {
            TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)),
            TokenType.Alternate => from t in SubTokens from s in t select s,
            _ => Repeat(Value, 1)
        }).GetEnumerator();

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }

    //===Extension methods===
    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {
        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() };
        return sequences.Aggregate(
            emptyProduct,
            (accumulator, sequence) =>
                from acc in accumulator
                from item in sequence
                select acc.Concat(new [] { item }));
    }

    static List<Token> With(this List<Token> list, Token token) {
        list.Add(token);
        return list;
    }

    static IEnumerable<Token> Range(this List<Token> list, Range range) {
        int start = range.Start.GetOffset(list.Count);
        int end = range.End.GetOffset(list.Count);
        for (int i = start; i < end; i++) yield return list[i];
    }

    static string Flush(this StringBuilder builder) {
        string result = builder.ToString();
        builder.Clear();
        return result;
    }
}


import system'routines;
import extensions;

class GameMaster
{
    object theNumbers;
    object theAttempt;

    constructor()
    {
        // generate secret number
        var randomNumbers := new int[]{1,2,3,4,5,6,7,8,9}.randomize(9);

        theNumbers := randomNumbers.Subarray(0, 4);
        theAttempt := new Integer(1);
    }

    ask()
    {
        var row := console.print("Your Guess #",theAttempt," ?").readLine();

        ^ row.toArray()
    }

    proceed(guess)
    {
        int cows := 0;
        int bulls := 0;

        if (guess.Length != 4)
        {
            bulls := -1
        }
        else
        {
            try
            {
                for (int i := 0, i < 4, i+=1) {
                    var ch := guess[i];
                    var number := ch.toString().toInt();

                    // check range
                    ifnot (number > 0 && number < 10)
                        { InvalidArgumentException.raise() };

                    // check duplicates
                    var duplicate := guess.seekEach:(x => (x == ch)&&(x.equalReference(ch).Inverted));
                    if (nil != duplicate)
                    {
                        InvalidArgumentException.raise()
                    };

                    if (number == theNumbers[i])
                    {
                        bulls += 1
                    }
                    else
                    {
                        if (theNumbers.ifExists(number))
                            { cows += 1 }
                    }
                }
            }
            catch(Exception e)
            {
                bulls := -1
            }
        };

        bulls =>
            -1 { console.printLine:"Not a valid guess."; ^ true }
             4 { console.printLine:"Congratulations! You have won!"; ^ false }
             : {
                 theAttempt.append(1);

                 console.printLine("Your Score is ",bulls," bulls and ",cows," cows");

                 ^ true
             }
    }
}

public program()
{
    var gameMaster := new GameMaster();

    (lazy:gameMaster.proceed(gameMaster.ask())).doWhile();

    console.readChar()
}


defmodule Bulls_and_cows do
  def play(size \\ 4) do
    secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1)
    play(size, secret)
  end

  defp play(size, secret) do
    guess = input(size)
    if guess == secret do
      IO.puts "You win!"
    else
      {bulls, cows} = count(guess, secret)
      IO.puts "  Bulls: #{bulls}; Cows: #{cows}"
      play(size, secret)
    end
  end

  defp input(size) do
    guess = IO.gets("Enter your #{size}-digit guess: ") |> String.strip
    cond do
      guess == "" ->
        IO.puts "Give up"
        exit(:normal)
      String.length(guess)==size and String.match?(guess, ~r/^[1-9]+$/) ->
        String.codepoints(guess)
      true -> input(size)
    end
  end

  defp count(guess, secret) do
    Enum.zip(guess, secret) |>
    Enum.reduce({0,0}, fn {g,s},{bulls,cows} ->
      cond do
        g == s      -> {bulls + 1, cows}
        g in secret -> {bulls, cows + 1}
        true        -> {bulls, cows}
      end
    end)
  end
end

Bulls_and_cows.play


clear screen

sub snoopy()
	local n, a$

	n = open("snoopy.txt", "r")

	while(not eof(#n))
		line input #n a$
		print "  "; : print color("black", "white") a$
	wend

	close #n
end sub

sub floor(n)
	return int(n + 0.5)
end sub

sub string.rep$(s$, n)
	local i, r$

	for i = 1 to n
		r$ = r$ + s$
	next i

	return r$
end sub

sub center$(s$, width)
	local fill1

	fill1 = floor(width - len(s$)) / 2

	return string.rep$(" ",fill1) + s$ + string.rep$(" ",fill1)
end sub

sub makeMonth(name, skip, days, cal$(), j)
	local cal, curday, line$, i

	curday = 1 - skip
	cal = 3

	cal$(j, 2) = " " + daysTitle$ + " "
	//cal$(j, 1) = center$(months$(name),len(cal$(j, 2)))
	cal$(j, 1) = left$(months$(name) + string.rep$(" ", 80), len(cal$(j, 2)))

	while(cal < 9)
  		line$ = ""
  		for i = 1 to 7
    		    if curday < 1 or curday > days then
      			line$ = line$ + "   "
    		    else
      			line$ = line$ + str$(curday, "###")
    		    end if
    		    curday = curday + 1
  		next
  		cal = cal + 1
  		cal$(j, cal) = line$ + " "
	wend
end sub

dim months$(12)
n = token("JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER", months$(), ",")
daysTitle$ = "MO TU WE TH FR SA SU"
dim daysPerMonth(12)
for n = 1 to 12
	read daysPerMonth(n)
next
data 31,28,31,30,31,30,31,31,30,31,30,31

sub print_cal(year)
	local i, q, l, m, startday, sep, monthwidth, calwidth, dpm, calendar$(12, 9), line$(3)

	startday=mod(((year-1)*365+floor((year-1)/4)-floor((year-1)/100)+floor((year-1)/400)),7)
 	if not mod(year,4) and mod(year,100) or not mod(year,400) then
    	    daysPerMonth(2)=29
  	end if

  	sep = 5
  	monthwidth = len(daysTitle$)
	calwidth = 3 * monthwidth + 2 * sep

	for i = 1 to 12
    	    dpm = daysPerMonth(i)
    	    makeMonth(i, startday, dpm, calendar$(), i)
    	    startday = mod(startday + dpm, 7)
	next

	snoopy()
 	print center$("--- " + str$(year) + " ---", calwidth), "\n"

 	print string.rep$(" ", sep + 1);
 	for q = 0 to 3
     	    for l = 1 to 9
       		for m = 1 to 3
         		print calendar$(q * 3 + m, l);
       		next
       		print
       		print string.rep$(" ", sep);
     	    next
     	    print
     	    print string.rep$(" ", sep + 1);
 	next
end sub

print_cal(2018)


INCLUDE "H6:SIEVE.ACT"

BYTE FUNC SameDigits(INT x,b)
  INT d

  d=x MOD b
  x==/b
  WHILE x>0
  DO
    IF x MOD b#d THEN
      RETURN (0)
    FI
    x==/b
  OD
RETURN (1)

BYTE FUNC IsBrazilian(INT x)
  INT b

  IF x<7 THEN RETURN (0) FI
  IF x MOD 2=0 THEN RETURN (1) FI
  FOR b=2 TO x-2
  DO
    IF SameDigits(x,b) THEN
      RETURN (1)
    FI
  OD
RETURN (0)

PROC Main()
  DEFINE COUNT="20"
  DEFINE MAXNUM="3000"
  BYTE ARRAY primes(MAXNUM+1)
  INT i,x,c
  CHAR ARRAY s

  Put(125) PutE() ;clear the screen
  Sieve(primes,MAXNUM+1)

  FOR i=0 TO 2
  DO
    IF i=0 THEN
      s=" "
    ELSEIF i=1 THEN
      s=" odd "
    ELSE
      s=" prime "
    FI
    PrintF("First %I%SBrazilian numbers:%E",COUNT,s)
    c=0 x=7
    DO
      IF IsBrazilian(x) THEN
        PrintI(x) Put(32)
        c==+1
        IF c=COUNT THEN EXIT FI
      FI
      IF i=0 THEN
        x==+1
      ELSEIF i=1 THEN
        x==+2
      ELSE
        DO
          x==+2
        UNTIL primes(x)
        OD
      FI
    OD
    PutE() PutE()
  OD
RETURN


begin % 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           %
    procedure BrazilianSieve ( logical array b ( * ) ; integer value n ) ;
    begin
        logical isEven;
        % start with even numbers flagged as Brazilian and odd numbers as    %
        % non-Brazilian                                              %
        isEven := false;
        for i := 1 until n do begin
            b( i ) := isEven;
            isEven := not isEven
        end for_i ;
        % numbers below 7 are not Brazilian (see task notes)                 %
        for i := 1 until 6 do b( i ) := false;
        % flag all 33, 55, etc. numbers in each base as Brazilian            %
        % No Brazilian number can have a representation of 11 in any base B  %
        %    as that would mean B + 1 = N, which contradicts B < N - 1       %
        % also, no need to consider even digits as we know even numbers > 6  %
        %    are all Brazilian                                               %
        for base := 2 until n div 2 do begin
            integer b11, bnn;
            b11 := base + 1;
            bnn := b11;
            for digit := 3 step 2 until base - 1 do begin
                bnn := bnn + b11 + b11;
                if bnn <= n
                then b( bnn ) := true
                else goto end_for_digits
            end for_digits ;
end_for_digits:
        end for_base ;
        % handle 111, 1111, 11111, ..., 333, 3333, ..., etc.                 %
        for base := 2 until truncate( sqrt( n ) ) do begin
            integer powerMax;
            powerMax := MAXINTEGER div base;              % avoid 32 bit     %
            if powerMax > n then powerMax := n;           % integer overflow %
            for digit := 1 step 2 until base - 1 do begin
                integer bPower, bN;
                bPower := base * base;
                bN     := digit * ( bPower + base + 1 ); % ddd               %
                while bN <= n and bPower <= powerMax do begin
                    if bN <= n then begin
                        b( bN ) := true
                    end if_bN_le_n ;
                    bPower := bPower * base;
                    bN     := bN + ( digit * bPower )
                end while_bStart_le_n
            end for_digit
        end for_base ;
    end BrazilianSieve ;
    % sets p( 1 :: n ) to a sieve of primes up to n                          %
    procedure Eratosthenes ( logical array p( * ) ; integer value n ) ;
    begin
        p( 1 ) := false; p( 2 ) := true;
        for i := 3 step 2 until n do p( i ) := true;
        for i := 4 step 2 until n do p( i ) := false;
        for i := 2 until truncate( sqrt( n ) ) do begin
            integer ii; ii := i + i;
            if p( i ) then for pr := i * i step ii until n do p( pr ) := false
        end for_i ;
    end Eratosthenes ;

    integer MAX_NUMBER;
    MAX_NUMBER := 2000000;
    begin
        logical array b ( 1 :: MAX_NUMBER );
        logical array p ( 1 :: MAX_NUMBER );
        integer bCount;
        BrazilianSieve( b, MAX_NUMBER );
        write( "The first 20 Brazilian numbers:" );write();
        bCount := 0;
        for bPos := 1 until MAX_NUMBER do begin
            if b( bPos ) then begin
                bCount := bCount + 1;
                writeon( i_w := 1, s_w := 0, " ", bPos );
                if bCount >= 20 then goto end_first_20
            end if_b_bPos
        end for_bPos ;
end_first_20:
        write();write( "The first 20 odd Brazilian numbers:" );write();
        bCount := 0;
        for bPos := 1 step 2 until MAX_NUMBER do begin
            if b( bPos ) then begin
                bCount := bCount + 1;
                writeon( i_w := 1, s_w := 0, " ", bPos );
                if bCount >= 20 then goto end_first_20_odd
            end if_b_bPos
        end for_bPos ;
end_first_20_odd:
        write();write( "The first 20 prime Brazilian numbers:" );write();
        Eratosthenes( p, MAX_NUMBER );
        bCount := 0;
        for bPos := 1 until MAX_NUMBER do begin
            if b( bPos ) and p( bPos ) then begin
                bCount := bCount + 1;
                writeon( i_w := 1, s_w := 0, " ", bPos );
                if bCount >= 20 then goto end_first_20_prime
            end if_b_bPos
        end for_bPos ;
end_first_20_prime:
        write();write( "Various Brazilian numbers:" );
        bCount := 0;
        for bPos := 1 until MAX_NUMBER do begin
            if b( bPos ) then begin
                bCount := bCount + 1;
                if   bCount  =     100
                or   bCount  =    1000
                or   bCount  =   10000
                or   bCount  =  100000
                or   bCount  = 1000000
                then write( s_w := 0, bCount, "th Brazilian number: ", bPos );
                if   bCount >= 1000000 then goto end_1000000
            end if_b_bPos
        end for_bPos ;
end_1000000:
    end
end.


on isBrazilian(n)
    repeat with b from 2 to n - 2
        set d to n mod b
        set temp to n div b
        repeat while (temp mod b = d) -- ((temp > 0) and (temp mod b = d))
            set temp to temp div b
        end repeat
        if (temp = 0) then return true
    end repeat

    return false
end isBrazilian

on isPrime(n)
    if (n < 4) then return (n > 1)
    if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
    repeat with i from 5 to (n ^ 0.5) div 1 by 6
        if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
    end repeat

    return true
end isPrime

-- Task code:
on runTask()
    set output to {}
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to "  "

    set collector to {}
    set n to 1
    repeat until ((count collector) is 20)
        if (isBrazilian(n)) then set end of collector to n
        set n to n + 1
    end repeat
    set end of output to "First 20 Brazilian numbers:  " & linefeed & collector

    set collector to {}
    set n to 1
    repeat until ((count collector) is 20)
        if (isBrazilian(n)) then set end of collector to n
        set n to n + 2
    end repeat
    set end of output to "First 20 odd Brazilian numbers:  " & linefeed & collector

    set collector to {}
    if (isBrazilian(2)) then set end of collector to 2
    set n to 3
    repeat until ((count collector) is 20)
        if (isPrime(n)) and (isBrazilian(n)) then set end of collector to n
        set n to n + 2
    end repeat
    set end of output to "First 20 prime Brazilian numbers:  " & linefeed & collector

    set AppleScript's text item delimiters to linefeed
    set output to output as text
    set AppleScript's text item delimiters to astid
    return output
end runTask

return runTask()


(defstruct alternation
  (alternatives nil :type list))

(defun alternatives-end-positions (string start)
  (assert (char= (char string start) #\{))
  (loop with level = 0
        with end-positions
        with escapep and commap
        for index from start below (length string)
        for c = (char string index)
        do (cond (escapep
                  (setf escapep nil))
                 ((char= c #\\)
                  (setf escapep t))
                 ((char= c #\{)
                  (incf level))
                 ((char= c #\})
                  (decf level)
                  (when (zerop level)
                    (push index end-positions)
                    (loop-finish)))
                 ((and (char= c #\,) (= level 1))
                  (setf commap t)
                  (push index end-positions)))
        finally (return (and (zerop level) commap (nreverse end-positions)))))

(defun parse-alternation (string start)
  (loop with end-positions = (alternatives-end-positions string start)
        for %start = (1+ start) then (1+ %end)
        for %end in end-positions
        collect (parse string :start %start :end %end) into alternatives
        finally (return (and alternatives
                             (values (make-alternation :alternatives alternatives) (1+ %end))))))

(defun parse (string &key (start 0) (end (length string)))
  (loop with result and escapep
        for index = start then next
        while (< index end)
        for c = (char string index)
        for next = (1+ index)
        do (cond (escapep
                  (push c result)
                  (setf escapep nil))
                 ((char= c #\\)
                  (push c result)
                  (setf escapep t))
                 ((char= c #\{)
                  (multiple-value-bind (alternation next-index)
                      (parse-alternation string index)
                    (cond (alternation
                           (push alternation result)
                           (setf next next-index))
                          (t
                           (push c result)))))
                 (t
                  (push c result)))
        finally (return (nreverse result))))

(defun traverse-alternation (alternation)
  (mapcan #'traverse (alternation-alternatives alternation)))

(defun traverse (parsed)
  (let ((results (list nil)))
    (dolist (element parsed results)
      (etypecase element
        (character
         (setf results (loop for r in results
                             collect (nconc r (list element)))))
        (alternation
         (setf results (loop for r in results
                             nconc (loop for ar in (traverse-alternation element)
                                         collect (append r ar)))))))))

(defun expand (string)
  (loop for result in (traverse (parse string))
        collect (coerce result 'string)))

(defun main ()
  (dolist (input '("~/{Downloads,Pictures}/*.{jpg,gif,png}"
                   "It{{em,alic}iz,erat}e{d,}, please."
                   "{,{,gotta have{ ,\\, again\\, }}more }cowbell!"
                   "{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}"))
    (write-line input)
    (dolist (output (expand input))
      (format t "    ~A~%" output))
    (terpri)))


-module(bulls_and_cows).
-export([generate_secret/0, score_guess/2, play/0]).

% generate the secret code
generate_secret() -> generate_secret([], 4, lists:seq(1,9)).
generate_secret(Secret, 0, _) -> Secret;
generate_secret(Secret, N, Digits) ->
  Next = lists:nth(random:uniform(length(Digits)), Digits),
  generate_secret(Secret ++ [Next], N - 1, Digits -- [Next]).

% evaluate a guess
score_guess(Secret, Guess)
  when length(Secret) =/= length(Guess) -> throw(badguess);
score_guess(Secret, Guess) ->
  Bulls = count_bulls(Secret,Guess),
  Cows = count_cows(Secret, Guess, Bulls),
  [Bulls, Cows].

% count bulls (exact matches)
count_bulls(Secret, Guess) ->
  length(lists:filter(fun(I) -> lists:nth(I,Secret) == lists:nth(I,Guess) end,
                      lists:seq(1, length(Secret)))).

% count cows (digits present but out of place)
count_cows(Secret, Guess, Bulls) ->
   length(lists:filter(fun(I) -> lists:member(I, Guess) end, Secret)) - Bulls.

% play a game
play() -> play_round(generate_secret()).

play_round(Secret) -> play_round(Secret, read_guess()).

play_round(Secret, Guess) ->
  play_round(Secret, Guess, score_guess(Secret,Guess)).

play_round(_, _, [4,0]) ->
  io:put_chars("Correct!\n");

play_round(Secret, _, Score) ->
  io:put_chars("\tbulls:"), io:write(hd(Score)), io:put_chars(", cows:"),
  io:write(hd(tl(Score))), io:put_chars("\n"), play_round(Secret).

read_guess() ->
  lists:map(fun(D)->D-48 end,
    lists:sublist(io:get_line("Enter your 4-digit guess: "), 4)).


var [const] D=Time.Date, days="Su Mo Tu We Th Fr Sa";

fcn center(text,m) { String(" "*((m-text.len())/2),text) }

fcn oneMonth(year,month){
   day1:=D.zeller(year,month,1);    //1969-1-1 -->3 (Wed, ISO 8601)
   dayz:=D.daysInMonth(year,month); //1969-1   -->31
   List(center(D.monthNames[month],days.len()),days).extend(
      (1).pump(dayz,(0).pump(day1,List,T(Void,""))).apply("%2s ".fmt)
      .pump(List,T(Void.Read,days.len()/3,False),String.create));
}

const M=70;	// mystery number
fcn oneYear(y=1969,title="3 Days of Peace & Music"){
   println(center(title,M),"\n",center(y.toString(),M),"\n");
   [1..12,3].pump(String,'wrap(m){  // 3 months per line
      mmm:=(m).pump(3,List,oneMonth.fp(y)); //L(L(7-8 lines), L(...), L(...))
      if(mmm.apply("len").sum() % 3)  // months have diff # of lines, pad
	 mmm=mmm.apply("append","");
      Utils.zipWith("%-25s%-25s%-25s\n".fmt,
           mmm.xplode()).concat() + (if (m<D.October) "\n" else "")
   })
}

if(vm.numArgs){ y:=vm.nthArg(0).toInt(); oneYear(y,"").println(); }
else oneYear().println();


with javascript_semantics
for i=1 to 3 do
    integer c = (i==2),         -- fine
            d = (c==1),         -- oops
            e = (c==true),      -- fine
            f = equal(c,1)      -- fine, ditto equal(c,true)
    printf(1,"%d==2:%5t(%d) ==1:%5t, eq1:%5t, ==true:%5t\n",
              {i,     c, c,       d,       e,          f})
end for
--
-- output on desktop/Phix: 1==2:false(0) ==1:false, eq1:false, ==true:false
--                         2==2: true(1) ==1: true, eq1: true, ==true: true
--                         3==2:false(0) ==1:false, eq1:false, ==true:false
--
-- output on pwa/p2js:     1==2:false(0) ==1:false, eq1:false, ==true:false
--                         2==2: true(1) ==1:false, eq1: true, ==true: true
--                         3==2:false(0) ==1:false, eq1:false, ==true:false
--


brazilian?: function [n][
    if n < 7 -> return false
    if zero? and n 1 -> return true
    loop 2..n-2 'b [
        if 1 = size unique digits.base:b n ->
            return true
    ]
    return false
]

printFirstByRule: function [rule,title][
    print ~"First 20 |title|brazilian numbers:"
    i: 7
    found: new []
    while [20 > size found][
        if brazilian? i ->
            'found ++ i
        do.import rule
    ]
    print found
    print ""
]

printFirstByRule [i: i+1] ""
printFirstByRule [i: i+2] "odd "
printFirstByRule [i: i+2, while [not? prime? i] -> i: i+2] "prime "


# syntax: GAWK -f BRAZILIAN_NUMBERS.AWK
# converted from C
BEGIN {
    split(",odd ,prime ",kinds,",")
    for (i=1; i<=3; ++i) {
      printf("first 20 %sBrazilian numbers:",kinds[i])
      c = 0
      n = 7
      while (1) {
        if (is_brazilian(n)) {
          printf(" %d",n)
          if (++c == 20) {
            printf("\n")
            break
          }
        }
        switch (i) {
          case 1:
            n++
            break
          case 2:
            n += 2
            break
          case 3:
            do {
              n += 2
            } while (!is_prime(n))
            break
        }
      }
    }
    exit(0)
}
function is_brazilian(n,  b) {
    if (n < 7) { return(0) }
    if (!(n % 2) && n >= 8) { return(1) }
    for (b=2; b<n-1; ++b) {
      if (same_digits(n,b)) { return(1) }
    }
    return(0)
}
function is_prime(n,  d) {
    d = 5
    if (n < 2) { return(0) }
    if (!(n % 2)) { return(n == 2) }
    if (!(n % 3)) { return(n == 3) }
    while (d*d <= n) {
      if (!(n % d)) { return(0) }
      d += 2
      if (!(n % d)) { return(0) }
      d += 4
    }
    return(1)
}
function same_digits(n,b,  f) {
    f = n % b
    n = int(n/b)
    while (n > 0) {
      if (n % b != f) { return(0) }
      n = int(n/b)
    }
    return(1)
}