import strutils

proc missingPermutation(arr: openArray[string]): string =
  result = ""
  if arr.len == 0: return
  if arr.len == 1: return arr[0][1] & arr[0][0]

  for pos in 0 ..< arr[0].len:
    var s: set[char] = {}
    for permutation in arr:
      let c = permutation[pos]
      if c in s: s.excl c
      else:      s.incl c
    for c in s: result.add c

const given = """ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
  CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB""".splitWhiteSpace()

echo missingPermutation(given)


USING: math kernel io math.functions math.parser math.ranges ;
IN: fizzbuzz
: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ;
: buzz ( n -- str ) 5 divisor? "Buzz" "" ? ;
: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ;
: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ;
MAIN: main


(* insert x at all positions into li and return the list of results *)
let rec insert x = function
  | [] -> [[x]]
  | a::m as li -> (x::li) :: (List.map (fun y -> a::y) (insert x m))

(* list of all permutations of li *)
let permutations li =
  List.fold_right (fun a z -> List.concat (List.map (insert a) z)) li [[]]

(* convert a string to a char list *)
let chars_of_string s =
  let cl = ref [] in
  String.iter (fun c -> cl := c :: !cl) s;
  (List.rev !cl)

(* convert a char list to a string *)
let string_of_chars cl =
  String.concat "" (List.map (String.make 1) cl)


given = [ 'ABCD';'CABD';'ACDB';'DACB'; ...
          'BCDA';'ACBD';'ADCB';'CDAB'; ...
          'DABC';'BCAD';'CADB';'CDBA'; ...
          'CBAD';'ABDC';'ADBC';'BDCA'; ...
          'DCBA';'BACD';'BADC';'BDAC'; ...
          'CBDA';'DBCA';'DCAB' ];
val = 4.^(3:-1:0)';
there = 1+(toascii(given)-toascii('A'))*val;
every = 1+perms(0:3)*val;

bits = zeros(max(every),1);
bits(every) = 1;
bits(there) = 0;
missing = dec2base(find(bits)-1,'ABCD')


for i in [1:101]
    switch i % 15
    case 0        : > "FizzBuzz"
    case 5,10     : > "Buzz"
    case 3,6,9,12 : > "Fizz"
    default       : > i
    end
end


declare
  GivenPermutations =
  ["ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA"
   "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"]

  %% four distinct variables between "A" and "D":
  proc {Description Root}
     Root = {FD.list 4 &A#&D}
     {FD.distinct Root}
     {FD.distribute naiv Root}
  end

  AllPermutations = {SearchAll Description}
in
  for P in AllPermutations do
     if {Not {Member P GivenPermutations}} then
        {System.showInfo "Missing: "#P}
     end
  end


class FizzBuzz
{
  public static Void main ()
  {
    for (Int i:=1; i <= 100; ++i)
    {
      if (i % 15 == 0)
        echo ("FizzBuzz")
      else if (i % 3 == 0)
        echo ("Fizz")
      else if (i % 5 == 0)
        echo ("Buzz")
      else
        echo (i)
    }
  }
}


program MissPerm;
{$MODE DELPHI} //for result

const
  maxcol = 4;
type
  tmissPerm = 1..23;
  tcol = 1..maxcol;
  tResString = String[maxcol];
const
  Given_Permutations : array [tmissPerm] of tResString =
     ('ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD',
      'ADCB', 'CDAB', 'DABC', 'BCAD', 'CADB', 'CDBA',
      'CBAD', 'ABDC', 'ADBC', 'BDCA', 'DCBA', 'BACD',
      'BADC', 'BDAC', 'CBDA', 'DBCA', 'DCAB');
  chOfs =  Ord('A')-1;
var
  SumElemCol: array[tcol,tcol] of NativeInt;
function fib(n: NativeUint): NativeUint;
var
  i : NativeUint;
Begin
  result := 1;
  For i := 2 to n do
    result:= result*i;
end;

function CountOccurences: tresString;
//count the number of every letter in every column
//should be (colmax-1)! => 6
//the missing should count (colmax-1)! -1 => 5
var
  fibN_1 : NativeUint;
  row, col: NativeInt;
Begin
  For row := low(tmissPerm) to High(tmissPerm) do
    For col := low(tcol) to High(tcol) do
      inc(SumElemCol[col,ORD(Given_Permutations[row,col])-chOfs]);

  //search the missing
  fibN_1 := fib(maxcol-1)-1;
  setlength(result,maxcol);
  For col := low(tcol) to High(tcol) do
    For row := low(tcol) to High(tcol) do
      IF SumElemCol[col,row]=fibN_1 then
        result[col]:= ansichar(row+chOfs);
end;

function CheckXOR: tresString;
var
  row,col: NativeUint;
Begin
  setlength(result,maxcol);
  fillchar(result[1],maxcol,#0);
  For row := low(tmissPerm) to High(tmissPerm) do
    For col := low(tcol) to High(tcol) do
      result[col] := ansichar(ord(result[col]) XOR ord(Given_Permutations[row,col]));
end;

Begin
  writeln(CountOccurences,' is missing');
  writeln(CheckXOR,' is missing');
end.


sub check_perm {
    my %hash; @hash{@_} = ();
    for my $s (@_) { exists $hash{$_} or return $_
        for map substr($s,1) . substr($s,0,1), (1..length $s); }
}

# Check and display
@perms = qw(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
            CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB);
print check_perm(@perms), "\n";


with javascript_semantics
constant perms = {"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
                  "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
                  "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"}

-- 1: sum of letters
sequence r = repeat(0,4)
for i=1 to length(perms) do
    r = sq_add(r,perms[i])
end for
r = sq_sub(max(r)+'A',r)
printf(1,"%s\n",{r})
-- based on the notion that missing = sum(full)-sum(partial) would be true,
--  and that sum(full) would be like {M,M,M,M} rather than a mix of numbers.
-- the final step is equivalent to eg {1528,1530,1531,1529}
--                        max-r[i] -> {   3,   1,   0,   2}
--                        to chars -> {   D,   B,   A,   C}
-- (but obviously both done in one line)

-- 2: the xor trick
r = repeat(0,4)
for i=1 to length(perms) do
    r = sq_xor_bits(r,perms[i])
end for
printf(1,"%s\n",{r})
-- (relies on the missing chars being present an odd number of times, non-missing chars an even number of times)

-- 3: find least frequent letters
r = "    "
for i=1 to length(r) do
    sequence count = repeat(0,4)
    for j=1 to length(perms) do
        integer cdx = perms[j][i]-'A'+1
        count[cdx] += 1
    end for
    r[i] = smallest(count,1)+'A'-1
end for
printf(1,"%s\n",{r})
-- (relies on the assumption that a full set would have each letter occurring the same number of times in each position)
-- (smallest(count,1) returns the index position of the smallest, rather than it's value)

-- 4: test all permutations
for i=1 to factorial(4) do
    r = permute(i,"ABCD")
    if not find(r,perms) then exit end if
end for
printf(1,"%s\n",{r})
-- (relies on brute force(!) - but this is the only method that could be made to cope with >1 omission)


#APPTYPE CONSOLE

DIM numbers AS STRING
DIM imod5 AS INTEGER
DIM imod3 AS INTEGER

FOR DIM i = 1 TO 100
    numbers = ""
    imod3 = i MOD 3
    imod5 = i MOD 5
    IF NOT imod3 THEN numbers = "Fizz"
    IF NOT imod5 THEN numbers = numbers & "Buzz"
    IF imod3 AND imod5 THEN numbers = i
    PRINT numbers, " ";
NEXT

PAUSE


<?php
$finalres = Array();
function permut($arr,$result=array()){
	global  $finalres;
	if(empty($arr)){
		$finalres[] = implode("",$result);
	}else{
		foreach($arr as $key => $val){
			$newArr = $arr;
			$newres = $result;
			$newres[] = $val;
			unset($newArr[$key]);
			permut($newArr,$newres);
		}
	}
}
$givenPerms = Array("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB");
$given = Array("A","B","C","D");
permut($given);
print_r(array_diff($finalres,$givenPerms)); // Array ( [20] => DBAC )


   P1 = ["ABCD","CABD","ACDB","DACB","BCDA","ACBD",
         "ADCB","CDAB","DABC","BCAD","CADB","CDBA",
         "CBAD","ABDC","ADBC","BDCA","DCBA","BACD",
         "BADC","BDAC","CBDA","DBCA","DCAB"],
   Perms = permutations("ABCD"),
   % ...


(setq *PermList
   (mapcar chop
      (quote
         "ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB"
         "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA"
         "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB" ) ) )

(let (Lst (chop "ABCD")  L Lst)
   (recur (L)  # Permute
      (if (cdr L)
         (do (length L)
            (recurse (cdr L))
            (rot L) )
         (unless (member Lst *PermList)  # Check
            (prinl Lst) ) ) ) )


function permutation ($array) {
    function generate($n, $array, $A) {
        if($n -eq 1) {
            $array[$A] -join ''
        }
        else{
            for( $i = 0; $i -lt ($n - 1); $i += 1) {
                generate ($n - 1) $array $A
                if($n % 2 -eq 0){
                    $i1, $i2 = $i, ($n-1)
                    $temp = $A[$i1]
                    $A[$i1] = $A[$i2]
                    $A[$i2] = $temp
                }
                else{
                    $i1, $i2 = 0, ($n-1)
                    $temp = $A[$i1]
                    $A[$i1] = $A[$i2]
                    $A[$i2] = $temp
                }
            }
            generate ($n - 1) $array $A
        }
    }
    $n = $array.Count
    if($n -gt 0) {
        (generate $n $array (0..($n-1)))
    } else {$array}
}
$perm = permutation @('A','B','C', 'D')
$find = @(
"ABCD"
"CABD"
"ACDB"
"DACB"
"BCDA"
"ACBD"
"ADCB"
"CDAB"
"DABC"
"BCAD"
"CADB"
"CDBA"
"CBAD"
"ABDC"
"ADBC"
"BDCA"
"DCBA"
"BACD"
"BADC"
"BDAC"
"CBDA"
"DBCA"
"DCAB"
)
$perm | where{-not $find.Contains($_)}


Procedure in_List(in.s)
  Define.i i, j
  Define.s a
  Restore data_to_test
  For i=1 To 3*8-1
    Read.s a
    If in=a
      ProcedureReturn #True
    EndIf
  Next i
  ProcedureReturn #False
EndProcedure

Define.c z, x, c, v
If OpenConsole()
  For z='A' To 'D'
    For x='A' To 'D'
      If z=x:Continue:EndIf
      For c='A' To 'D'
        If c=x Or c=z:Continue:EndIf
        For v='A' To 'D'
          If v=c Or v=x Or v=z:Continue:EndIf
          Define.s test=Chr(z)+Chr(x)+Chr(c)+Chr(v)
          If Not in_List(test)
            PrintN(test+" is missing.")
          EndIf
        Next
      Next
    Next
  Next
  PrintN("Press Enter to exit"):Input()
EndIf

DataSection
data_to_test:
  Data.s "ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB"
  Data.s "DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA"
  Data.s "DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"
EndDataSection


from itertools import permutations

given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
           CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''.split()

allPerms = [''.join(x) for x in permutations(given[0])]

missing = list(set(allPerms) - set(given)) # ['DBAC']


for i = 1 to 100 do if i|15=0 then !'FizzBuzz ' else if i|5=0 then !'Buzz ' else if i|3=0 then !'Fizz ' else !i;!' ' fi fi fi od


  $ "ABCD CABD ACDB DACB BCDA ACBD
     ADCB CDAB DABC BCAD CADB CDBA
     CBAD ABDC ADBC BDCA DCBA BACD
     BADC BDAC CBDA DBCA DCAB" nest$
  16 base put
  [] swap
  witheach [ $->n drop join ]
  0 swap witheach ^
  number$ echo$
  base release


library(combinat)

permute.me <- c("A", "B", "C", "D")
perms  <- permn(permute.me)  # list of all permutations
perms2 <- matrix(unlist(perms), ncol=length(permute.me), byrow=T)  # matrix of all permutations
perms3 <- apply(perms2, 1, paste, collapse="")  # vector of all permutations

incomplete <- c("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
                "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
                "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB")

setdiff(perms3, incomplete)


#lang racket

(define almost-all
  '([A B C D] [C A B D] [A C D B] [D A C B] [B C D A] [A C B D] [A D C B]
    [C D A B] [D A B C] [B C A D] [C A D B] [C D B A] [C B A D] [A B D C]
    [A D B C] [B D C A] [D C B A] [B A C D] [B A D C] [B D A C] [C B D A]
    [D B C A] [D C A B]))

;; Obvious method:
(for/first ([p (in-permutations (car almost-all))]
            #:unless (member p almost-all))
  p)
;; -> '(D B A C)

;; For permutations of any set
(define charmap
  (for/hash ([x (in-list (car almost-all))] [i (in-naturals)])
    (values x i)))
(define size (hash-count charmap))

;; Illustrating approach mentioned in the task description.
;; For each position, character with odd parity at that position.

(require data/bit-vector)

(for/list ([i (in-range size)])
  (define parities (make-bit-vector size #f))
  (for ([permutation (in-list almost-all)])
    (define n (hash-ref charmap (list-ref permutation i)))
    (bit-vector-set! parities n (not (bit-vector-ref parities n))))
  (for/first ([(c i) charmap] #:when (bit-vector-ref parities i))
    c))
;; -> '(D B A C)


my @givens = <ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
                CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB>;

my @perms = <A B C D>.permutations.map: *.join;

.say when none(@givens) for @perms;


: fizz ( n -- ) drop ." Fizz" ;
: buzz ( n -- ) drop ." Buzz" ;
: fb   ( n -- ) drop ." FizzBuzz" ;
: vector create does> ( n -- )
  over 15 mod cells + @ execute ;
vector .fizzbuzz
  ' fb   , ' . ,    ' . ,
  ' fizz , ' . ,    ' buzz ,
  ' fizz , ' . ,    ' . ,
  ' fizz , ' buzz , ' . ,
  ' fizz , ' . ,    ' . ,


Dim PList as QStringList
PList.addItems "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB"
PList.additems "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA"
PList.additems "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"

Dim NumChar(4, 65 to 68) as integer
Dim MPerm as string

'Create table with occurences
For x = 0 to PList.Itemcount -1
    for y = 1 to 4
        Inc(NumChar(y, asc(PList.Item(x)[y])))
    next
next

'When a char only occurs 5 times it's the missing one
for x = 1 to 4
    for y = 65 to 68
        MPerm = MPerm + iif(NumChar(x, y)=5, chr$(y), "")
    next
next

showmessage MPerm
'= DBAC


/*REXX pgm finds one or more missing permutations from an internal list & displays them.*/
list= 'ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA',
      "DCBA BACD BADC BDAC CBDA DBCA DCAB"       /*list that is missing one permutation.*/
@.=                                              /* [↓]  needs to be as long as  THINGS.*/
@abcU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'             /*an uppercase (Latin/Roman) alphabet. */
things= 4                                        /*number of unique letters to be used. */
bunch = 4                                        /*number letters to be used at a time. */
                 do j=1  for things              /* [↓]  only get a portion of alphabet.*/
                 $.j= substr(@abcU, j, 1)        /*extract just one letter from alphabet*/
                 end   /*j*/                     /* [↑]  build a letter array for speed.*/
call permSet 1                                   /*invoke PERMSET subroutine recursively*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
permSet: procedure expose $. @. bunch list things; parse arg ? /*calls self recursively.*/
         if ?>bunch  then do;  _=
                                   do m=1  for bunch           /*build a permutation.   */
                                   _= _  ||  @.m               /*add permutation──►list.*/
                                   end   /*m*/
                                                               /* [↓]  is in the list?  */
                          if wordpos(_,list)==0  then say _  ' is missing from the list.'
                          end
                     else do x=1  for things                   /*build a permutation.   */
                                   do k=1  for ?-1
                                   if @.k==$.x  then iterate x /*was permutation built? */
                                   end  /*k*/
                          @.?= $.x                             /*define as being built. */
                          call permSet  ?+1                    /*call self recursively. */
                          end   /*x*/
         return


program fizzbuzz_if
   integer :: i

   do i = 1, 100
      if     (mod(i,15) == 0) then; print *, 'FizzBuzz'
      else if (mod(i,3) == 0) then; print *, 'Fizz'
      else if (mod(i,5) == 0) then; print *, 'Buzz'
      else;                         print *, i
      end if
   end do
end program fizzbuzz_if


list = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"

for a = ascii("A") to ascii("D")
    for b = ascii("A") to ascii("D")
        for c = ascii("A") to ascii("D")
            for d = ascii("A") to ascii("D")
                x = char(a) + char(b) + char(c)+ char(d)
                if a!=b and a!=c and a!=d and b!=c and b!=d and c!=d
                   if substr(list,x) = 0 see x + " missing" + nl ok ok
            next
        next
    next
next


given = %w{
  ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
  CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB
}

all = given[0].chars.permutation.collect(&:join)

puts "missing: #{all - given}"


list$ = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"

for a = asc("A") to asc("D")
  for b = asc("A") to asc("D")
    for c = asc("A") to asc("D")
      for d = asc("A") to asc("D")
        x$ = chr$(a) + chr$(b) + chr$(c)+ chr$(d)
        for i = 1 to 4                                            ' make sure each letter is unique
          j = instr(x$,mid$(x$,i,1))
          if instr(x$,mid$(x$,i,1),j + 1) <> 0 then goto [nxt]
        next i
       if instr(list$,x$) = 0 then print x$;" missing"            ' found missing permutation
[nxt] next d
    next c
  next b
next a


const GIVEN_PERMUTATIONS: [&str; 23] = [
    "ABCD",
    "CABD",
    "ACDB",
    "DACB",
    "BCDA",
    "ACBD",
    "ADCB",
    "CDAB",
    "DABC",
    "BCAD",
    "CADB",
    "CDBA",
    "CBAD",
    "ABDC",
    "ADBC",
    "BDCA",
    "DCBA",
    "BACD",
    "BADC",
    "BDAC",
    "CBDA",
    "DBCA",
    "DCAB"
];

fn main() {

    const PERMUTATION_LEN: usize = GIVEN_PERMUTATIONS[0].len();
    let mut bytes_result: [u8; PERMUTATION_LEN] = [0; PERMUTATION_LEN];

    for permutation in &GIVEN_PERMUTATIONS {
        for (i, val) in permutation.bytes().enumerate() {
            bytes_result[i] ^= val;
        }
    }
    println!("{}", std::str::from_utf8(&bytes_result).unwrap());
}


gen n word = cycle (take (n - 1) (repeat "") ++ [word])
pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz")
fizzbuzz = zipWith combine pattern [1..] where
    combine word number = if null word
                             then show number
                             else word
show $ take 100 fizzbuzz


def fat(n: Int) = (2 to n).foldLeft(1)(_*_)
def perm[A](x: Int, a: Seq[A]): Seq[A] = if (x == 0) a else {
  val n = a.size
  val fatN1 = fat(n - 1)
  val fatN = fatN1 * n
  val p = x / fatN1 % fatN
  val (before, Seq(el, after @ _*)) = a splitAt p
  el +: perm(x % fatN1, before ++ after)
}
def findMissingPerm(start: String, perms: Array[String]): String = {
  for {
    i <- 0 until fat(start.size)
    p = perm(i, start).mkString
  } if (!perms.contains(p)) return p
  ""
}
val perms = """ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB""".stripMargin.split("\n")
println(findMissingPerm(perms(0), perms))


$ include "seed7_05.s7i";

const func string: missingPermutation (in array string: perms) is func
  result
    var string: missing is "";
  local
    var integer: pos is 0;
    var set of char: chSet is (set of char).EMPTY_SET;
    var string: permutation is "";
    var char: ch is ' ';
  begin
    if length(perms) <> 0 then
      for key pos range perms[1] do
        chSet := (set of char).EMPTY_SET;
        for permutation range perms do
          ch := permutation[pos];
          if ch in chSet then
            excl(chSet, ch);
          else
            incl(chSet, ch);
          end if;
        end for;
        missing &:= min(chSet);
      end for;
    end if;
  end func;

const proc: main is func
  begin
    writeln(missingPermutation([] ("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",
           "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
           "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB")));
  end func;


func check_perm(arr) {
    var hash = Hash()
    hash.set_keys(arr...)
    arr.each { |s|
        {
            var t = (s.substr(1) + s.substr(0, 1))
            hash.has_key(t) || return t
        } * s.len
    }
}

var perms = %w(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
               CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB)

say check_perm(perms)


"ABCDCABDACDBDACBBCDAACBDADCBCDABDABCBCADCADBCDBACBADABDCADBCBDCADCBABACDBADCBDACCBDADBCADCAB"→Str0
"ABCD"→Str1
length(Str0)→L
[[0,0,0,0][0,0,0,0][0,0,0,0][0,0,0,0]]→[A]

For(I,1,L,4)
For(J,1,4,1)
sub(Str0,I+J-1,1)→Str2
For(K,1,4,1)
sub(Str1,K,1)→Str3
If Str2=Str3
Then
[A](J,K)+1→[A](J,K)
End
End
End
End

Matr►list([A],1,L₁)
min(L₁)→M

" "→Str4

For(I,1,4,1)
For(J,1,4,1)
If [A](I,J)=M
Then
Str4+sub(Str1,J,1)→Str4
End
End
End
sub(Str4,2,4)→Str4
Disp "MISSING"
Disp Str4


package require struct::list

set have { \
    ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC \
    ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB \
}

struct::list foreachperm element {A B C D} {
	set text [join $element ""]
	if {$text ni $have} {
		puts "Missing permutation(s): $text"
	}
}


for i = 1 to 100
{
   flag = false
   if i mod 3 == 0
   {
      flag = true
      print["Fizz"]
   }

   if i mod 5 == 0
   {
      flag = true
      print["Buzz"]
   }

   if flag == false
      print[i]

   println[]
}


permutations = ~&itB^?a\~&aNC *=ahPfatPRD refer ^C/~&a ~&ar&& ~&arh2falrtPXPRD


arrp = Array("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",_
      "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",_
      "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD",_
      "BADC", "BDAC", "CBDA", "DBCA", "DCAB")

Dim col(4)

'supposes that a complete column have 6 of each letter.
target = (6*Asc("A")) + (6*Asc("B")) + (6*Asc("C")) + (6*Asc("D"))

missing = ""

For i = 0 To UBound(arrp)
	For j = 1 To 4
            col(j) = col(j) + Asc(Mid(arrp(i),j,1))
	Next
Next

For k = 1 To 4
	n = target - col(k)
	missing = missing & Chr(n)
Next

WScript.StdOut.WriteLine missing


import "./set" for Set
import "./perm" for Perm

var missingPerms = Fn.new { |input, perms|
    var s1 = Set.new()
    s1.addAll(perms)
    var perms2 = Perm.list(input).map { |p| p.join() }
    var s2 = Set.new()
    s2.addAll(perms2)
    return s2.except(s1).toList
}

var input = ["A", "B", "C", "D"]
var perms = [
    "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
    "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
    "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
]
var missing = missingPerms.call(input, perms)
if (missing.count == 1) {
    System.print("The missing permutation is %(missing[0])")
} else {
    System.print("There are %(missing.count) missing permutations, namely:\n")
    System.print(missing)
}


include "NSLog.incl"

long fizz, buzz, i

for i = 1 to 100
  fizz = (i mod 3 )
  buzz = (i mod 5 )
  if fizz + buzz == 0 then NSLog(@"FizzBuzz") : continue
  if fizz == 0 then NSLog(@"Fizz") : continue
  if buzz == 0 then NSLog(@"Buzz") : continue
  NSLog(@"%ld",i)
next i

HandleEvents


code HexIn=26, HexOut=27;
int  P, I;
[P:= 0;
for I:= 1 to 24-1 do P:= P xor HexIn(1);
HexOut(0, P);
]


var data=L("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB",
           "DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA",
           "DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB");
Utils.Helpers.permute(["A".."D"]).apply("concat").copy().remove(data.xplode());


10 LET l$="ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"
20 LET length=LEN l$
30 FOR a= CODE "A" TO  CODE "D"
40 FOR b= CODE "A" TO  CODE "D"
50 FOR c= CODE "A" TO  CODE "D"
60 FOR d= CODE "A" TO  CODE "D"
70 LET x$=""
80 IF a=b OR a=c OR a=d OR b=c OR b=d OR c=d THEN GO TO 140
90 LET x$=CHR$ a+CHR$ b+CHR$ c+CHR$ d
100 FOR i=1 TO length STEP 5
110 IF x$=l$(i TO i+3) THEN GO TO 140
120 NEXT i
130 PRINT x$;" is missing"
140 NEXT d: NEXT c: NEXT b: NEXT a


Public Sub Main()
Dim siCount As Short
Dim sText As String

For siCount = 1 To 100
  sText = ""
  If siCount Mod 3 = 0 Then sText = "Fizz"
  If siCount Mod 5 = 0 Then sText = "Buzz"
  If siCount Mod 15 = 0 Then sText = "FizzBuzz"
  If sText Then Print sText Else Print siCount
Next

End


FizzBuzz := function()
	local i;
	for i in [1 .. 100] do
		if RemInt(i, 15) = 0 then
			Print("FizzBuzz\n");
		elif RemInt(i, 3) = 0 then
			Print("Fizz\n");
		elif RemInt(i, 5) = 0 then
			Print("Buzz\n");
		else
			Print(i, "\n");
		fi;
	od;
end;


@prefix u "http://www.genyris.org/lang/utilities#"

def fizzbuzz (n)
    map-left ^((3 = 'fizz') (5 = 'buzz'))
        lambda (d)
            cond
                (equal? 0 (% n d!left))
                    d!right
                else
                    ''

for n in (range 1 100)
    define fb (''(.join (fizzbuzz n)))
    u:format "%a\n"
        cond
            (equal? fb '')
                n
            else
                fb


' Fizz Buzz
'
FOR i%=1 TO 100
  IF i% MOD 15=0
    PRINT "FizzBuzz"
  ELSE IF i% MOD 3=0
    PRINT "Fizz"
  ELSE IF i% MOD 5=0
    PRINT "Buzz"
  ELSE
    PRINT i%
  ENDIF
NEXT i%


import gleam/int
import gleam/io
import gleam/iterator

pub fn main() {
  iterator.range(1, 101)
  |> iterator.map(to_fizzbuzz)
  |> iterator.map(io.println)
  |> iterator.run
}

fn to_fizzbuzz(n: Int) -> String {
  case n % 3, n % 5 {
    0, 0 -> "FizzBuzz"
    0, _ -> "Fizz"
    _, 0 -> "Buzz"
    _, _ -> int.to_string(n)
  }
}


package main

import "fmt"

func main() {
    for i := 1; i <= 100; i++ {
        switch {
        case i%15==0:
            fmt.Println("FizzBuzz")
        case i%3==0:
            fmt.Println("Fizz")
        case i%5==0:
            fmt.Println("Buzz")
        default:
            fmt.Println(i)
        }
    }
}


module FizzBuzz

augment java.lang.Integer {
	function getFizzAndOrBuzz = |this| -> match {
		when this % 15 == 0 then "FizzBuzz"
		when this % 3 == 0 then "Fizz"
		when this % 5 == 0 then "Buzz"
		otherwise this
	}
}

function main = |args| {
  foreach i in [1..101] {
	println(i: getFizzAndOrBuzz())
  }
}


for (i in 1..100) {

    if (i % 3 == 0 && i % 5 == 0) {
        print("FizzBuzz")
        continue
    }

    if (i % 3 == 0) {
        print("Fizz")
        continue
    }

    if (i % 5 == 0) {
        print("Buzz")
        continue
    }

    // default
    print(i)

}


fizzbuzz :: Int -> String
fizzbuzz x
  | f 15 = "FizzBuzz"
  | f 3 = "Fizz"
  | f 5 = "Buzz"
  | otherwise = show x
  where
    f = (0 ==) . rem x

main :: IO ()
main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]


for let i 1; i <= 100; i++
  if   i % 3 = 0 && i % 5 = 0; println "FizzBuzz"
  elif i % 3 = 0; println "Fizz"
  elif i % 5 = 0; println "Buzz"
  else println i; endif
endfor


DO i = 1, 100
  IF(     MOD(i, 15) == 0 ) THEN
    WRITE() "FizzBuzz"
  ELSEIF( MOD(i, 5) == 0 ) THEN
    WRITE() "Buzz"
  ELSEIF( MOD(i, 3) == 0 ) THEN
    WRITE() "Fizz"
  ELSE
    WRITE() i
  ENDIF
ENDDO


U8 i;
for (i = 1; i <= 100; i++) {
  if (!(i % 15))
    Print("FizzBuzz");
  else if (!(i % 3))
    Print("Fizz");
  else if (!(i % 5))
    Print("Buzz");
  else
    Print("%d", i);
  Print("\n");
}


import Algorithms as algo;

main( argv_ ) {
	if ( size( argv_ ) < 2 ) {
		throw Exception( "usage: fizzbuzz {NUM}" );
	}
	top = integer( argv_[1] );
	for ( i : algo.range( 1, top + 1 ) ) {
		by3 = ( i % 3 ) == 0;
		by5 = ( i % 5 ) == 0;
		if ( by3 ) {
			print( "fizz" );
		}
		if ( by5 ) {
			print( "buzz" );
		}
		if ( ! ( by3 || by5 ) ) {
			print( i );
		}
		print( "\n" );
	}
	return ( 0 );
}


(for [i (range 1 101)] (print (cond
  [(not (% i 15)) "FizzBuzz"]
  [(not (% i  5)) "Buzz"]
  [(not (% i  3)) "Fizz"]
  [True           i])))


software {
	for each 1 to 100
		if i % 15 = 0
			print("FizzBuzz")
		else if i % 3 = 0
			print("Fizz")
		else if i % 5 = 0
			print("Buzz")
		else
			print(i)
		end
	end
}


# straight-forward modulo tester
procedure main()
    every i := 1 to 100 do
        if i % 15 = 0 then
            write("FizzBuzz")
        else if i % 5 = 0 then
            write("Buzz")
        else if i % 3 = 0 then
            write("Fizz")
        else
            write(i)
end


partial
fizzBuzz : Nat -> String
fizzBuzz n = if (n `modNat` 15) == 0 then "FizzBuzz"
             else if (n `modNat` 3) == 0 then "Fizz"
             else if (n `modNat` 5)  == 0 then "Buzz"
             else show n

main : IO ()
main = sequence_ $ map (putStrLn . fizzBuzz) [1..100]


Home is a room.

When play begins:
	repeat with N running from 1 to 100:
		let printed be false;
		if the remainder after dividing N by 3 is 0:
			say "Fizz";
			now printed is true;
		if the remainder after dividing N by 5 is 0:
			say "Buzz";
			now printed is true;
		if printed is false, say N;
		say ".";
	end the story.


for(a,1,100,
   if(a % 15 == 0) then(
      "FizzBuzz" println
   ) elseif(a % 3 == 0) then(
      "Fizz" println
   ) elseif(a % 5 == 0) then(
      "Buzz" println
   ) else (
      a println
   )
)


(1..100) each(x,
  cond(
    (x % 15) zero?, "FizzBuzz" println,
    (x % 3) zero?, "Fizz" println,
    (x % 5) zero?, "Buzz" println
  )
)


; FizzBuzz in Iptscrae
1 a =
{
   "" b =
   { "fizz" b &= } a 3 % 0 == IF
   { "buzz" b &= } a 5 % 0 == IF
   { a ITOA LOGMSG } { b LOGMSG } b STRLEN 0 == IFELSE
   a ++
}
{ a 100 <= } WHILE


(loop [i :range [1 101]
       :let [fizz (zero? (% i 3))
             buzz (zero? (% i 5))]]
  (print (cond
           (and fizz buzz) "fizzbuzz"
           fizz "fizz"
           buzz "buzz"
           i)))


public class FizzBuzz {
    public static void main(String[] args) {
        for (int number = 1; number <= 100; number++) {
            if (number % 15 == 0) {
                System.out.println("FizzBuzz");
            } else if (number % 3 == 0) {
                System.out.println("Fizz");
            } else if (number % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(number);
            }
        }
    }
}


var fizzBuzz = function () {
  var i, output;
  for (i = 1; i < 101; i += 1) {
    output = '';
    if (!(i % 3)) { output += 'Fizz'; }
    if (!(i % 5)) { output += 'Buzz'; }
    console.log(output || i);//empty string is false, so we short-circuit
  }
};


DEFINE one == [[[dup 15 rem 0 =] "FizzBuzz"] [[dup 3 rem 0 =] "Fizz"] [[dup 5 rem 0 =] "Buzz"] [dup]] cond.
1 [100 <=] [dup one put succ] while.


range(1;101)
  | if   . % 15 == 0 then "FizzBuzz"
    elif . % 5  == 0 then "Buzz"
    elif . % 3  == 0 then "Fizz"
    else .
    end


for i in 1:100
    if i % 15 == 0
        println("FizzBuzz")
    elseif i % 3 == 0
        println("Fizz")
    elseif i % 5 == 0
        println("Buzz")
    else
        println(i)
    end
end


# FizzBuzz
log_stderror=yes
loadmodule "pv"
loadmodule "xlog"

route {
    $var(i) = 1;
    while ($var(i) <= 1000) {
        if ($var(i) mod 15 == 0) {
            xlog("FizzBuzz\n");
        } else if ($var(i) mod 5 == 0) {
            xlog("Buzz\n");
        } else if ($var(i) mod 3 == 0) {
            xlog("Fizz\n");
        } else {
            xlog("$var(i)\n");
        }
        $var(i) = $var(i) + 1;
    }
}


// fizzbuzz in Kaya
program fizzbuzz;

Void fizzbuzz(Int size) {
    for i in [1..size] {
        if (i % 15 == 0) {
            putStrLn("FizzBuzz");
        } else if (i % 5 == 0) {
            putStrLn("Buzz");
        } else if (i % 3 == 0) {
            putStrLn("Fizz");
        } else {
            putStrLn( string(i) );
        }
    }
}

Void main() {
    fizzbuzz(100);
}


:- module main.

main :-
    nats(100, Nats),
    fizzbuzz(Nats, Output),
    display(Output).

nats(Max, Out) :-
    nats(Max, 1, Out).
nats(Max, Count, Out) :- Count =< Max |
    Out = [Count|NewOut],
    NewCount := Count + 1,
    nats(Max, NewCount, NewOut).
nats(Max, Count, Out) :- Count > Max |
    Out = [].

fizzbuzz([N|Rest], Out) :- N mod 3 =:= 0, N mod 5 =:= 0 |
    Out = ['FizzBuzz' | NewOut],
    fizzbuzz(Rest, NewOut).
fizzbuzz([], Out) :-
    Out = [].
alternatively.
fizzbuzz([N|Rest], Out) :- N mod 3 =:= 0 |
    Out = ['Fizz' | NewOut],
    fizzbuzz(Rest, NewOut).
fizzbuzz([N|Rest], Out) :- N mod 5 =:= 0 |
    Out = ['Buzz' | NewOut],
    fizzbuzz(Rest, NewOut).
alternatively.
fizzbuzz([N|Rest], Out) :-
    Out = [N | NewOut],
    fizzbuzz(Rest, NewOut).

display([Message|Rest]) :-
    io:outstream([print(Message), nl]),
    display(Rest).
display([]).


fun fizzBuzz() {
    for (number in 1..100) {
        println(
            when {
                number % 15 == 0 -> "FizzBuzz"
                number % 3 == 0 -> "Fizz"
                number % 5 == 0 -> "Buzz"
                else -> number
            }
        )
    }
}


range i from 1 to 100 step 1
| project Result =
    case(
        i % 15 == 0, "FizzBuzz",
        i % 3 == 0, "Fizz",
        i % 5 == 0, "Buzz",
        tostring(i)
    )


`plain
[1 100] `for pos : n ~
	out = []
	n `mod 3 == 0 ? out.# = 'Fizz' ;
	n `mod 5 == 0 ? out.# = 'Buzz' ;
	(out `or n) #write_ln #
;


1. direct:

{S.map
 {lambda {:i}
  {if {= {% :i 15} 0}
   then fizzbuzz
   else {if {= {% :i 3} 0}
   then fizz
   else {if {= {% :i 5} 0}
   then buzz
   else :i}}}}
 {S.serie 1 100}}
-> 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizzbuzz 31 32 fizz 34 buzz fizz 37 38 fizz buzz 41 fizz 43 44 fizzbuzz 46 47 fizz 49 buzz fizz 52 53 fizz buzz 56 fizz 58 59 fizzbuzz 61 62 fizz 64 buzz fizz 67 68 fizz buzz 71 fizz 73 74 fizzbuzz 76 77 fizz 79 buzz fizz 82 83 fizz buzz 86 fizz 88 89 fizzbuzz 91 92 fizz 94 buzz fizz 97 98 fizz buzz

2. via a function

{def fizzbuzz
 {lambda {:i :n}
  {if {> :i :n}
   then .
   else {if {= {% :i 15} 0}
   then fizzbuzz
   else {if {= {% :i 3} 0}
   then fizz
   else {if {= {% :i 5} 0}
   then buzz
   else :i}}} {fizzbuzz {+ :i 1} :n}
}}}
-> fizzbuzz

{fizzbuzz 1 100}
-> same as above.


for .i of 100 {
    writeln given(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i)
}


with i in generateSeries(1, 100)
select ((#i % 3 == 0 ? 'Fizz' | '') + (#i % 5 == 0 ? 'Buzz' | '') || #i)


\documentclass{minimal}
\usepackage{ifthen}
\usepackage{intcalc}
\newcounter{mycount}
\newboolean{fizzOrBuzz}
\newcommand\fizzBuzz[1]{%
\setcounter{mycount}{1}\whiledo{\value{mycount}<#1}
    {
    \setboolean{fizzOrBuzz}{false}
    \ifthenelse{\equal{\intcalcMod{\themycount}{3}}{0}}{\setboolean{fizzOrBuzz}{true}Fizz}{}
    \ifthenelse{\equal{\intcalcMod{\themycount}{5}}{0}}{\setboolean{fizzOrBuzz}{true}Buzz}{}
    \ifthenelse{\boolean{fizzOrBuzz}}{}{\themycount}
    \stepcounter{mycount}
    \\
    }
}
\begin{document}
\fizzBuzz{101}
\end{document}


# fizzbuzz in LIL
for {set i 1} {$i <= 100} {inc i} {
    set show ""
    if {[expr $i % 3 == 0]} {set show "Fizz"}
    if {[expr $i % 5 == 0]} {set show $show"Buzz"}
    if {[expr [length $show] == 0]} {set show $i}
    print $show
}


repeat with i = 1 to 100
    switch
        case i mod 15 = 0
            put "FizzBuzz" & cr after fizzbuzz
            break
        case i mod 5 = 0
            put "Buzz" & cr after fizzbuzz
            break
        case i mod 3 = 0
            put "Fizz" & cr after fizzbuzz
            break
        default
            put i & cr after fizzbuzz
    end switch
end repeat
put fizzbuzz


; ModuleID = 'fizzbuzz.c'
; source_filename = "fizzbuzz.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
; target triple = "x86_64-pc-windows-msvc19.21.27702"

; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.

; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps

$"\[email protected][email protected][email protected]" = comdat any
$"\[email protected][email protected][email protected]" = comdat any
$"\[email protected][email protected][email protected]" = comdat any
$"\[email protected][email protected][email protected]" = comdat any

;--- String constant defintions
@"\[email protected][email protected][email protected]" = linkonce_odr unnamed_addr constant [10 x i8] c"FizzBuzz\0A\00", comdat, align 1
@"\[email protected][email protected][email protected]" = linkonce_odr unnamed_addr constant [6 x i8] c"Fizz\0A\00", comdat, align 1
@"\[email protected][email protected][email protected]" = linkonce_odr unnamed_addr constant [6 x i8] c"Buzz\0A\00", comdat, align 1
@"\[email protected][email protected][email protected]" = linkonce_odr unnamed_addr constant [4 x i8] c"%d\0A\00", comdat, align 1

;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)

; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
  %1 = alloca i32, align 4
  store i32 1, i32* %1, align 4
;--- It does not seem like this branch can be removed
  br label %loop

;--- while (i <= 100)
loop:
  %2 = load i32, i32* %1, align 4
  %3 = icmp sle i32 %2, 100
  br i1 %3, label %divisible_15, label %finished

;--- if (i % 15 == 0)
divisible_15:
  %4 = load i32, i32* %1, align 4
  %5 = srem i32 %4, 15
  %6 = icmp eq i32 %5, 0
  br i1 %6, label %print_fizzbuzz, label %divisible_3

;--- Print 'FizzBuzz'
print_fizzbuzz:
  %7 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\[email protected][email protected][email protected]", i32 0, i32 0))
  br label %next

;--- if (i % 3 == 0)
divisible_3:
  %8 = load i32, i32* %1, align 4
  %9 = srem i32 %8, 3
  %10 = icmp eq i32 %9, 0
  br i1 %10, label %print_fizz, label %divisible_5

;--- Print 'Fizz'
print_fizz:
  %11 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\[email protected][email protected][email protected]", i32 0, i32 0))
  br label %next

;--- if (i % 5 == 0)
divisible_5:
  %12 = load i32, i32* %1, align 4
  %13 = srem i32 %12, 5
  %14 = icmp eq i32 %13, 0
  br i1 %14, label %print_buzz, label %print_number

;--- Print 'Buzz'
print_buzz:
  %15 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\[email protected][email protected][email protected]", i32 0, i32 0))
  br label %next

;--- Print the number
print_number:
  %16 = load i32, i32* %1, align 4
  %17 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\[email protected][email protected][email protected]", i32 0, i32 0), i32 %16)
;--- It does not seem like this branch can be removed
  br label %next

;--- i = i + 1
next:
  %18 = load i32, i32* %1, align 4
  %19 = add nsw i32 %18, 1
  store i32 %19, i32* %1, align 4
  br label %loop

;--- exit main
finished:
  ret i32 0
}

attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.module.flags = !{!0, !1}
!llvm.ident = !{!2}

!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}


include "std.lobster"

forbias(100, 1) i:
    fb := (i % 3 == 0 and "fizz" or "") +
          (i % 5 == 0 and "buzz" or "")
    print fb.length and fb or "" + i


to fizzbuzz :n
  output cond [ [[equal? 0 modulo :n 15] "FizzBuzz]
                [[equal? 0 modulo :n  5] "Buzz]
                [[equal? 0 modulo :n  3] "Fizz]
                [else :n] ]
end

repeat 100 [print fizzbuzz #]


1* FIZZBUZZ en L.S.E.
10 CHAINE FB
20 FAIRE 45 POUR I_1 JUSQUA 100
30 FB_SI &MOD(I,3)=0 ALORS SI &MOD(I,5)=0 ALORS 'FIZZBUZZ' SINON 'FIZZ' SINON SI &MOD(I,5)=0 ALORS 'BUZZ' SINON ''
40 AFFICHER[U,/] SI FB='' ALORS I SINON FB
45*FIN BOUCLE
50 TERMINER
100 PROCEDURE &MOD(A,B) LOCAL A,B
110 RESULTAT A-B*ENT(A/B)


for i = 1, 100 do
	if i % 15 == 0 then
		print("FizzBuzz")
	elseif i % 3 == 0 then
		print("Fizz")
	elseif i % 5 == 0 then
		print("Buzz")
	else
		print(i)
	end
end


for i in range(1,101) do (
   if i%15 == 0 then print("FizzBuzz")
   else if i%3 == 0 then print("Fizz")
   else if i%5 == 0 then print("Buzz")
   else print(i)
)


\\ one line, hard to read
For i=1 to 100 {If i mod 3=0 Then {if i mod 5=0 Then Print "FizzBuzz",  Else Print "Fizz",} Else {if i mod 5=0 Then Print "Buzz", else print i, } } : Print

\\ Better code
For i=1 to 100 {
      Push str$(i,0)+". "+if$(i mod 3=0->"Fizz","")+if$(i mod 5=0->"Buzz","")
      If stackitem$()="" then Drop : Continue
      Print Letter$
}

\\ Far Better Code
For i=1 to 100 {
      Printme(if$(i mod 3=0->"Fizz","")+if$(i mod 5=0->"Buzz",""))
}
Print
Sub Printme(a$)
      If a$<>"" Then Print a$, else Print i,
End Sub


MOD3 = 0
MOD5 = 0
ALL != jot 100

all: say-100

.for NUMBER in $(ALL)

MOD3 != expr \( $(MOD3) + 1 \) % 3; true
MOD5 != expr \( $(MOD5) + 1 \) % 5; true

. if "$(NUMBER)" > 1
PRED != expr $(NUMBER) - 1
say-$(NUMBER): say-$(PRED)
. else
say-$(NUMBER):
. endif
. if "$(MOD3)$(MOD5)" == "00"
	@echo FizzBuzz
. elif "$(MOD3)" == "0"
	@echo Fizz
. elif "$(MOD5)" == "0"
	@echo Buzz
. else
	@echo $(NUMBER)
. endif

.endfor


function fizzBuzz()
    for i = (1:100)
        if mod(i,15) == 0
           fprintf('FizzBuzz ')
        elseif mod(i,3) == 0
           fprintf('Fizz ')
        elseif mod(i,5) == 0
           fprintf('Buzz ')
        else
           fprintf('%i ',i))
        end
    end
    fprintf('\n');
end


for n:1 thru 100 do
   if mod(n, 15) = 0 then (sprint("FizzBuzz"), newline())
   elseif mod(n, 3) = 0 then (sprint("Fizz"), newline())
   elseif mod(n,5) = 0 then (sprint("Buzz"), newline())
   else (sprint(n), newline());


for i in 1 to 100 do
(
    case of
    (
        (mod i 15 == 0): (print "FizzBuzz")
        (mod i 5 == 0):  (print "Buzz")
        (mod i 3 == 0):  (print "Fizz")
        default:         (print i)
    )
)


for($i=1; $i<=100; $i++)
{
    if($i % 15 == 0)
        print "FizzBuzz\n";
    else if ($i % 3 == 0)
        print "Fizz\n";
    else if ($i % 5 == 0)
        print "Buzz\n";
    else
        print ($i + "\n");
}


:- module fizzbuzz.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, string, bool.

:- func fizz(int) = bool.
fizz(N) = ( if N mod 3 = 0 then yes else no ).

:- func buzz(int) = bool.
buzz(N) = ( if N mod 5 = 0 then yes else no ).

%                N    3?    5?
:- func fizzbuzz(int, bool, bool) = string.
fizzbuzz(_, yes, yes) = "FizzBuzz".
fizzbuzz(_, yes, no)  = "Fizz".
fizzbuzz(_, no,  yes) = "Buzz".
fizzbuzz(N, no,  no)  = from_int(N).

main(!IO) :- main(1, 100, !IO).

:- pred main(int::in, int::in, io::di, io::uo) is det.
main(N, To, !IO) :-
    io.write_string(fizzbuzz(N, fizz(N), buzz(N)), !IO),
    io.nl(!IO),
    ( if N < To then
        main(N + 1, To, !IO)
    else
        true
    ).


for i := 1 upto 100:
message if i mod 15 = 0: "FizzBuzz" &
elseif i mod 3 = 0: "Fizz" &
elseif i mod 5 = 0: "Buzz" &
else: decimal i & fi "";
endfor
end


For n = 1 To 100
  op = ""
  If Math.Remainder(n, 3) = 0 Then
    op = "Fizz"
  EndIf
  IF Math.Remainder(n, 5) = 0 Then
    op = text.Append(op, "Buzz")
  EndIf
  If op = "" Then
    TextWindow.WriteLine(n)
  Else
    TextWindow.WriteLine(op)
  EndIf
EndFor


0 (
  succ false :hit
  (3 mod 0 ==) ("Fizz" print! true @hit) when
  (5 mod 0 ==) ("Buzz" print! true @hit) when
  (hit) (print) unless newline
) 100 times


for i in range(1,100)
    if i % 15 == 0 then
        print "FizzBuzz"
    else if i % 3 == 0 then
        print "Fizz"
    else if i % 5 == 0 then
        print "Buzz"
    else
        print i
    end if
end for


#################################
# Fizz Buzz                     #
# MIPS Assembly targetings MARS #
# By Keith Stellyes             #
# August 24, 2016               #
#################################

# $a0 left alone for printing
# $a1 stores our counter
# $a2 is 1 if not evenly divisible

.data
	fizz: .asciiz "Fizz\n"
	buzz: .asciiz "Buzz\n"
	fizzbuzz: .asciiz "FizzBuzz\n"
	newline: .asciiz "\n"

.text
loop:
	beq $a1,100,exit
	add $a1,$a1,1

	#test for counter mod 15 ("FIZZBUZZ")
	div $a2,$a1,15
	mfhi $a2
	bnez $a2,loop_not_fb #jump past the fizzbuzz print logic if NOT MOD 15

#### PRINT FIZZBUZZ: ####
	li $v0,4 #set syscall arg to PRINT_STRING
	la $a0,fizzbuzz #set the PRINT_STRING arg to fizzbuzz
	syscall #call PRINT_STRING
	j loop #return to start
#### END PRINT FIZZBUZZ ####

loop_not_fb:
	div $a2,$a1,3 #divide $a1 (our counter) by 3 and store remainder in HI
	mfhi $a2 #retrieve remainder (result of MOD)
	bnez $a2, loop_not_f #jump past the fizz print logic if NOT MOD 3

#### PRINT FIZZ ####
	li $v0,4
	la $a0,fizz
	syscall
	j loop
#### END PRINT FIZZ ####

loop_not_f:
	div $a2,$a1,5
	mfhi $a2
	bnez $a2,loop_not_b

#### PRINT BUZZ ####
	li $v0,4
	la $a0,buzz
	syscall
	j loop
#### END PRINT BUZZ ####

loop_not_b:
	#### PRINT THE INTEGER ####
	li $v0,1 #set syscall arg to PRINT_INTEGER
	move $a0,$a1 #set PRINT_INTEGER arg to contents of $a1
	syscall #call PRINT_INTEGER

	### PRINT THE NEWLINE CHAR ###
	li $v0,4 #set syscall arg to PRINT_STRING
	la $a0,newline
	syscall

	j loop #return to beginning

exit:
	li $v0,10
	syscall


1.upto(100) do |n|
    print "Fizz" if a = ((n % 3) == 0)
    print "Buzz" if b = ((n % 5) == 0)
    print n unless (a || b)
    print "\n"
end


local
  fun fbstr i =
      case (i mod 3 = 0, i mod 5 = 0) of
          (true , true ) => "FizzBuzz"
        | (true , false) => "Fizz"
        | (false, true ) => "Buzz"
        | (false, false) => Int.toString i

  fun fizzbuzz' (n, j) =
      if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1))
in
  fun fizzbuzz n = fizzbuzz' (n, 1)
  val _ = fizzbuzz 100
end


t   IS $255
Ja  IS $127

       LOC Data_Segment
data   GREG   @

fizz   IS @-Data_Segment
       BYTE "Fizz",0,0,0,0

buzz   IS @-Data_Segment
       BYTE "Buzz",0,0,0,0

nl     IS @-Data_Segment
       BYTE #a,0,0,0,0,0,0,0

buffer IS @-Data_Segment

       LOC #1000
       GREG @

% "usual" print integer subroutine
printnum LOC @
       OR   $1,$0,0
       SETL $2,buffer+64
       ADDU $2,$2,data
       XOR  $3,$3,$3
       STBU $3,$2,1
loop   DIV  $1,$1,10
       GET  $3,rR
       ADDU $3,$3,'0'
       STBU $3,$2,0
       SUBU $2,$2,1
       PBNZ $1,loop
       ADDU t,$2,1
       TRAP 0,Fputs,StdOut
       GO   Ja,Ja,0

Main   SETL $0,1           % i = 1
1H     SETL $2,0           % fizz not taken
       CMP  $1,$0,100      % i <= 100
       BP   $1,4F          % if no, go to end
       DIV  $1,$0,3
       GET  $1,rR          % $1 = mod(i,3)
       CSZ  $2,$1,1        % $2 = Fizz taken?
       BNZ  $1,2F          % $1 != 0? yes, then skip
       ADDU t,data,fizz
       TRAP 0,Fputs,StdOut % print "Fizz"
2H     DIV  $1,$0,5
       GET  $1,rR          % $1 = mod(i,5)
       BNZ  $1,3F          % $1 != 0? yes, then skip
       ADDU t,data,buzz
       TRAP 0,Fputs,StdOut % print "Buzz"
       JMP  5F             % skip print i
3H     BP   $2,5F          % skip if Fizz was taken
       GO   Ja,printnum    % print i
5H     ADDU t,data,nl
       TRAP 0,Fputs,StdOut % print newline
       ADDU $0,$0,1
       JMP  1B             % repeat for next i
4H     XOR  t,t,t
       TRAP 0,Halt,0       % exit(0)


MODULE Fizzbuzz;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

TYPE CB = PROCEDURE(INTEGER);

PROCEDURE Fizz(n : INTEGER);
BEGIN
    IF n MOD 3 = 0 THEN
        WriteString("Fizz");
        Buzz(n,Newline)
    ELSE
        Buzz(n,WriteInt)
    END
END Fizz;

PROCEDURE Buzz(n : INTEGER; f : CB);
BEGIN
    IF n MOD 5 = 0 THEN
        WriteString("Buzz");
        WriteLn
    ELSE
        f(n)
    END
END Buzz;

PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..9] OF CHAR;
BEGIN
    FormatString("%i\n", buf, n);
    WriteString(buf)
END WriteInt;

PROCEDURE Newline(n : INTEGER);
BEGIN
    WriteLn
END Newline;

VAR i : INTEGER;
BEGIN
    FOR i:=1 TO 30 DO
        Fizz(i)
    END;

    ReadChar
END Fizzbuzz.


MODULE Fizzbuzz EXPORTS Main;

IMPORT IO;

BEGIN
   FOR i := 1 TO 100 DO
      IF i MOD 15 = 0 THEN
         IO.Put("FizzBuzz\n");
      ELSIF i MOD 5 = 0 THEN
         IO.Put("Buzz\n");
      ELSIF i MOD 3 = 0 THEN
         IO.Put("Fizz\n");
      ELSE
         IO.PutInt(i);
         IO.Put("\n");
      END;
   END;
END Fizzbuzz.


V digits = ‘0123456789abcdefghijklmnopqrstuvwxyz’

F baseN(=num, b)
   I num == 0
      R ‘0’
   V result = ‘’
   L num != 0
      (num, V d) = divmod(num, b)
      result ‘’= :digits[Int(d)]
   R reversed(result)

F pal2(num)
   I num == 0 | num == 1
      R 1B
   V based = bin(num)
   R based == reversed(based)

F pal_23(limit)
   V r = [Int64(0), 1]
   V n = 1
   L
      n++
      V b = baseN(n, 3)
      V revb = reversed(b)

      L(trial) (b‘’revb, b‘0’revb, b‘1’revb, b‘2’revb)
         V t = Int64(trial, radix' 3)
         I pal2(t)
            r.append(t)
            I r.len == limit
               R r

L(pal23) pal_23(6)
   print(pal23‘ ’baseN(pal23, 3)‘ ’baseN(pal23, 2))


def fizzBuzz(top):
    var t := 1
    while (t < top):
        if ((t % 3 == 0) || (t % 5 == 0)):
            if (t % 15 == 0):
                traceln(`$t  FizzBuzz`)
            else if (t % 3 == 0):
                traceln(`$t  Fizz`)
            else:
                traceln(`$t  Buzz`)
        t += 1

fizzBuzz(100)


with Ada.Text_IO, Base_Conversion;

procedure Brute is

   type Long is range 0 .. 2**63-1;
   package BC is new Base_Conversion(Long);

   function Palindrome (S : String) return Boolean is
      (if S'Length < 2 then True
      elsif S(S'First) /= S(S'Last) then False
      else Palindrome(S(S'First+1 .. S'Last-1)));

   function Palindrome(N: Long; Base: Natural) return Boolean is
      (Palindrome(BC.Image(N, Base =>Base)));

  package IIO is new Ada.Text_IO.Integer_IO(Long);

begin
   for I in Long(1) .. 10**8 loop
      if Palindrome(I, 3) and then Palindrome(I, 2) then
	 IIO.Put(I, Width => 12); -- prints I (Base 10)
	 Ada.Text_IO.Put_Line(": " & BC.Image(I, Base => 2) & "(2)" &
			      ", " & BC.Image(I, Base => 3) & "(3)");
	 -- prints I (Base 2 and Base 3)
      end if;
      end loop;
end Brute;


on intToText(int, base) -- Simple version for brevity.
    script o
        property digits : {int mod base as integer}
    end script

    set int to int div base
    repeat until (int = 0)
        set beginning of o's digits to int mod base as integer
        set int to int div base
    end repeat

    return join(o's digits, "")
end intToText

on join(lst, delim)
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to delim
    set txt to lst as text
    set AppleScript's text item delimiters to astid
    return txt
end join

on task()
    set output to {"0  0  0", "1  1  1"} -- Results for 0 and 1 taken as read.

    set b3Hi to 0 -- Integer value of a palindromic ternary number, minus its low end.
    set msdCol to 1 -- Column number (0-based) of its leftmost ternary digit.
    set lsdCol to 1 -- Column number of the high end's rightmost ternary digit.
    set lsdUnit to 3 ^ lsdCol as integer -- Value of 1 in this column.
    set lrdCol to 1 -- Column number of the rightmost hi end digit to mirror in the low end.
    set lrdUnit to 3 ^ lrdCol as integer -- Value of 1 in this column.
    set columnTrigger to 3 ^ (msdCol + 1) as integer -- Next value that will need an additional column.
    repeat until ((count output) = 6)
        -- Notionally increment the high end's rightmost column.
        set b3Hi to b3Hi + lsdUnit
        -- If this carries through to start an additional column, adjust the presets.
        if (b3Hi = columnTrigger) then
            set lrdCol to lrdCol + msdCol mod 2
            set lrdUnit to 3 ^ lrdCol as integer
            set msdCol to msdCol + 1
            set lsdCol to (msdCol + 1) div 2
            set lsdUnit to 3 ^ lsdCol as integer
            set columnTrigger to columnTrigger * 3
        end if
        -- Work out a mirroring low end value and add it in.
        set b3Lo to b3Hi div lrdUnit mod 3
        repeat with p from (lrdCol + 1) to msdCol
            set b3Lo to b3Lo * 3 + b3Hi div (3 ^ p) mod 3
        end repeat
        set n to b3Hi + b3Lo

        -- See if the result's palindromic in base 2 too. It must be an odd number and the value of the
        -- reverse of its low end (including any overlap) must match that of its truncated high end.
        set oL2b to n mod 2
        if (oL2b = 1) then
            set b2Hi to n
            repeat while (b2Hi > oL2b)
                set b2Hi to b2Hi div 2
                if (b2Hi > oL2b) then set oL2b to oL2b * 2 + b2Hi mod 2
            end repeat
            -- If it is, append its decimal, binary, and ternary representations to the output.
            if (b2Hi = oL2b) then ¬
                set end of output to join({intToText(n, 10), intToText(n, 2), intToText(n, 3)}, "  ")
        end if
    end repeat
    set beginning of output to "decimal  binary  ternary:"

    return join(output, linefeed)
end task

task()


&DEFINE LOOP 100&
1 VAR i .

FOR LOOP
    || VAR ln .
    i 5 % 0 ==
    IF : .
        ln |Buzz| + VAR ln .
    ENDIF
    i 3 % 0 ==
    IF : .
        ln |Fizz| + VAR ln .
    ENDIF
    ln || ==
    IF : .
        i PRINT .
    ENDIF
    ln || !=
    IF : .
        ln PRINT .
    ENDIF
i 1 + VAR i .
ENDFOR


pal2?: function [n][
    digs2: digits.base:2 n
    return digs2 = reverse digs2
]

revNumber: function [z][
    u: z
    result: 0
    while [u > 0][
        result: result + (2*result) + u%3
        u: u/3
    ]
    return result
]

pal23: function [][
    p3: 1
    cnt: 1
    print [
        pad (to :string 0)++" :" 14
        pad.right join to [:string] digits.base:2 0 37 "->"
        join to [:string] digits.base:3 0
    ]
    loop 0..31 'p [
        while [(p3*(1+3*p3)) < shl 1 2*p]-> p3: p3*3

        bound: (shl 1 2*p)/3*p3
        limDown: max @[p3/3, bound]
        limUp: min @[2*bound, p3-1]
        if limUp >= limDown [
            loop limDown..limUp 'k [
                n: (revNumber k) + (1+3*k)*p3
                if pal2? n [
                    print [
                        pad (to :string n)++" :" 14
                        pad.right join to [:string] digits.base:2 n 37 "->"
                        join to [:string] digits.base:3 n
                    ]
                    cnt: cnt + 1
                    if cnt=6 -> return null
                ]
            ]
        ]
    ]
]

pal23


for i = 1,100
    print ((a) -> a == "" and i or a) table.concat {
        i % 3 == 0 and "Fizz" or ""
        i % 5 == 0 and "Buzz" or ""}


#include <stdio.h>
typedef unsigned long long xint;

int is_palin2(xint n)
{
	xint x = 0;
	if (!(n&1)) return !n;
	while (x < n) x = x<<1 | (n&1), n >>= 1;
	return n == x || n == x>>1;
}

xint reverse3(xint n)
{
	xint x = 0;
	while (n) x = x*3 + (n%3), n /= 3;
	return x;
}

void print(xint n, xint base)
{
	putchar(' ');
	// printing digits backwards, but hey, it's a palindrome
	do { putchar('0' + (n%base)), n /= base; } while(n);
	printf("(%lld)", base);
}

void show(xint n)
{
	printf("%llu", n);
	print(n, 2);
	print(n, 3);
	putchar('\n');
}

xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }

int main(void)
{
	xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
	int cnt;

	show(0);
	cnt = 1;

	lo = 0;
	hi = pow2 = pow3 = 1;

	while (1) {
		for (i = lo; i < hi; i++) {
			n = (i * 3 + 1) * pow3 + reverse3(i);
			if (!is_palin2(n)) continue;
			show(n);
			if (++cnt >= 7) return 0;
		}

		if (i == pow3)
			pow3 *= 3;
		else
			pow2 *= 4;

		while (1) {
			while (pow2 <= pow3) pow2 *= 4;

			lo2 = (pow2 / pow3 - 1) / 3;
			hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
			lo3 = pow3 / 3;
			hi3 = pow3;

			if (lo2 >= hi3)
				pow3 *= 3;
			else if (lo3 >= hi2)
				pow2 *= 4;
			else {
				lo = max(lo2, lo3);
				hi = min(hi2, hi3);
				break;
			}
		}
	}
	return 0;
}


FIZZBUZZ
 NEW I
 FOR I=1:1:100 WRITE !,$SELECT(('(I#3)&'(I#5)):"FizzBuzz",'(I#5):"Buzz",'(I#3):"Fizz",1:I)
 KILL I
 QUIT


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

public class FindPalindromicNumbers
{
    static void Main(string[] args)
    {
        var query =
            PalindromicTernaries()
            .Where(IsPalindromicBinary)
            .Take(6);
        foreach (var x in query) {
            Console.WriteLine("Decimal: " + x);
            Console.WriteLine("Ternary: " + ToTernary(x));
            Console.WriteLine("Binary: " + Convert.ToString(x, 2));
            Console.WriteLine();
        }
    }

    public static IEnumerable<long> PalindromicTernaries() {
        yield return 0;
        yield return 1;
        yield return 13;
        yield return 23;

        var f = new List<long> {0};
        long fMiddle = 9;
        while (true) {
            for (long edge = 1; edge < 3; edge++) {
                int i;
                do {
                    //construct the result
                    long result = fMiddle;
                    long fLeft = fMiddle * 3;
                    long fRight = fMiddle / 3;
                    for (int j = f.Count - 1; j >= 0; j--) {
                        result += (fLeft + fRight) * f[j];
                        fLeft *= 3;
                        fRight /= 3;
                    }
                    result += (fLeft + fRight) * edge;
                    yield return result;

                    //next permutation
                    for (i = f.Count - 1; i >= 0; i--) {
                        if (f[i] == 2) {
                            f[i] = 0;
                        } else {
                            f[i]++;
                            break;
                        }
                    }
                } while (i >= 0);
            }
            f.Add(0);
            fMiddle *= 3;
        }
    }

    public static bool IsPalindromicBinary(long number) {
        long n = number;
        long reverse = 0;
        while (n != 0) {
            reverse <<= 1;
            if ((n & 1) == 1) reverse++;
            n >>= 1;
        }
        return reverse == number;
    }

    public static string ToTernary(long n)
    {
        if (n == 0) return "0";
        string result = "";
        while (n > 0) {        {
            result = (n % 3) + result;
            n /= 3;
        }
        return result;
    }

}


for i in range(1, 100)
	if ((i % 3) = 0) and ((i % 5) = 0)
		println "FizzBuzz"
	else if i % 3 = 0
		println "Fizz"
	else if i % 5 = 0
		println "Buzz"
	else
		println i
	end
end


(defun palindromep (str)
  (string-equal str (reverse str)) )

(loop
  for i from 0
  with results = 0
  until (>= results 6)
  do
    (when (and (palindromep (format nil "~B" i))
               (palindromep (format nil "~3R" i)) )
      (format t "n:~a~:*  [2]:~B~:*  [3]:~3R~%" i)
      (incf results) ))


import core.stdc.stdio, std.ascii;

bool isPalindrome2(ulong n) pure nothrow @nogc @safe {
    ulong x = 0;
    if (!(n & 1))
        return !n;
    while (x < n) {
        x = (x << 1) | (n & 1);
        n >>= 1;
    }
    return n == x || n == (x >> 1);
}

ulong reverse3(ulong n) pure nothrow @nogc @safe {
    ulong x = 0;
    while (n) {
        x = x * 3 + (n % 3);
        n /= 3;
    }
    return x;
}

void printReversed(ubyte base)(ulong n) nothrow @nogc {
    ' '.putchar;
    do {
        digits[n % base].putchar;
        n /= base;
    } while(n);

    printf("(%d)", base);
}

void main() nothrow @nogc {
    ulong top = 1, mul = 1, even = 0;
    uint count = 0;

    for (ulong i = 0; true; i++) {
        if (i == top) {
            if (even ^= 1)
                top *= 3;
            else {
                i = mul;
                mul = top;
            }
        }

        immutable n = i * mul + reverse3(even ? i / 3 : i);

        if (isPalindrome2(n)) {
            printf("%llu", n);
            printReversed!3(n);
            printReversed!2(n);
            '\n'.putchar;

            if (++count >= 6) // Print first 6.
                break;
        }
    }
}


DEFINE DATA
LOCAL
1 #I       (I4)
1 #MODULO  (I4)
1 #DIVISOR (I4)
1 #OUT     (A10)
END-DEFINE
*
FOR #I := 1 TO 100
  #DIVISOR := 15
  #OUT := 'FizzBuzz'
  PERFORM MODULO
*
  #DIVISOR := 5
  #OUT := 'Buzz'
  PERFORM MODULO
*
  #DIVISOR := 3
  #OUT := 'Fizz'
  PERFORM MODULO
*
  WRITE #I
END-FOR
*
DEFINE SUBROUTINE MODULO
#MODULO := #I - (#I / #DIVISOR) * #DIVISOR
IF #MODULO = 0
  WRITE NOTITLE #OUT
  ESCAPE TOP
END-IF
END-SUBROUTINE
*
END


defmodule Palindromic do
  import Integer, only: [is_odd: 1]

  def number23 do
    Stream.concat([0,1], Stream.unfold(1, &number23/1))
  end
  def number23(i) do
    n3 = Integer.to_string(i,3)
    n = (n3 <> "1" <> String.reverse(n3)) |> String.to_integer(3)
    n2 = Integer.to_string(n,2)
    if is_odd(String.length(n2)) and n2 == String.reverse(n2),
      do:   {n, i+1},
      else: number23(i+1)
  end

  def task do
    IO.puts "     decimal          ternary                          binary"
    number23()
    |> Enum.take(6)
    |> Enum.each(fn n ->
      n3 = Integer.to_charlist(n,3) |> :string.centre(25)
      n2 = Integer.to_charlist(n,2) |> :string.centre(39)
      :io.format "~12w ~s ~s~n", [n, n3, n2]
    end)
  end
end

Palindromic.task


// Find palindromic numbers in both binary and ternary bases. December 19th., 2018
let fG(n,g)=(Seq.unfold(fun(g,e)->if e<1L then None else Some((g%3L)*e,(g/3L,e/3L)))(n,g/3L)|>Seq.sum)+g+n*g*3L
Seq.concat[seq[0L;1L;2L];Seq.unfold(fun(i,e)->Some (fG(i,e),(i+1L,if i=e-1L then e*3L else e)))(1L,3L)]
  |>Seq.filter(fun n->let n=System.Convert.ToString(n,2).ToCharArray() in n=Array.rev n)|>Seq.take 6|>Seq.iter (printfn "%d")


var i = 1

while(i < 100) {
	if(i % 15 == 0) {
		$print("FizzBuzz\n");
	} else if(i % 3 == 0) {
		$print("Fizz\n");
	} else if(i % 5 == 0) {
		$print("Buzz\n");
	} else {
		$print(i + "\n");
	}

	i ++= 1
}


USING: combinators.short-circuit formatting io kernel lists
lists.lazy literals math math.parser sequences tools.time ;
IN: rosetta-code.2-3-palindromes

CONSTANT: info $[
    "The first 6 numbers which are palindromic in both binary "
    "and ternary:" append
]

: expand ( n -- m ) 3 >base dup <reversed> "1" glue 3 base> ;

: 2-3-pal? ( n -- ? )
    expand >bin
    { [ length odd? ] [ dup <reversed> sequence= ] } 1&& ;

: first6 ( -- seq )
    4 0 lfrom [ 2-3-pal? ] lfilter ltake list>array
    [ expand ] map { 0 1 } prepend ;

: main ( -- )
    info print nl first6 [
        dup [ >bin ] [ 3 >base ] bi
        "Decimal : %d\nBinary  : %s\nTernary : %s\n\n" printf
    ] each ;

[ main ] time


' FB 1.05.0 Win64

'converts decimal "n" to its ternary equivalent
Function Ter(n As UInteger) As String
  If n = 0 Then Return "0"
  Dim result As String = ""
  While n > 0
    result = (n Mod 3) & result
    n \= 3
  Wend
  Return result
End Function

' check if a binary or ternary numeric string "s" is palindromic
Function isPalindromic(s As String) As Boolean
  ' we can assume "s" will have an odd number of digits, so can ignore the middle digit
  Dim As UInteger length = Len(s)
  For i As UInteger = 0 To length \ 2 - 1
    If s[i] <> s[length - 1 - i] Then Return False
  Next
  Return True
End Function

' print a number which is both a binary and ternary palindrome in all three bases
Sub printPalindrome(n As UInteger)
  Print "Decimal : "; Str(n)
  Print "Binary  : "; bin(n)
  Print "Ternary : "; ter(n)
  Print
End Sub

' create a ternary palindrome whose left part is the ternary equivalent of "n" and return its decimal equivalent
Function createPalindrome3(n As UInteger) As UInteger
  Dim As String ternary = Ter(n)
  Dim As UInteger power3 = 1, sum = 0, length = Len(ternary)
  For i As Integer = 0 To Length - 1 ''right part of palindrome is mirror image of left part
    If ternary[i] > 48 Then  '' i.e. non-zero
      sum += (ternary[i] - 48) * power3
    End If
    power3 *= 3
  Next
  sum += power3 '' middle digit must be 1
  power3 *= 3
  sum += n * power3  '' value of left part is simply "n" multiplied by appropriate power of 3
  Return sum
End Function

Dim t As Double = timer
Dim As UInteger i = 1, p3, count = 2
Dim As String binStr
Print "The first 6 numbers which are palindromic in both binary and ternary are :"
Print
' we can assume the first two palindromic numbers as per the task description
printPalindrome(0) '' 0 is a palindrome in all 3 bases
printPalindrome(1) '' 1 is a palindrome in all 3 bases
Do
  p3 = createPalindrome3(i)
  If p3 Mod 2 > 0 Then ' cannot be even as binary equivalent would end in zero
    binStr = Bin(p3)  '' Bin function is built into FB
    If Len(binStr) Mod 2 = 1 Then  '' binary palindrome must have an odd number of digits
      If isPalindromic(binStr) Then
        printPalindrome(p3)
        count += 1
      End If
    End If
  End If
  i += 1
Loop Until count = 6
Print "Took ";
Print Using "#.###"; timer - t;
Print " seconds on i3 @ 2.13 GHz"
Print "Press any key to quit"
Sleep


using System;
using System.Console;

module FizzBuzz
{
    FizzBuzz(x : int) : string
    {
        |x when x % 15 == 0 => "FizzBuzz"
        |x when x %  5 == 0 => "Buzz"
        |x when x %  3 == 0 => "Fizz"
        |_                  => $"$x"
    }

    Main() : void
    {
        foreach (i in [1 .. 100])
            WriteLine($"$(FizzBuzz(i))")
    }
}


package main

import (
    "fmt"
    "strconv"
    "time"
)

func isPalindrome2(n uint64) bool {
    x := uint64(0)
    if (n & 1) == 0 {
        return n == 0
    }
    for x < n {
        x = (x << 1) | (n & 1)
        n >>= 1
    }
    return n == x || n == (x>>1)
}

func reverse3(n uint64) uint64 {
    x := uint64(0)
    for n != 0 {
        x = x*3 + (n % 3)
        n /= 3
    }
    return x
}

func show(n uint64) {
    fmt.Println("Decimal :", n)
    fmt.Println("Binary  :", strconv.FormatUint(n, 2))
    fmt.Println("Ternary :", strconv.FormatUint(n, 3))
    fmt.Println("Time    :", time.Since(start))
    fmt.Println()
}

func min(a, b uint64) uint64 {
    if a < b {
        return a
    }
    return b
}

func max(a, b uint64) uint64 {
    if a > b {
        return a
    }
    return b
}

var start time.Time

func main() {
    start = time.Now()
    fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
    show(0)
    cnt := 1
    var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
    for {
        i := lo
        for ; i < hi; i++ {
            n := (i*3+1)*pow3 + reverse3(i)
            if !isPalindrome2(n) {
                continue
            }
            show(n)
            cnt++
            if cnt >= 7 {
                return
            }
        }

        if i == pow3 {
            pow3 *= 3
        } else {
            pow2 *= 4
        }

        for {
            for pow2 <= pow3 {
                pow2 *= 4
            }

            lo2 := (pow2/pow3 - 1) / 3
            hi2 := (pow2*2/pow3-1)/3 + 1
            lo3 := pow3 / 3
            hi3 := pow3

            if lo2 >= hi3 {
                pow3 *= 3
            } else if lo3 >= hi2 {
                pow2 *= 4
            } else {
                lo = max(lo2, lo3)
                hi = min(hi2, hi3)
                break
            }
        }
    }
}


loop j=1 for 100
  select
    when j//15==0 then say 'FizzBuzz'
    when j//5==0  then say 'Buzz'
    when j//3==0  then say 'Fizz'
    otherwise say j.right(4)
  end
end


import Data.Char (digitToInt, intToDigit, isDigit)
import Data.List (transpose, unwords)
import Numeric (readInt, showIntAtBase)

---------- PALINDROMIC IN BOTH BINARY AND TERNARY --------

dualPalindromics :: [Integer]
dualPalindromics =
  0 :
  1 :
  take
    4
    ( filter
        isBinPal
        (readBase3 . base3Palindrome <$> [1 ..])
    )

base3Palindrome :: Integer -> String
base3Palindrome =
  ((<>) <*> (('1' :) . reverse)) . showBase 3

isBinPal :: Integer -> Bool
isBinPal n =
  ( \s ->
      ( \(q, r) ->
          (1 == r)
            && drop (succ q) s == reverse (take q s)
      )
        $ quotRem (length s) 2
  )
    $ showBase 2 n

--------------------------- TEST -------------------------
main :: IO ()
main =
  mapM_
    putStrLn
    ( unwords
        <$> transpose
          ( ( fmap
                =<< flip justifyLeft ' '
                  . succ
                  . maximum
                  . fmap length
            )
              <$> transpose
                ( ["Decimal", "Ternary", "Binary"] :
                  fmap
                    ( (<*>) [show, showBase 3, showBase 2]
                        . return
                    )
                    dualPalindromics
                )
          )
    )
  where
    justifyLeft n c s = take n (s <> replicate n c)

-------------------------- BASES -------------------------

readBase3 :: String -> Integer
readBase3 = fst . head . readInt 3 isDigit digitToInt

showBase :: Integer -> Integer -> String
showBase base n = showIntAtBase base intToDigit n []


func fizz_buzz() -> int
{
    var i = 1;

    for (i = 1; i <= 100; i = i + 1)
    {
        /* if (i % 15 == 0) */
        if (i % 3 == 0 && i % 5 == 0)
        {
            prints("Fizz Buzz\n")
        }
        else if (i % 3 == 0)
        {
            prints("Fizz\n")
        }
        else if (i % 5 == 0)
        {
            prints("Buzz\n")
        }
        else
        {
            prints(i + "\n")
        }
    };

    0
}

func main() -> int {
    fizz_buzz();

    0
}


isPalin=: -: |.                          NB. check if palindrome
toBase=: #.inv"0                         NB. convert to base(s) in left arg
filterPalinBase=: ] #~ [email protected]/   NB. palindromes for base(s)
find23Palindromes=: 3 filterPalinBase 2 filterPalinBase ]  NB. palindromes in both base 2 and base 3

showBases=: [: ;:[email protected]|: <@({&'0123456789ABCDEFGH')@toBase/ NB. display numbers in bases

NB.*getfirst a Adverb to get first y items returned by verb u
getfirst=: adverb define
  100000x u getfirst y
:
  res=. 0$0
  start=. 0
  blk=. i.x
  whilst. y > #res do.
    tmp=. u start + blk
    start=. start + x
    res=. res, tmp
  end.
  y{.res
)


public class Pali23 {
	public static boolean isPali(String x){
		return x.equals(new StringBuilder(x).reverse().toString());
	}

	public static void main(String[] args){

		for(long i = 0, count = 0; count < 6;i++){
			if((i & 1) == 0 && (i != 0)) continue; //skip non-zero evens, nothing that ends in 0 in binary can be in this sequence
			//maybe speed things up through short-circuit evaluation by putting toString in the if
			//testing up to 10M, base 2 has slightly fewer palindromes so do that one first
			if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
				System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
				count++;
			}
		}
	}
}


(() => {
    'use strict';

    // GENERIC FUNCTIONS

    // range :: Int -> Int -> [Int]
    const range = (m, n) =>
        Array.from({
            length: Math.floor(n - m) + 1
        }, (_, i) => m + i);

    // compose :: (b -> c) -> (a -> b) -> (a -> c)
    const compose = (f, g) => x => f(g(x));

    // listApply :: [(a -> b)] -> [a] -> [b]
    const listApply = (fs, xs) =>
        [].concat.apply([], fs.map(f =>
        [].concat.apply([], xs.map(x => [f(x)]))));

    // pure :: a -> [a]
    const pure = x => [x];

    // curry :: Function -> Function
    const curry = (f, ...args) => {
        const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :
            function () {
                return go(xs.concat([].slice.apply(arguments)));
            };
        return go([].slice.call(args, 1));
    };

    // transpose :: [[a]] -> [[a]]
    const transpose = xs =>
        xs[0].map((_, iCol) => xs.map(row => row[iCol]));

    // reverse :: [a] -> [a]
    const reverse = xs =>
        typeof xs === 'string' ? (
            xs.split('')
            .reverse()
            .join('')
        ) : xs.slice(0)
        .reverse();

    // take :: Int -> [a] -> [a]
    const take = (n, xs) => xs.slice(0, n);

    // drop :: Int -> [a] -> [a]
    const drop = (n, xs) => xs.slice(n);

    // maximum :: [a] -> a
    const maximum = xs =>
        xs.reduce((a, x) => (x > a || a === undefined ? x : a), undefined);

    // quotRem :: Integral a => a -> a -> (a, a)
    const quotRem = (m, n) => [Math.floor(m / n), m % n];

    // length :: [a] -> Int
    const length = xs => xs.length;

    // justifyLeft :: Int -> Char -> Text -> Text
    const justifyLeft = (n, cFiller, strText) =>
        n > strText.length ? (
            (strText + cFiller.repeat(n))
            .substr(0, n)
        ) : strText;

    // unwords :: [String] -> String
    const unwords = xs => xs.join(' ');

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // BASES AND PALINDROMES

    // show, showBinary, showTernary :: Int -> String
    const show = n => n.toString(10);
    const showBinary = n => n.toString(2);
    const showTernary = n => n.toString(3);

    // readBase3 :: String -> Int
    const readBase3 = s => parseInt(s, 3);

    // base3Palindrome :: Int -> String
    const base3Palindrome = n => {
        const s = showTernary(n);
        return s + '1' + reverse(s);
    };

    // isBinPal :: Int -> Bool
    const isBinPal = n => {
        const
            s = showBinary(n),
            [q, r] = quotRem(s.length, 2);
        return (r !== 0) && drop(q + 1, s) === reverse(take(q, s));
    };

    // solutions :: [Int]
    const solutions = [0, 1].concat(range(1, 10E5)
        .map(compose(readBase3, base3Palindrome))
        .filter(isBinPal));

    // TABULATION

    // cols :: [[Int]]
    const cols = transpose(
        [
            ['Decimal', 'Ternary', 'Binary']
        ].concat(
            solutions.map(
                compose(
                    xs => listApply([show, showTernary, showBinary], xs),
                    pure
                )
            )
        )
    );

    return unlines(
        transpose(cols.map(col => col.map(
            curry(justifyLeft)(maximum(col.map(length)) + 1, ' ')
        )))
        .map(unwords));
})();


for i := 1 to 100 do
begin
	if i mod 15 = 0 then
		print("FizzBuzz")
	else if i mod 3 = 0 then
		print("Fizz")
	else if i mod 5 = 0 then
		print("Buzz")
	else
		print(i);
	print("\n")
end


ispalindrome(n, bas) = (s = string(n, base=bas); s == reverse(s))
prin3online(n) = println(lpad(n, 15), lpad(string(n, base=2), 40), lpad(string(n, base=3), 30))
reversebase3(n) = (x = 0; while n != 0 x = 3x + (n %3); n = div(n, 3); end; x)

function printpalindromes(N)
    lo, hi, pow2, pow3, count, i = 0, 1, 1, 1, 1, 0
    println(lpad("Number", 15), lpad("Base 2", 40), lpad("Base 3", 30))
    prin3online(0)
    while true
        for j in lo:hi-1
            i = j
            n = (3 * j + 1) * pow3 + reversebase3(j)
            if ispalindrome(n, 2)
                prin3online(n)
                count += 1
                if count >= N
                    return
                end
            end
        end
        if i == pow3
            pow3 *= 3
        else
            pow2 *= 4
        end

        while true
            while pow2 <= pow3
                pow2 *= 4
            end
            lo2 = div(div(pow2, pow3) - 1, 3)
            hi2 = div(div(pow2 * 2, pow3), 3) + 1
            lo3 = div(pow3, 3)
            hi3 = pow3

            if lo2 >= hi3
                pow3 *= 3
            elseif lo3 >= hi2
                pow2 *= 4
            else
                lo = max(lo2, lo3)
                hi = min(hi2, hi3)
                break
            end
        end
    end
end

printpalindromes(6)


// version 1.0.5-2

/** converts decimal 'n' to its ternary equivalent */
fun Long.toTernaryString(): String = when {
    this < 0L  -> throw IllegalArgumentException("negative numbers not allowed")
    this == 0L -> "0"
    else   -> {
        var result = ""
        var n = this
        while (n > 0) {
            result += n % 3
            n /= 3
        }
        result.reversed()
    }
}

/** wraps java.lang.Long.toBinaryString in a Kotlin extension function */
fun Long.toBinaryString(): String = java.lang.Long.toBinaryString(this)

/** check if a binary or ternary numeric string 's' is palindromic */
fun isPalindromic(s: String): Boolean = (s == s.reversed())

/** print a number which is both a binary and ternary palindrome in all three bases */
fun printPalindrome(n: Long) {
    println("Decimal : $n")
    println("Binary  : ${n.toBinaryString()}")
    println("Ternary : ${n.toTernaryString()}")
    println()
}

/** create a ternary palindrome whose left part is the ternary equivalent of 'n' and return its decimal equivalent */
fun createPalindrome3(n: Long): Long {
    val ternary = n.toTernaryString()
    var power3 = 1L
    var sum = 0L
    val length = ternary.length
    for (i in 0 until length) {  // right part of palindrome is mirror image of left part
        if (ternary[i] > '0') sum += (ternary[i].toInt() - 48) * power3
        power3 *= 3L
    }
    sum += power3 // middle digit must be 1
    power3 *= 3L
    sum += n * power3  // value of left part is simply 'n' multiplied by appropriate power of 3
    return sum
}

fun main(args: Array<String>) {
    var i = 1L
    var p3: Long
    var count = 2
    var binStr: String
    println("The first 6 numbers which are palindromic in both binary and ternary are:\n")
    // we can assume the first two palindromic numbers as per the task description
    printPalindrome(0L)  // 0 is a palindrome in all 3 bases
    printPalindrome(1L)  // 1 is a palindrome in all 3 bases

    do {
        p3 = createPalindrome3(i)
        if (p3 % 2 > 0L)  { // cannot be even as binary equivalent would end in zero
            binStr = p3.toBinaryString()
            if (binStr.length % 2 == 1) { // binary palindrome must have an odd number of digits
                if (isPalindromic(binStr)) {
                    printPalindrome(p3)
                    count++
                }
            }
        }
        i++
    }
    while (count < 6)
}


/* Fizzbuzz in nickle */

void function fizzbuzz(size) {
    for (int i = 1; i < size; i++) {
        if (i % 15 == 0) { printf("Fizzbuzz\n"); }
        else if (i % 5 == 0) { printf("Buzz\n"); }
        else if (i % 3 == 0) { printf("Fizz\n"); }
        else { printf("%i\n", i); }
    }
}

fizzbuzz(1000);


palindromify3[n_] :=
    Block[{digits},
      If[Divisible[n, 3], {},
         digits = IntegerDigits[n, 3];
         FromDigits[#, 3] & /@
            {Join[Reverse[digits], digits], Join[Reverse[Rest[digits]], {First[digits]}, Rest[digits]]}
      ]
    ];
base2PalindromeQ[n_] := IntegerDigits[n, 2] === Reverse[IntegerDigits[n, 2]];
Select[Flatten[palindromify3 /@ Range[1000000]], base2PalindromeQ]


check(n)={ \\ Check for 2n+1-digit palindromes in base 3
  my(N=3^n);
  forstep(i=N+1,2*N,[1,2],
    my(base2,base3=digits(i,3),k);
    base3=concat(Vecrev(base3[2..n+1]), base3);
    k=subst(Pol(base3),'x,3);
    base2=binary(k);
    if(base2==Vecrev(base2), print1(", "k))
  )
};
print1("0, 1"); for(i=1,11,check(i))


for i in 1..100:
  if i mod 15 == 0:
    echo("FizzBuzz")
  elif i mod 3 == 0:
    echo("Fizz")
  elif i mod 5 == 0:
    echo("Buzz")
  else:
    echo(i)


with (import <nixpkgs> { }).lib;
with builtins;
let
  fizzbuzz = { x ? 1 }:
    ''
      ${if (mod x 15 == 0) then
        "FizzBuzz"
      else if (mod x 3 == 0) then
        "Fizz"
      else if (mod x 5 == 0) then
        "Buzz"
      else
        (toString x)}
    '' + (if (x < 100) then
      fizzbuzz { x = x + 1; } else "");
in
fizzbuzz { }


use ntheory qw/fromdigits todigitstring/;

print "0  0  0\n";  # Hard code the 0 result
for (0..2e5) {
  # Generate middle-1-palindrome in base 3.
  my $pal = todigitstring($_, 3);
  my $b3 = $pal . "1" . reverse($pal);
  # Convert base 3 number to base 2
  my $b2 = todigitstring(fromdigits($b3, 3), 2);
  # Print results (including base 10) if base-2 palindrome
  print fromdigits($b2,2),"  $b3  $b2\n"   if $b2 eq reverse($b2);
}


with javascript_semantics
-- widths and limits for 32/64 bit running (see output below):
constant {dsize,w3,w2,limit} = iff(machine_bits()=32?{12,23,37,6}
                                                    :{18,37,59,7}),
-- [atoms on 32-bit have only 53 bits of precision, but 7th ^^^^ requires 59]
         dfmt = sprintf("%%%dd",dsize), -- ie "%12d" or "%18d"
         esc = #1B

function center(string s, integer l)
    l = max(0,floor((l-length(s))/2))
    string space = repeat(' ',l)
    s = space & s & space
    return s
end function

integer count = 1

procedure show(atom n, string p2, p3)
    if count=1 then
        printf(1,"    %s %s %s\n",{pad_head("decimal",dsize),center("ternary",w3),center(" binary",w2)})
    end if
    string ns = sprintf(dfmt,n)
    printf(1,"%2d: %s %s %s\n",{count, ns, center(p3,w3), center(p2,w2)})
    count += 1
end procedure

procedure progress64(string e, p2, p3)
    e = pad_head(e,dsize)
    printf(1,"--: %s %s %s\r",{e, center(p3,w3), center(p2,w2)})
end procedure

function to_base(atom i, integer base)
    string s = ""
    while i>0 do
        s = append(s,remainder(i,base)+'0')
        i = floor(i/base)
    end while
    s = reverse(s)
    if s="" then
        s = "0"
    end if
    return s
end function

function from_base(string s, integer base)
    atom res = 0
    for i=1 to length(s) do
        res = res*base+s[i]-'0'
    end for
    return res
end function

function sn(string s, integer f, base)
-- helper function, return s mirrored (if f!=0)
--       and as a (decimal) number (if base!=0)
-- all returns from next_palindrome() get fed through here.
    if f then
        s[f+2..$] = reverse(s[1..f])
    end if
    atom n = iff(base?from_base(s,base):0)
    return {s,n}
end function

function next_palindrome(integer base, object s)
--
-- base is 2 or 3
-- s is not usually a palindrome, but derived from one in <5-base>
--
-- all done with very obvious string manipulations, plus a few
-- less obvious optimisations (odd length, middle 1 in base 3).
--
-- example: next_palindrome(2,"10001000100") -> "10001010001"
--
    if not string(s) then s = to_base(s,base) end if
    integer l = length(s),
            f = floor(l/2),
            m = f+1, c
    if mod(l,2) then    -- optimisation: palindromes must be odd-length
        -- 1) is a plain mirror greater? (as in the example just given)
        {string r} = sn(s,f,0)
        -- optimisation: base 3 palindromes have '1' in the middle
        if base=3 and r[m]!='1' then r[m] = '1' end if
        if r>s then return sn(r,0,base) end if
        -- 2) can we (just) increment the middle digit?
        c = s[m]-'0'+1
        if base=2 or c=1 then
            if c<base then
                s[m] = c+'0'
                return sn(s,f,base)
            end if
            s[m] = '0'
        elsif base=3 then
            s[m] = '1'
        end if
        -- 3) can we increment left half (or is it all <base-1>s?)
        for i=f to 1 by -1 do
            if s[i]<base-1+'0' then
                s[i] += 1
                return sn(s,f,base)
            else
                s[i] = '0'
            end if
        end for
        l += 2  -- (stay odd)
    else
        l += 1  -- (even->odd)
    end if
    -- 4) well then, next palindrome is longer, 1000..0001-style
    s = sprintf("1%s1",{repeat('0',l-2)})
    -- optimisation: base 3 palindromes have '1' in the middle
    if base=3 then
        m = (l+1)/2
        s[m] = '1'
    end if
    return sn(s,0,base)
end function

string p2 = "0", p3 = "0"   -- palindromes as strings in base 2 and 3
atom n2 = 0, n3 = 0,        -- decimal equivalents of the above.
     t0 = time(),
     t1 = time()+1

while count<=limit do
    if n2=n3 then
        show(n2,p2,p3)
        {p2,n2} = next_palindrome(2,p2)
        {p3,n3} = next_palindrome(3,p3)
    elsif n2<n3 then
        {p2,n2} = next_palindrome(2,n3-1)
    elsif n2>n3 then
        {p3,n3} = next_palindrome(3,n2-1)
    end if
    if time()>t1 and platform()!=JS then
        progress64(elapsed_short(time()-t0),p2,p3)
        t1 = time()+1
        if find(get_key(),{'q','Q',esc}) then exit end if
    end if
end while
?elapsed(time()-t0)


MODULE FizzBuzz;

   IMPORT Out;

   VAR i: INTEGER;

BEGIN
   FOR i := 1 TO 100 DO
      IF i MOD 15 = 0 THEN
         Out.String("FizzBuzz")
      ELSIF i MOD 5 = 0 THEN
         Out.String("Buzz")
      ELSIF i MOD 3 = 0 THEN
         Out.String("Fizz")
      ELSE
         Out.Int(i,0)
      END;
      Out.Ln
   END
END FizzBuzz.


import sat.
to_num(List, Base, Num) =>
        Len = length(List),
        Num #= sum([List[I] * Base**(Len-I) : I in 1..Len]).

palindrom(S) =>
    N = len(S),
    Start :: 1..N, % start at the first non-zero position:
    foreach(I in 1..N)
        I1 #= max(1, min(N, N-(I-Start))), % I1 is the symmetry index partner of I (if relevant)
        element(I1, S, S1),                % S1 is the respective digit
        I #<  Start #=> S[I] #= 0,         % skip leading 0´s
        I #=  Start #=> S[I] #> 0,         % Start points to the first non-zero digit
        I #>= Start #=> S[I] #= S1         % palindromic symmetry
    end.

constrain(Max, B, X) =>
    Len = floor(log(Max) / log(B)) + 1, % length of Max in Base B representation
    Digits = new_list(Len), Digits :: 0..B-1,
    to_num(Digits, B, X), % Digits show the Base B representation of X
    palindrom(Digits).

main =>
    N = 11, % maximum number of decimal digits for search, can be set freely
    Max = 10**N - 1, % maximum number
    X :: 2..Max,
    constrain(Max, 2, X),
    constrain(Max, 3, X),
    Pnumbers = solve_all([X]),
    foreach([Y] in [[0], [1]] ++ Pnumbers.sort()) % start with 0 and 1, then show solutions > 1
        printf("%w %s %s%n", Y, to_radix_string(Y,2), to_radix_string(Y,3))
    end.


(de ternary (N)
   (if (=0 N)
      (cons N)
      (make
         (while (gt0 N)
            (yoke (% (swap 'N (/ N 3)) 3)) ) ) ) )
(de p? (L1 L2)
   (and
      (= L1 (reverse L1))
      (= L2 (reverse L2)) ) )

(zero N)
(for (I 0 (> 6 I))
   (let (B2 (chop (bin N))  B3 (ternary N))
      (when (p? B2 B3)
         (println N (pack B2) (pack B3))
         (inc 'I) )
      (inc 'N) ) )


from itertools import islice

digits = "0123456789abcdefghijklmnopqrstuvwxyz"

def baseN(num,b):
  if num == 0: return "0"
  result = ""
  while num != 0:
    num, d = divmod(num, b)
    result += digits[d]
  return result[::-1] # reverse

def pal2(num):
    if num == 0 or num == 1: return True
    based = bin(num)[2:]
    return based == based[::-1]

def pal_23():
    yield 0
    yield 1
    n = 1
    while True:
        n += 1
        b = baseN(n, 3)
        revb = b[::-1]
        #if len(b) > 12: break
        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
            t = int(trial, 3)
            if pal2(t):
                yield t

for pal23 in islice(pal_23(), 6):
    print(pal23, baseN(pal23, 3), baseN(pal23, 2))


bundle Default {
  class Fizz {
    function : Main(args : String[]) ~ Nil {
      for(i := 0; i <= 100; i += 1;) {
        if(i % 15 = 0) {
          "FizzBuzz"->PrintLine();
        }
        else if(i % 3 = 0) {
          "Fizz"->PrintLine();
        }
        else if(i % 5 = 0) {
          "Buzz"->PrintLine();
        }
        else {
          i->PrintLine();
        };
      };
    }
  }
}


#lang racket
(require racket/generator)

(define (digital-reverse/base base N)
  (define (inr n r)
    (if (zero? n) r (inr (quotient n base) (+ (* r base) (modulo n base)))))
  (inr N 0))

(define (palindrome?/base base N)
  (define (inr? n m)
    (if (= n 0)
        (= m N)
        (inr? (quotient n base) (+ (* m base) (modulo n base)))))
  (inr? N 0))

(define (palindrome?/3 n)
  (palindrome?/base 3 n))

(define (b-palindromes-generator b)
  (generator
   ()
   ;; it's a bit involved getting the initial palindroms, so we do them manually
   (for ((p (in-range b))) (yield p))
   (let loop ((rhs 1) (mx-rhs b) (mid #f) (mx-rhs*b (* b b)))
     (cond
       [(= rhs mx-rhs)
        (cond
          [(not mid) (loop (quotient mx-rhs b) mx-rhs 0 mx-rhs*b)]
          [(zero? mid) (loop mx-rhs mx-rhs*b #f (* mx-rhs*b b))])]
       [else
        (define shr (digital-reverse/base b rhs))
        (cond
          [(not mid)
           (yield (+ (* rhs mx-rhs) shr))
           (loop (add1 rhs) mx-rhs #f mx-rhs*b)]
          [(= mid (- b 1))
           (yield (+ (* rhs mx-rhs*b) (* mid mx-rhs) shr))
           (loop (+ 1 rhs) mx-rhs 0 mx-rhs*b)]
          [else
           (yield (+ (* rhs mx-rhs*b) (* mid mx-rhs) shr))
           (loop rhs mx-rhs (add1 mid) mx-rhs*b)])]))))

(define (number->string/base n b)
  (define (inr acc n)
    (if (zero? n) acc
        (let-values (((q r) (quotient/remainder n b)))
          (inr (cons (number->string r) acc) q))))
  (if (zero? n) "0" (apply string-append (inr null n))))

(module+ main
  (for ((n (sequence-filter palindrome?/3 (in-producer (b-palindromes-generator 2))))
        (i (in-naturals))
        #:final (= i 5))
    (printf "~a: ~a_10 ~a_3 ~a_2~%"
            (~a #:align 'right #:min-width  3 (add1 i))
            (~a #:align 'right #:min-width 11 n)
            (~a #:align 'right #:min-width 23 (number->string/base n 3))
            (~a #:align 'right #:min-width 37 (number->string/base n 2)))))

(module+ test
  (require rackunit)
  (check-true  (palindrome?/base 2 #b0))
  (check-true  (palindrome?/base 2 #b10101))
  (check-false (palindrome?/base 2 #b1010))
  (define from-oeis:A060792
    (list 0 1 6643 1422773 5415589 90396755477 381920985378904469
          1922624336133018996235 2004595370006815987563563
          8022581057533823761829436662099))
  (check-match from-oeis:A060792
               (list (? (curry palindrome?/base 2)
                        (? (curry palindrome?/base 3))) ...))

  (check-eq? (digital-reverse/base 2 #b0)        #b0)
  (check-eq? (digital-reverse/base 2 #b1)        #b1)
  (check-eq? (digital-reverse/base 2 #b10)      #b01)
  (check-eq? (digital-reverse/base 2 #b1010)  #b0101)

  (check-eq? (digital-reverse/base 10 #d0)       #d0)
  (check-eq? (digital-reverse/base 10 #d1)       #d1)
  (check-eq? (digital-reverse/base 10 #d10)     #d01)
  (check-eq? (digital-reverse/base 10 #d1010) #d0101)

  (define pg ((b-palindromes-generator 2)))
  (check-match
   (map (curryr number->string 2) (for/list ((i 16) (p (in-producer (b-palindromes-generator 2)))) p))
   (list "0" "1" "11" "101" "111" "1001" "1111" "10001" "10101" "11011"
         "11111" "100001" "101101" "110011" "111111" "1000001")))


constant palindromes = 0, 1, |gather for 1 .. * -> $p {
    my $pal = $p.base(3);
    my $n = :3($pal ~ '1' ~ $pal.flip);
    next if $n %% 2;
    my $b2 = $n.base(2);
    next if $b2.chars %% 2;
    next unless $b2 eq $b2.flip;
    take $n;
}

printf "%d, %s, %s\n", $_, .base(2), .base(3) for palindromes[^6];


// FizzBuzz in Objective-C
#import <Foundation/Foundation.h>

int main(int argc, char* argv[]) {
	for (NSInteger i=1; I <= 101; i++) {
		if (i % 15 == 0) {
		    NSLog(@"FizzBuzz\n");
		} else if (i % 3 == 0) {
		    NSLog(@"Fizz\n");
		} else if (i % 5 == 0) {
		    NSLog(@"Buzz\n");
		} else {
		    NSLog(@"%li\n", i);
		}
	}
}


/*REXX program finds  numbers  that are  palindromic  in both  binary  and  ternary.    */
digs=50;  numeric digits digs                    /*biggest known B2B3 palindrome: 44 dig*/
parse arg maxHits .;   if maxHits==''  then maxHits=6              /*use six as a limit.*/
hits=0;                      #= 'fiat'           /*the number of palindromes  (so far). */
call show 0,0,0;       call show 1,1,1           /*show the first two palindromes (fiat)*/
!.=                                              /* [↓]  build list of powers of three. */
     do i=1  until !.i>10**digs;  !.i=3**i;  end /*compute powers of  three  for radix3.*/
p=1                                              /* [↓]  primary search: bin palindromes*/
     do #=digs                                   /*use all numbers, however, DEC is odd.*/
     binH=x2b( d2x(#) )   + 0                    /*convert some decimal number to binary*/
     binL=reverse(binH)                          /*reverse the binary digits  (or bits).*/
     dec=x2d( b2x( binH'0'binL) );   if dec//3\==0  then call radix3
     dec=x2d( b2x( binH'1'binL) );   if dec//3\==0  then call radix3
     end   /*#*/                                 /* [↑]  crunch 'til found 'nuff numbers*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
radix3: parse var dec x 1 $,q                    /* [↓] convert decimal  # ──►  ternary.*/
                 do j=p  while !.j<=x;   end     /*find upper limit of power of three.  */
        p=j-1                                    /*use this power of three for next time*/
                 do k=p  by -1  for p;   _=!.k;   d=x%_;   q=q || d;   x=x//_;   end /*k*/
        t=q || x                                 /*handle residual of ternary conversion*/
        if t\==reverse(t)  then return           /*is T ternary number not palindromic? */
        call show $, t, strip(x2b(d2x($)), , 0)  /*show number: decimal, ternary, binary*/
        return                                   /* [↑]   RADIX3 subroutine is sluggish.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: hits=hits+1;         say                   /*bump the number of palindromes found.*/
      say right('['hits"]", 5)   right( arg(1), digs)   '(decimal),   ternary='  arg(2)
      say right('', 5+1+ digs)                          '             binary ='  arg(3)
      if hits>2  then  if hits//2  then #=#'0'
      if hits<maxHits  then return               /*Not enough palindromes?  Keep looking*/
      exit                                       /*stick a fork in it,  we're all done. */


# Project: Find palindromic numbers in both binary and ternary bases

max = 6
nr = 0
pal = 0
see "working..." + nl
see "wait for done..." + nl
while true
      binpal = basedigits(nr,2)
      terpal = basedigits(nr,3)
      bool1 = ispalindrome(binpal)
      bool2 = ispalindrome(terpal)
      if bool1 = 1 and bool2 = 1
         pal = pal + 1
         see string(nr) + " " + binpal + "(2) " + terpal + "(3)" + nl
         if pal = max
            exit
         ok
      ok
      nr = nr + 1
end
see "done..." + nl

func basedigits(n,base)
     if n = 0
        return "0"
     ok
     result = ""
     while n > 0
           result = string(n % base) + result
           n = floor(n/base)
     end
     return result

func ispalindrome(astring)
     if astring = "0"
        return 1
     ok
     bString = ""
     for i=len(aString) to 1 step -1
         bString = bString + aString[i]
     next
     if aString = bString
        return 1
     else
        return 0
     ok


let fizzbuzz i =
  match i mod 3, i mod 5 with
    0, 0 -> "FizzBuzz"
  | 0, _ -> "Fizz"
  | _, 0 -> "Buzz"
  | _    -> string_of_int i

let _ =
  for i = 1 to 100 do print_endline (fizzbuzz i) done


pal23 = Enumerator.new do |y|
  y << 0
  y << 1
  for i in 1 .. 1.0/0.0                 # 1.step do |i|  (Ruby 2.1+)
    n3 = i.to_s(3)
    n = (n3 + "1" + n3.reverse).to_i(3)
    n2 = n.to_s(2)
    y << n  if n2.size.odd? and n2 == n2.reverse
  end
end

puts "         decimal          ternary                          binary"
6.times do |i|
  n = pal23.next
  puts "%2d: %12d %s %s" % [i, n, n.to_s(3).center(25), n.to_s(2).center(39)]
end


import scala.annotation.tailrec
import scala.compat.Platform.currentTime

object Palindrome23 extends App {
  private val executionStartTime = currentTime
  private val st: Stream[(Int, Long)] = (0, 1L) #:: st.map(xs => nextPalin3(xs._1))

  @tailrec
  private def nextPalin3(n: Int): (Int, Long) = {

    @inline
    def isPali2(i: BigInt): Boolean = {
      val s = i.toString(2)
      if ((s.length & 1) == 0) false else s == s.reverse
    }

    def palin3(i: BigInt): Long = {
      val n3 = i.toString(3)
      java.lang.Long.parseLong(n3 + "1" + n3.reverse, 3)
    }

    val actual: Long = palin3(n)
    if (isPali2(actual)) (n + 1, actual) else nextPalin3(n + 1)
  }

  println(f"${"Decimal"}%18s${"Binary"}%35s${"Ternary"}%51s")
  (Stream(0L) ++ st.map(_._2)).take(6).foreach(n => {
    val bigN = BigInt(n)
    val (bin, ter) = (bigN.toString(2), bigN.toString(3))

    println(f"${n}%18d, ${
      bin + " " * ((60 - bin.length) / 2)}%60s, ${
      ter + " " * ((37 - ter.length) / 2)}%37s")
  })

  println(s"Successfully completed without errors. [total ${currentTime - executionStartTime} ms]")

}


for i = 1:100
  if ( mod(i,15) == 0 )
    disp("FizzBuzz");
  elseif ( mod(i, 3) == 0 )
    disp("Fizz")
  elseif ( mod(i, 5) == 0 )
    disp("Buzz")
  else
    disp(i)
  endif
endfor


(import (scheme base)
        (scheme write)
        (srfi 1 lists)) ; use 'fold' from SRFI 1

;; convert number to a list of digits, in desired base
(define (r-number->list n base)
  (let loop ((res '())
             (num n))
    (if (< num base)
      (cons num res)
      (loop (cons (remainder num base) res)
            (quotient num base)))))

;; convert number to string, in desired base
(define (r-number->string n base)
  (apply string-append
         (map number->string
              (r-number->list n base))))

;; test if a list of digits is a palindrome
(define (palindrome? lst)
  (equal? lst (reverse lst)))

;; based on Perl/Ruby's insight
;; -- construct the ternary palindromes in order
;;    using fact that their central number is always a 1
;; -- convert into binary, and test if result is a palindrome too
(define (get-series size)
  (let loop ((results '(1 0))
             (i 1))
    (if (= size (length results))
      (reverse results)
      (let* ((n3 (r-number->list i 3))
             (n3-list (append n3 (list 1) (reverse n3)))
             (n10 (fold (lambda (d t) (+ d (* 3 t))) 0 n3-list))
             (n2 (r-number->list n10 2)))
        (loop (if (palindrome? n2)
                (cons n10 results)
                results)
              (+ 1 i))))))

;; display final results, in bases 10, 2 and 3.
(for-each
  (lambda (n)
    (display
      (string-append (number->string n)
                     " in base 2: "
                     (r-number->string n 2)
                     " in base 3: "
                     (r-number->string n 3)))
    (newline))
  (get-series 6))


: fizzbuzz
| i |
   100 loop: i [
      null
      i 3 mod ifZero: [ "Fizz" + ]
      i 5 mod ifZero: [ "Buzz" + ]
      dup ifNull: [ drop i ] .
      ] ;


var format = "%11s %24s %38s\n"
format.printf("decimal", "ternary", "binary")
format.printf(0, 0, 0)

for n in (0 .. 2e5) {
    var pal = n.base(3)||''
    var b3 = (pal + '1' + pal.flip)
    var b2 = Num(b3, 3).base(2)
    if (b2 == b2.flip) {
        format.printf(Num(b2, 2), b3, b2)
    }
}