import std.algorithm;
import std.array;
import std.range;
import std.stdio;

alias matrix = int[][];

auto dList(int n, int start) {
    start--;    // use 0 basing
    auto a = iota(0, n).array;
    a[start] = a[0];
    a[0] = start;
    sort(a[1..$]);
    auto first = a[1];
    // recursive closure permutes a[1:]
    matrix r;
    void recurse(int last) {
        if (last == first) {
            // bottom of recursion. you get here once for each permutation.
            // test if permutation is deranged.
            foreach (j,v; a[1..$]) {
                if (j + 1 == v) {
                    return; //no, ignore it
                }
            }
            // yes, save a copy with 1 based indexing
            auto b = a.map!"a+1".array;
            r ~= b;
            return;
        }
        for (int i = last; i >= 1; i--) {
            swap(a[i], a[last]);
            recurse(last -1);
            swap(a[i], a[last]);
        }
    }
    recurse(n - 1);
    return r;
}

ulong reducedLatinSquares(int n, bool echo) {
    if (n <= 0) {
        if (echo) {
            writeln("[]\n");
        }
        return 0;
    } else if (n == 1) {
        if (echo) {
            writeln("[1]\n");
        }
        return 1;
    }

    matrix rlatin = uninitializedArray!matrix(n);
    foreach (i; 0..n) {
        rlatin[i] = uninitializedArray!(int[])(n);
    }
    // first row
    foreach (j; 0..n) {
        rlatin[0][j] = j + 1;
    }

    ulong count;
    void recurse(int i) {
        auto rows = dList(n, i);

        outer:
        foreach (r; 0..rows.length) {
            rlatin[i-1] = rows[r].dup;
            foreach (k; 0..i-1) {
                foreach (j; 1..n) {
                    if (rlatin[k][j] == rlatin[i - 1][j]) {
                        if (r < rows.length - 1) {
                            continue outer;
                        }
                        if (i > 2) {
                            return;
                        }
                    }
                }
            }
            if (i < n) {
                recurse(i + 1);
            } else {
                count++;
                if (echo) {
                    printSquare(rlatin, n);
                }
            }
        }
    }

    // remaining rows
    recurse(2);
    return count;
}

void printSquare(matrix latin, int n) {
    foreach (row; latin) {
        writeln(row);
    }
    writeln;
}

ulong factorial(ulong n) {
    if (n == 0) {
        return 1;
    }
    ulong prod = 1;
    foreach (i; 2..n+1) {
        prod *= i;
    }
    return prod;
}

void main() {
    writeln("The four reduced latin squares of order 4 are:\n");
    reducedLatinSquares(4, true);

    writeln("The size of the set of reduced latin squares for the following orders");
    writeln("and hence the total number of latin squares of these orders are:\n");
    foreach (n; 1..7) {
        auto size = reducedLatinSquares(n, false);
        auto f = factorial(n - 1);
        f *= f * n * size;
        writefln("Order %d: Size %-4d x %d! x %d! => Total %d", n, size, n, n - 1, f);
    }
}


-V n = 13

F method1(n)
   V squares = (0..n).map(x -> x ^ 2)
   V sqrset = Set(squares)
   Set[(Int, Int, Int)] tri90, tri60, tri120

   L(a) 1..n
      V a2 = squares[a]
      L(b) 1..a
         V b2 = squares[b]
         V c2 = a2 + b2
         I c2 C sqrset
            tri90.add(tuple_sorted((a, b, Int(sqrt(c2)))))
         V ab = a * b
         c2 -= ab
         I c2 C sqrset
            tri60.add(tuple_sorted((a, b, Int(sqrt(c2)))))
         c2 += 2 * ab
         I c2 C sqrset
            tri120.add(tuple_sorted((a, b, Int(sqrt(c2)))))
   R [sorted(Array(tri90)),
      sorted(Array(tri60)),
      sorted(Array(tri120))]

print(‘Integer triangular triples for sides 1..#.:’.format(n))
L(angle, triples) zip([90, 60, 120], method1(n))
   print("  #3° has #. solutions:\n    #.".format(angle, triples.len, triples))
V t60 = method1(10'000)[1]
V notsame = sum(t60.filter((a, b, c) -> a != b | b != c).map((a, b, c) -> 1))
print(‘Extra credit: ’notsame)


.&ws.say for slurp.comb.Bag.sort: -*.value;

sub ws ($pair) {
    $pair.key ~~ /\n/
    ?? ('NEW LINE' => $pair.value)
    !! $pair.key ~~ /\s/
    ?? ($pair.key.uniname => $pair.value)
    !! $pair
}


define count_letters use $words
   { } as $wordHash    [ ] as $keys   [ ]  as $vals
   $words each chr
      dup $wordHash swap get 0 prefer 1 +   # stack: chr cnt
      swap $wordHash swap set
   $wordHash keys copy sort each
      dup $keys push
      $wordHash swap get $vals push
   $keys $vals combine  print "\n" print

"test.dat" as $file
$file read as $all_data
$all_data count_letters


with javascript_semantics
include mpfr.e

sequence lf_list

procedure init(integer n)
    mpz f = mpz_init(1)
    lf_list = repeat(f,n+1)
    for i=1 to n do
        f = mpz_init_set(f)
        mpz_mul_si(f,f,i)
        lf_list[i+1] = f
    end for
end procedure

function lf(integer n, bool len=false)
-- Returns left factorial of n, or it's length, as a string
    mpz sumf = mpz_init(0)
    for k=1 to n do mpz_add(sumf,sumf,lf_list[k]) end for
    return iff(len?sprintf("%d",mpz_sizeinbase(sumf,10))
                  :shorten(mpz_get_str(sumf)))
end function

-- Main procedure
atom t0 = time()
init(10000)
for i=0 to 10 do printf(1,"!%d = %s\n",{i,lf(i)}) end for
for i=20 to 110 by 10 do printf(1,"!%d = %s\n",{i,lf(i)}) end for
for i=1000 to 10000 by 1000 do printf(1,"!%d contains %s digits\n",{i,lf(i,true)}) end for
printf(1,"complete (%3.2fs)\n",{time()-t0})


(de n! (N)
       (cache '(NIL) N
          (if (> 2 N) 1
	      (* N (n! (dec N))))))

(de !n (Num)
  (if (= Num 0) 1
      (sum n! (range 0 (dec Num)))))

(de pril (List) (mapcar 'println List))

(prinl "0-10")
(pril (mapcar '!n (range 0 10)))
(prinl "20 - 110")
(pril (mapcar '!n (range 20 110 10)))
(prinl "length of 1000 - 10000")
(pril (mapcar 'length (mapcar '!n (range 1000 10000 1000))))


// Generate Latin Squares in reduced form. Nigel Galloway: July 10th., 2019
let normLS α=
  let N=derange α|>List.ofSeq|>List.groupBy(fun n->n.[0])|>List.sortBy(fun(n,_)->n)|>List.map(fun(_,n)->n)|>Array.ofList
  let rec fG n g=match n with h::t->fG t (g|>List.filter(fun g->Array.forall2((<>)) h g )) |_->g
  let rec normLS n g=seq{for i in fG n N.[g] do if g=α-2 then yield [|1..α|]::(List.rev (i::n)) else yield! normLS (i::n) (g+1)}
  match α with 1->seq[[[|1|]]] |2-> seq[[[|1;2|];[|2;1|]]] |_->Seq.collect(fun n->normLS [n] 1) N.[0]


package main

import (
    "fmt"
    "sort"
)

type matrix [][]int

// generate derangements of first n numbers, with 'start' in first place.
func dList(n, start int) (r matrix) {
    start-- // use 0 basing
    a := make([]int, n)
    for i := range a {
        a[i] = i
    }
    a[0], a[start] = start, a[0]
    sort.Ints(a[1:])
    first := a[1]
    // recursive closure permutes a[1:]
    var recurse func(last int)
    recurse = func(last int) {
        if last == first {
            // bottom of recursion.  you get here once for each permutation.
            // test if permutation is deranged.
            for j, v := range a[1:] { // j starts from 0, not 1
                if j+1 == v {
                    return // no, ignore it
                }
            }
            // yes, save a copy
            b := make([]int, n)
            copy(b, a)
            for i := range b {
                b[i]++ // change back to 1 basing
            }
            r = append(r, b)
            return
        }
        for i := last; i >= 1; i-- {
            a[i], a[last] = a[last], a[i]
            recurse(last - 1)
            a[i], a[last] = a[last], a[i]
        }
    }
    recurse(n - 1)
    return
}

func reducedLatinSquare(n int, echo bool) uint64 {
    if n <= 0 {
        if echo {
            fmt.Println("[]\n")
        }
        return 0
    } else if n == 1 {
        if echo {
            fmt.Println("[1]\n")
        }
        return 1
    }
    rlatin := make(matrix, n)
    for i := 0; i < n; i++ {
        rlatin[i] = make([]int, n)
    }
    // first row
    for j := 0; j < n; j++ {
        rlatin[0][j] = j + 1
    }

    count := uint64(0)
    // recursive closure to compute reduced latin squares and count or print them
    var recurse func(i int)
    recurse = func(i int) {
        rows := dList(n, i) // get derangements of first n numbers, with 'i' first.
    outer:
        for r := 0; r < len(rows); r++ {
            copy(rlatin[i-1], rows[r])
            for k := 0; k < i-1; k++ {
                for j := 1; j < n; j++ {
                    if rlatin[k][j] == rlatin[i-1][j] {
                        if r < len(rows)-1 {
                            continue outer
                        } else if i > 2 {
                            return
                        }
                    }
                }
            }
            if i < n {
                recurse(i + 1)
            } else {
                count++
                if echo {
                    printSquare(rlatin, n)
                }
            }
        }
        return
    }

    // remaining rows
    recurse(2)
    return count
}

func printSquare(latin matrix, n int) {
    for i := 0; i < n; i++ {
        fmt.Println(latin[i])
    }
    fmt.Println()
}

func factorial(n uint64) uint64 {
    if n == 0 {
        return 1
    }
    prod := uint64(1)
    for i := uint64(2); i <= n; i++ {
        prod *= i
    }
    return prod
}

func main() {
    fmt.Println("The four reduced latin squares of order 4 are:\n")
    reducedLatinSquare(4, true)

    fmt.Println("The size of the set of reduced latin squares for the following orders")
    fmt.Println("and hence the total number of latin squares of these orders are:\n")
    for n := uint64(1); n <= 6; n++ {
        size := reducedLatinSquare(int(n), false)
        f := factorial(n - 1)
        f *= f * n * size
        fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f)
    }
}


PROC Test(INT max,angle,coeff)
  BYTE count,a,b,c

  PrintF("gamma=%B degrees:%E",angle)
  count=0
  FOR a=1 TO max
  DO
    FOR b=1 TO a
    DO
      FOR c=1 TO max
      DO
        IF a*a+b*b-coeff*a*b=c*c THEN
          PrintF("(%B,%B,%B) ",a,b,c)
          count==+1
        FI
      OD
    OD
  OD
  PrintF("%Enumber of triangles is %B%E%E",count)
RETURN

PROC Main()
  Test(13,90,0)
  Test(13,60,1)
  Test(13,120,-1)
RETURN


with Ada.Text_IO;
with Ada.Containers.Ordered_Maps;

procedure Law_Of_Cosines is

   type Angle_Kind is (Angle_60, Angle_90, Angle_120);

   function Is_Triangle (A, B, C : in Positive;
                         Angle   : in Angle_Kind) return Boolean
   is
      A2 : constant Positive := A**2;
      B2 : constant Positive := B**2;
      C2 : constant Positive := C**2;
      AB : constant Positive := A * B;
   begin
      case Angle is
         when Angle_60  =>  return A2 + B2 - AB = C2;
         when Angle_90  =>  return A2 + B2 = C2;
         when Angle_120 =>  return A2 + B2 + AB = C2;
      end case;
   end Is_Triangle;

   procedure Count_Triangles is
      use Ada.Text_IO;
      Count : Natural;
   begin
      for Angle in Angle_Kind loop
         Count := 0;
         Put_Line (Angle'Image & " triangles");
         for A in 1 ..13 loop
            for B in 1 .. A loop
               for C in 1 .. 13 loop
                  if Is_Triangle (A, B, C, Angle) then
                     Put_Line (A'Image & B'Image & C'Image);
                     Count := Count + 1;
                  end if;
               end loop;
            end loop;
         end loop;
         Put_Line ("There are " & Count'Image & " " & Angle'Image &" triangles");
      end loop;
   end Count_Triangles;

   procedure Extra_Credit (Limit : in Natural) is
      use Ada.Text_IO;

      package Square_Maps is new Ada.Containers.Ordered_Maps (Natural, Boolean);
      Squares : Square_Maps.Map;

      Count : Natural :=  0;
   begin
      for C in 1 .. Limit loop
         Squares.Insert (C**2, True);
      end loop;

      for A in 1 .. Limit loop
         for B in 1 .. A loop
            if Squares.Contains (A**2 + B**2 - A * B) then
               Count := Count + 1;
            end if;
         end loop;
      end loop;
      Put_Line ("There are " & Natural'(Count - Limit)'Image &
                  " " & Angle_60'Image &" triangles between 1 and " & Limit'Image & ".");
   end Extra_Credit;

begin
   Count_Triangles;
   Extra_Credit (Limit => 10_000);
end Law_Of_Cosines;


/*REXX program counts the occurrences of all characters in a file,  and note that all   */
/* Latin alphabet letters are uppercased for also counting {Latin} letters (both cases).*/
/*════════════════════════════════════~~~~~~~~~~════════════════════════════════════════*/
abc = 'abcdefghijklmnopqrstuvwxyz'               /*define an (Latin or English) alphabet*/
abcU= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'               /*define an uppercase version of  [↑]. */
parse arg fileID .                               /*this last char isn't a middle dot: · */
if fileID==''  then fileID= 'JUNK.TXT'           /*¿none specified? Then use the default*/
totChars= 0;           totLetters= 0             /*count of all chars and of all letters*/
pad= left('',18);      pad9= left('', 18%2)      /*used for the indentations of output. */
@.= 0                                            /*wouldn't it be neat to use Θ instead?*/
     do j=1  while lines(fileID)\==0             /*read the file 'til the cows come home*/
     rec= linein(fileID)                         /*get a line/record from the input file*/
                                                 /* [↓]  process all characters in  REC.*/
       do k=1  for length(rec)                   /*examine/count each of the characters.*/
       totChars= totChars + 1                    /*bump count of number of characters.  */
       c= substr(rec, k, 1);      @.c= @.c + 1   /*Peel off a character; bump its count.*/
       if \datatype(c, 'M')  then iterate        /*Not a Latin letter?   Get next char.⌠*/
       totLetters= totLetters + 1                /*bump the count for [Latin] letters. ⌡*/
       upper c                                   /* ◄─────◄ uppercase a Latin character.*/
       @..c= @..c + 1                            /*bump the  (Latin)  letter's count.   */
       end   /*k*/                               /*no Greek glyphs:  αßΓπΣσµτΦΘΩδφε ··· */
     end     /*j*/                               /*maybe we're ½ done by now, or mäÿbé ¬*/
                          LL= '(Latin) letter'   /*literal used for a  "SAY"  (below).  */
w= length(totChars)                              /*used for right─aligning the counts.  */
say 'file ─────'  fileId  "───── has"   j-1   'records and has'   totLetters LL"s.";   say
     do L=0  for 256;    c= d2c(L)               /*display all none─zero letter counts. */
     if @..c==0  then iterate                    /*Has a zero count? Then skip character*/
     say pad9  LL' '    c    " (also" translate(c,abc,abcU)')  count:'      right(@..c, w)
     end   /*L*/                                 /*we may be in a rut, but not a cañyon.*/
say                                              /*¡The old name for Eygpt was Æygpt!  _*/
say 'file ─────'    fileId     "───── has"     totChars     'characters.'          /* √ */
say                                              /*The name for « » chars is guillemets.*/
     do #=0  for 256;    y= d2c(#)               /*display all none─zero char counts.   */
     if @.y==0  then iterate                     /*¿Å zero count?  Then ignore character*/
     c= d2c(#);               ch= c              /*C  is the character glyph of a char. */
     if c<<' ' | #==255  then ch=                /*don't show some control characters.  */
     if c==' '           then ch= 'blank'        /*show a blank's  {true}  name.        */
     say pad right(ch, 5)         " ('"d2x(#,2)"'x  character count:"      right(@.c, w)
     end   /*#*/                                 /*255 isn't quite ∞, but sometimes ∙∙∙ */
say                                              /*not a good place for dithering: ░▒▓█ */
say  pad   pad9   '☼ end─of─list ☼'              /*show we are at the end of the list.  */
/*§§§§ Talk about a mishmash of 2¢ comments. ▬▬^▬▬ stick a fork in it, we're all done. ☻*/


lf: procedure (n) returns (fixed decimal (31) );
   declare n fixed binary;
   declare (s, f) fixed (31);
   declare (i, j) fixed;

   s = 0;
   do i = n-1 to 0 by -1;
      f = 1;
      do j = i to 1 by -1;
         f = f * j;
      end;
      s = s + f;
   end;
   return (s);
end lf;

   declare n fixed binary;

   do n = 0 to 10, 20 to 30;
      put skip list ('Left factorial of ' || n || '=' || lf(n) );
   end;

end left_factorials;


function left-factorial ([BigInt]$n) {
    [BigInt]$k, [BigInt]$fact = ([BigInt]::Zero), ([BigInt]::One)
    [BigInt]$lfact = ([BigInt]::Zero)
    while($k -lt $n){
        if($k -gt ([BigInt]::Zero)) {
            $fact = [BigInt]::Multiply($fact, $k)
            $lfact = [BigInt]::Add($lfact, $fact)
        } else {
            $lfact = ([BigInt]::One)
        }
        $k = [BigInt]::Add($k, [BigInt]::One)
    }
    $lfact
}
0..9 | foreach{
    "!$_ = $(left-factorial $_)"
}
for($i = 10; $i -le 110; $i += 10) {
    "!$i = $(left-factorial $i)"
}
for($i = 1000; $i -le 10000; $i += 1000) {
    $digits = [BigInt]::Log10($(left-factorial $i))
    $digits = [Math]::Floor($digits) + 1
    if($digits -gt 1) {"!$i has $digits digits"}
    else {"!$i has $digits digit"}
}


import Data.List (permutations, (\\))
import Control.Monad (foldM, forM_)

latinSquares :: Eq a => [a] -> [[[a]]]
latinSquares [] = []
latinSquares set = map reverse <$> squares
  where
    squares = foldM addRow firstRow perm
    perm = tail (groupedPermutations set)
    firstRow = pure <$> set
    addRow tbl rows = [ zipWith (:) row tbl
                      | row <- rows
                      , and $ different (tail row) (tail tbl) ]
    different = zipWith $ (not .) . elem

groupedPermutations :: Eq a => [a] -> [[[a]]]
groupedPermutations lst = map (\x -> (x :) <$> permutations (lst \\ [x])) lst

printTable :: Show a => [[a]] -> IO ()
printTable tbl = putStrLn $ unlines $ unwords . map show <$> tbl


import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LatinSquaresInReducedForm {

    public static void main(String[] args) {
        System.out.printf("Reduced latin squares of order 4:%n");
        for ( LatinSquare square : getReducedLatinSquares(4) ) {
            System.out.printf("%s%n", square);
        }

        System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n");
        for ( int n = 1 ; n <= 6 ; n++ ) {
            List<LatinSquare> list = getReducedLatinSquares(n);
            System.out.printf("Size = %d, %d * %d * %d = %,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));
        }
    }

    private static long fact(int n) {
        if ( n == 0 ) {
            return 1;
        }
        int prod = 1;
        for ( int i = 1 ; i <= n ; i++ ) {
            prod *= i;
        }
        return prod;
    }

    private static List<LatinSquare> getReducedLatinSquares(int n) {
        List<LatinSquare> squares = new ArrayList<>();

        squares.add(new LatinSquare(n));
        PermutationGenerator permGen = new PermutationGenerator(n);
        for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {
            List<LatinSquare> squaresNext = new ArrayList<>();
            for ( LatinSquare square : squares ) {
                while ( permGen.hasMore() ) {
                    int[] perm = permGen.getNext();

                    //  If not the correct row - next permutation.
                    if ( (perm[0]+1) != (fillRow+1) ) {
                        continue;
                    }

                    //  Check permutation against current square.
                    boolean permOk = true;
                    done:
                    for ( int row = 0 ; row < fillRow ; row++ ) {
                        for ( int col = 0 ; col < n ; col++ ) {
                            if ( square.get(row, col) == (perm[col]+1) ) {
                                permOk = false;
                                break done;
                            }
                        }
                    }
                    if ( permOk ) {
                        LatinSquare newSquare = new LatinSquare(square);
                        for ( int col = 0 ; col < n ; col++ ) {
                            newSquare.set(fillRow, col, perm[col]+1);
                        }
                        squaresNext.add(newSquare);
                    }
                }
                permGen.reset();
            }
            squares = squaresNext;
        }

        return squares;
    }

    @SuppressWarnings("unused")
    private static int[] display(int[] in) {
        int [] out = new int[in.length];
        for ( int i = 0 ; i < in.length ; i++ ) {
            out[i] = in[i] + 1;
        }
        return out;
    }

    private static class LatinSquare {

        int[][] square;
        int size;

        public LatinSquare(int n) {
            square = new int[n][n];
            size = n;
            for ( int col = 0 ; col < n ; col++ ) {
                set(0, col, col + 1);
            }
        }

        public LatinSquare(LatinSquare ls) {
            int n = ls.size;
            square = new int[n][n];
            size = n;
            for ( int row = 0 ; row < n ; row++ ) {
                for ( int col = 0 ; col < n ; col++ ) {
                    set(row, col, ls.get(row, col));
                }
            }
        }

        public void set(int row, int col, int value) {
            square[row][col] = value;
        }

        public int get(int row, int col) {
            return square[row][col];
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            for ( int row = 0 ; row < size ; row++ ) {
                sb.append(Arrays.toString(square[row]));
                sb.append("\n");
            }
            return sb.toString();
        }

    }

    private static class PermutationGenerator {

        private int[] a;
        private BigInteger numLeft;
        private BigInteger total;

        public PermutationGenerator (int n) {
            if (n < 1) {
                throw new IllegalArgumentException ("Min 1");
            }
            a = new int[n];
            total = getFactorial(n);
            reset();
        }

        private void reset () {
            for ( int i = 0 ; i < a.length ; i++ ) {
                a[i] = i;
            }
            numLeft = new BigInteger(total.toString());
        }

        public boolean hasMore() {
            return numLeft.compareTo(BigInteger.ZERO) == 1;
        }

        private static BigInteger getFactorial (int n) {
            BigInteger fact = BigInteger.ONE;
            for ( int i = n ; i > 1 ; i-- ) {
                fact = fact.multiply(new BigInteger(Integer.toString(i)));
            }
            return fact;
        }

        /*--------------------------------------------------------
         * Generate next permutation (algorithm from Rosen p. 284)
         *--------------------------------------------------------
         */
        public int[] getNext() {
            if ( numLeft.equals(total) ) {
                numLeft = numLeft.subtract (BigInteger.ONE);
                return a;
            }

            // Find largest index j with a[j] < a[j+1]
            int j = a.length - 2;
            while ( a[j] > a[j+1] ) {
                j--;
            }

            // Find index k such that a[k] is smallest integer greater than a[j] to the right of a[j]
            int k = a.length - 1;
            while ( a[j] > a[k] ) {
                k--;
            }

            // Interchange a[j] and a[k]
            int temp = a[k];
            a[k] = a[j];
            a[j] = temp;

            // Put tail end of permutation after jth position in increasing order
            int r = a.length - 1;
            int s = j + 1;
            while (r > s) {
                int temp2 = a[s];
                a[s] = a[r];
                a[r] = temp2;
                r--;
                s++;
            }

            numLeft = numLeft.subtract(BigInteger.ONE);
            return a;
        }
    }

}


BEGIN
    # find all integer sided 90, 60 and 120 degree triangles by finding integer solutions for #
    #    a^2 + b^2 = c^2, a^2 + b^2 - ab = c^2, a^2 + b^2 + ab = c^2 where a, b, c in 1 .. 13 #
    INT max side   = 13;                  # max triangle side to consider                     #
    INT max square = max side * max side; # max triangle side squared to consider             #
    [ 1 : max square ]INT root;           # table of square roots                             #
    FOR s TO UPB root DO root[ s     ] := 0 OD;
    FOR s TO max side DO root[ s * s ] := s OD;
    INT tcount := 0;
    [ 1 : max square ]INT ta, tb, tc, tangle;
    # prints solutions for the specified angle                                                #
    PROC print triangles = ( INT angle )VOID:
    BEGIN
        INT scount := 0;
        FOR t TO tcount DO IF tangle[ t ] = angle THEN scount +:= 1 FI OD;
        print( ( whole( scount, -4 ), " ", whole( angle, -3 ), " degree triangles:", newline ) );
        FOR t TO tcount DO
            IF tangle[ t ] = angle THEN
                print( ( "    ", whole( ta[ t ], -3 ), whole( tb[ t ], -3 ), whole( tc[ t ], -3 ), newline ) )
            FI
        OD
    END # print triangles # ;
    # stores the triangle with sides a, b, root[ c2 ] and the specified angle,                #
    # if it is a solution                                                                     #
    PROC try triangle = ( INT a, b, c2, angle )VOID:
        IF  c2 <= max square THEN
            # the third side is small enough                                                  #
            INT c = root[ c2 ];
            IF  c /= 0 THEN
                # the third side is the square of an integer                                  #
                tcount +:= 1;
                ta[     tcount ] := a; tb[ tcount ] := b; tc[ tcount ] := root[ c2 ];
                tangle[ tcount ] := angle
            FI
        FI # try triangle # ;
    # find all triangles                                                                      #
    FOR a TO max side DO
        FOR b FROM a TO max side DO
            try triangle( a, b, ( a * a ) + ( b * b ) - ( a * b ),  60 );
            try triangle( a, b, ( a * a ) + ( b * b ),              90 );
            try triangle( a, b, ( a * a ) + ( b * b ) + ( a * b ), 120 )
        OD
    OD;
    # print the solutions                                                                     #
    print triangles(  60 );
    print triangles(  90 );
    print triangles( 120 )
END


textData = read("C:\Ring\ReadMe.txt")
ln =len(textData)
charCount = list(255)
totCount = 0

for i =1 to ln
    char = ascii(substr(textData,i,1))
    charCount[char] = charCount[char] + 1
    if char > 31 totCount = totCount + 1 ok
next

for i = 32 to 255
    if charCount[i] > 0 see char(i) + " = " + charCount[i] + " " + (charCount[i]/totCount)*100 + " %" + nl ok
next


def letter_frequency(file)
  letters = 'a' .. 'z'
  File.read(file) .
       split(//) .
       group_by {|letter| letter.downcase} .
       select   {|key, val| letters.include? key} .
       collect  {|key, val| [key, val.length]}
end

letter_frequency(ARGV[0]).sort_by {|key, val| -val}.each {|pair| p pair}


leftfact(N):-
    leftfact(N, 0, 0, 1).

leftfact(N, N, _, _):-
    !.
leftfact(N, M, L, F):-
    ((M =< 10 ; (M =< 110, 0 is M mod 10)) ->
        writef("!%w = %w\n", [M, L])
        ;
        (0 is M mod 1000 ->
            number_string(L, S),
            string_length(S, Len),
            writef("length of !%w is %w\n", [M, Len])
            ;
            true)),
    L1 is L + F,
    M1 is M + 1,
    F1 is F * M1,
    leftfact(N, M1, L1, F1).

main:-
    leftfact(10001).


from itertools import islice

def lfact():
    yield 0
    fact, summ, n = 1, 0, 1
    while 1:
        fact, summ, n = fact*n, summ + fact, n + 1
        yield summ

print('first 11:\n  %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10):
    print(lf)
print('Digits in 1,000 through 10,000 (inclusive) by thousands:\n  %r'
      % [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] )


def count(s): reduce s as $x (0; .+1);

def factorial: reduce range(2;.+1) as $i (1; . * $i);

def permutations:
  if length == 0 then []
  else
    range(0;length) as $i
    | [.[$i]] + (del(.[$i])|permutations)
  end ;


using Combinatorics

clash(row2, row1::Vector{Int}) = any(i -> row1[i] == row2[i], 1:length(row2))

clash(row, rows::Vector{Vector{Int}}) = any(r -> clash(row, r), rows)

permute_onefixed(i, n) = map(vec -> vcat(i, vec), permutations(filter(x -> x != i, 1:n)))

filter_permuted(rows, i, n) = filter(v -> !clash(v, rows), permute_onefixed(i, n))

function makereducedlatinsquares(n)
    matarray = [reshape(collect(1:n), 1, n)]
    for i in 2:n
        newmatarray = Vector{Matrix{Int}}()
        for mat in matarray
            r = size(mat)[1] + 1
            newrows = filter_permuted(collect(row[:] for row in eachrow(mat)), r, n)
            newmat = zeros(Int, r, n)
            newmat[1:r-1, :] .= mat
            append!(newmatarray,
                [deepcopy(begin newmat[i, :] .= row; newmat end) for row in newrows])
        end
        matarray = newmatarray
    end
    matarray, length(matarray)
end

function testlatinsquares()
    squares, count = makereducedlatinsquares(4)
    println("The four reduced latin squares of order 4 are:")
    for sq in squares, (i, row) in enumerate(eachrow(sq)), j in 1:4
        print(row[j], j == 4 ? (i == 4 ? "\n\n" : "\n") : " ")
    end
    for i in 1:6
        squares, count = makereducedlatinsquares(i)
        println("Order $i: Size ", rpad(count, 5), "* $(i)! * $(i - 1)! = ",
            count * factorial(i) * factorial(i - 1))
    end
end

testlatinsquares()


typealias Matrix = MutableList<MutableList<Int>>

fun dList(n: Int, sp: Int): Matrix {
    val start = sp - 1 // use 0 basing

    val a = generateSequence(0) { it + 1 }.take(n).toMutableList()
    a[start] = a[0].also { a[0] = a[start] }
    a.subList(1, a.size).sort()

    val first = a[1]
    // recursive closure permutes a[1:]
    val r = mutableListOf<MutableList<Int>>()
    fun recurse(last: Int) {
        if (last == first) {
            // bottom of recursion. you get here once for each permutation.
            // test if permutation is deranged
            for (jv in a.subList(1, a.size).withIndex()) {
                if (jv.index + 1 == jv.value) {
                    return  // no, ignore it
                }
            }
            // yes, save a copy with 1 based indexing
            val b = a.map { it + 1 }
            r.add(b.toMutableList())
            return
        }
        for (i in last.downTo(1)) {
            a[i] = a[last].also { a[last] = a[i] }
            recurse(last - 1)
            a[i] = a[last].also { a[last] = a[i] }
        }
    }
    recurse(n - 1)
    return r
}

fun reducedLatinSquares(n: Int, echo: Boolean): Long {
    if (n <= 0) {
        if (echo) {
            println("[]\n")
        }
        return 0
    } else if (n == 1) {
        if (echo) {
            println("[1]\n")
        }
        return 1
    }

    val rlatin = MutableList(n) { MutableList(n) { it } }
    // first row
    for (j in 0 until n) {
        rlatin[0][j] = j + 1
    }

    var count = 0L
    fun recurse(i: Int) {
        val rows = dList(n, i)

        outer@
        for (r in 0 until rows.size) {
            rlatin[i - 1] = rows[r].toMutableList()
            for (k in 0 until i - 1) {
                for (j in 1 until n) {
                    if (rlatin[k][j] == rlatin[i - 1][j]) {
                        if (r < rows.size - 1) {
                            continue@outer
                        }
                        if (i > 2) {
                            return
                        }
                    }
                }
            }
            if (i < n) {
                recurse(i + 1)
            } else {
                count++
                if (echo) {
                    printSquare(rlatin)
                }
            }
        }
    }

    // remaining rows
    recurse(2)
    return count
}

fun printSquare(latin: Matrix) {
    for (row in latin) {
        println(row)
    }
    println()
}

fun factorial(n: Long): Long {
    if (n == 0L) {
        return 1
    }
    var prod = 1L
    for (i in 2..n) {
        prod *= i
    }
    return prod
}

fun main() {
    println("The four reduced latin squares of order 4 are:\n")
    reducedLatinSquares(4, true)

    println("The size of the set of reduced latin squares for the following orders")
    println("and hence the total number of latin squares of these orders are:\n")
    for (n in 1 until 7) {
        val size = reducedLatinSquares(n, false)
        var f = factorial(n - 1.toLong())
        f *= f * n * size
        println("Order $n: Size %-4d x $n! x ${n - 1}! => Total $f".format(size))
    }
}


# syntax: GAWK -f LAW_OF_COSINES_-_TRIPLES.AWK
# converted from C
BEGIN {
    description[1] = "90 degrees, a*a + b*b = c*c"
    description[2] = "60 degrees, a*a + b*b - a*b = c*c"
    description[3] = "120 degrees, a*a + b*b + a*b = c*c"
    split("0,1,-1",coeff,",")
    main(13,1,0)
    main(1000,0,1) # 10,000 takes too long
    exit(0)
}
function main(max_side_length,show_sides,no_dups,  a,b,c,count,k) {
    printf("\nmaximum side length: %d\n",max_side_length)
    for (k=1; k<=3; k++) {
      count = 0
      for (a=1; a<=max_side_length; a++) {
        for (b=1; b<=a; b++) {
          for (c=1; c<=max_side_length; c++) {
            if (a*a + b*b - coeff[k] * a*b == c*c) {
              if (no_dups && (a == b || b == c)) {
                continue
              }
              count++
              if (show_sides) {
                printf("  %d %d %d\n",a,b,c)
              }
            }
          }
        }
      }
      printf("%d triangles, %s\n",count,description[k])
    }
}


/*
 * RossetaCode: Law of cosines - triples
 *
 * An quick and dirty brute force solutions with O(N^3) cost.
 * Anyway it is possible set MAX_SIDE_LENGTH equal to 10000
 * and use fast computer to obtain the "extra credit" badge.
 *
 * Obviously, there are better algorithms.
 */

#include <stdio.h>
#include <math.h>

#define MAX_SIDE_LENGTH 13
//#define DISPLAY_TRIANGLES 1

int main(void)
{
    static char description[3][80] = {
        "gamma =  90 degrees,  a*a + b*b       == c*c",
        "gamma =  60 degrees,  a*a + b*b - a*b == c*c",
        "gamma = 120 degrees,  a*a + b*b + a*b == c*c"
    };
    static int coeff[3] = { 0, 1, -1 };

    for (int k = 0; k < 3; k++)
    {
        int counter = 0;
        for (int a = 1; a <= MAX_SIDE_LENGTH; a++)
            for (int b = 1; b <= a; b++)
                for (int c = 1; c <= MAX_SIDE_LENGTH; c++)
                    if (a * a + b * b - coeff[k] * a * b == c * c)
                    {
                        counter++;
#ifdef DISPLAY_TRIANGLES
                        printf("  %d  %d  %d\n", a, b, c);
#endif
                    }
        printf("%s,  number of triangles = %d\n", description[k], counter);
    }

    return 0;
}


open "c:\rbp101\public\textFile.txt" for input as #f
textData$ = input$(#f, lof( #f))
ln =len(textData$)
close #f

dim charCount( 255)

for i =1 to ln
   char            = asc(mid$(textData$,i,1))
   charCount(char) = charCount(char) + 1
   if char > 31 then totCount = totCount + 1
next i

for i = 32 to 255
if charCount(i) > 0 then print "Ascii:";using("###",i);" char:";chr$(i);" Count:";using("#######",charCount(i));" ";using("##.#",(charCount(i) / totCount) * 100);"%"
next i


use std::collections::btree_map::BTreeMap;
use std::{env, process};
use std::io::{self, Read, Write};
use std::fmt::Display;
use std::fs::File;

fn main() {
    let filename = env::args().nth(1)
        .ok_or("Please supply a file name")
        .unwrap_or_else(|e| exit_err(e, 1));

    let mut buf = String::new();
    let mut count = BTreeMap::new();

    File::open(&filename)
        .unwrap_or_else(|e| exit_err(e, 2))
        .read_to_string(&mut buf)
        .unwrap_or_else(|e| exit_err(e, 3));

    for c in buf.chars() {
        *count.entry(c).or_insert(0) += 1;
    }

    println!("Number of occurences per character");
    for (ch, count) in &count {
        println!("{:?}: {}", ch, count);
    }
}

#[inline]
fn exit_err<T>(msg: T, code: i32) -> ! where T: Display {
    writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr");
    process::exit(code)
}


  [ 1 swap times [ i 1+ * ] ] is !  ( n --> n )

  [ 0 swap times  [ i ! + ] ] is !n ( n --> n )

  say "First 11 left factorials:" cr
  11 times [ i^ !n echo sp ] cr
  cr
  say "20 through 110 (inclusive) by tens:" cr
  10 times [ i^ 2 + 10 * !n echo cr ]
  cr
  say "Digits in 1,000 through 10,000 by thousands:" cr
  10 times [ i^ 1+ 1000 * !n number$ size echo cr ]
  cr


library(gmp)

left_factorial <- function(n) {
	if (n == 0) return(0)
	result <- as.bigz(0)

	adder <- as.bigz(1)
	for (k in 1:n) {
		result <- result + adder
		adder <- adder * k
	}
	result
}

digit_count <- function(n) {
	nchar(as.character(n))
}

for (n in 0:10) {
	cat("!",n," = ",sep = "")
	cat(as.character(left_factorial(n)))
	cat("\n")
}
for (n in seq(20,110,10)) {
	cat("!",n," = ",sep = "")
	cat(as.character(left_factorial(n)))
	cat("\n")
}
for (n in seq(1000,10000,1000)) {
  cat("!",n," has ",digit_count(left_factorial(n))," digits\n", sep = "")
}


#lang racket
(define ! (let ((rv# (make-hash))) (λ (n) (hash-ref! rv# n (λ () (if (= n 0) 1 (* n (! (- n 1)))))))))

(define (!n n)
  ;; note that in-range n is from 0 to n-1 inclusive
  (for/sum ((k (in-range n))) (! k)))

(define (dnl. s) (for-each displayln s))
(dnl
  "Display the left factorials for:"
  "zero through ten (inclusive)"
  (pretty-format (for/list ((i (in-range 0 (add1 10)))) (!n i)))
  "20 through 110 (inclusive) by tens"
  (pretty-format (for/list ((i (in-range 20 (add1 110) 10))) (!n i)))
  "Display the length (in decimal digits) of the left factorials for:"
  "1,000, 2,000 through 10,000 (inclusive), by thousands."
  (pretty-format (for/list ((i (in-range 1000 10001 1000))) (add1 (order-of-magnitude (!n i))))))


%Latin Squares in Reduced Form. Nigel Galloway, September 5th., 2019
include "alldifferent.mzn";
int: N;
array[1..N,1..N] of var 1..N: p; constraint forall(n in 1..N)(p[1,n]=n /\ p[n,1]=n);
constraint forall(n in 1..N)(alldifferent([p[n,g]|g in 1..N])/\alldifferent([p[g,n]|g in 1..N]));


import algorithm, math, sequtils, strformat

type

  # Row managed as a sequence of ints with base index 1.
  Row = object
    value: seq[int]

  # Matrix managed as a sequence of rows with base index 1.
  Matrix = object
    value: seq[Row]

func newRow(n: Natural = 0): Row =
  ## Create a new row of length "n".
  Row(value: newSeq[int](n))

# Create a new matrix of length "n" containing rows of length "p".
func newMatrix(n, p: Natural = 0): Matrix = Matrix(value: newSeqWith(n, newRow(p)))

# Functions for rows.
func `[]`(r: var Row; i: int): var int = r.value[i - 1]
func `[]=`(r: var Row; i, n: int) = r.value[i - 1] = n
func sort(r: var Row; low, high: Positive) =
  r.value.toOpenArray(low - 1, high - 1).sort()
func `$`(r: Row): string = ($r.value)[1..^1]

# Functions for matrices.
func `[]`(m: Matrix; i: int): Row = m.value[i - 1]
func `[]`(m: var Matrix; i: int): var Row = m.value[i - 1]
func `[]=`(m: var Matrix; i: int; r: Row) = m.value[i - 1] = r
func high(m: Matrix): Natural = m.value.len
func add(m: var Matrix; r: Row) = m.value.add r
func `$`(m: Matrix): string =
  for row in m.value: result.add $row & '\n'

func dList(n, start: Positive): Matrix =
  ## Generate derangements of first 'n' numbers, with 'start' in first place.

  var a = Row(value: toSeq(1..n))

  swap a[1], a[start]
  a.sort(2, n)
  let first = a[2]
  var r: Matrix

  func recurse(last: int) =
    ## Recursive closure permutes a[2..^1].
    if last == first:
      # Bottom of recursion. You get here once for each permutation.
      # Test if permutation is deranged.
      for i in 2..n:
        if a[i] == i: return  # No: ignore it.
      r.add a
      return
    for i in countdown(last, 2):
      swap a[i], a[last]
      recurse(last - 1)
      swap a[i], a[last]

  recurse(n)
  result = r

proc reducedLatinSquares(n: Positive; print: bool): int =

  if n == 1:
    if print: echo [1]
    return 1

  var rlatin = newMatrix(n, n)
  # Initialize first row.
  for i in 1..n: rlatin[1][i] = i

  var count = 0

  proc recurse(i: int) =
    let rows = dList(n, i)
    for r in 1..rows.high:
      block inner:
        rlatin[i] = rows[r]
        for k in 1..<i:
          for j in 2..n:
            if rlatin[k][j] == rlatin[i][j]:
              if r < rows.high: break inner
              if i > 2: return
        if i < n:
          recurse(i + 1)
        else:
          inc count
          if print: echo rlatin

  # Remaining rows.
  recurse(2)
  result = count

when isMainModule:

  echo "The four reduced latin squares of order 4 are:"
  discard reducedLatinSquares(4, true)

  echo "The size of the set of reduced latin squares for the following orders"
  echo "and hence the total number of latin squares of these orders are:"
  for n in 1..6:
    let size = reducedLatinSquares(n, false)
    let f = fac(n - 1)^2 * n * size
    echo &"Order {n}: Size {size:<4} x {n}! x {n - 1}! => Total {f}"


#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Latin_Squares_in_reduced_form
use warnings;

my $n = 0;
my $count;
our @perms;

while( ++$n <= 7 )
  {
  $count = 0;
  @perms = perm( my $start = join '', 1 .. $n );
  find( $start );
  print "order $n size $count total @{[$count * fact($n) * fact($n-1)]}\n\n";
  }

sub find
  {
  @_ >= $n and return $count += ($n != 4) || print join "\n", @_, "\n";
  local @perms = grep 0 == ($_[-1] ^ $_) =~ tr/\0//, @perms;
  my $row = @_ + 1;
  find( @_, $_ ) for grep /^$row/, @perms;
  }

sub fact { $_[0] > 1 ? $_[0] * fact($_[0] - 1) : 1 }

sub perm
  {
  my $s = shift;
  length $s <= 1 ? $s :
    map { my $f = $_; map "$f$_", perm( $s =~ s/$_//r ) } split //, $s;
  }


#include <cmath>
#include <iostream>
#include <tuple>
#include <vector>

using triple = std::tuple<int, int, int>;

void print_triple(std::ostream& out, const triple& t) {
    out << '(' << std::get<0>(t) << ',' << std::get<1>(t) << ',' << std::get<2>(t) << ')';
}

void print_vector(std::ostream& out, const std::vector<triple>& vec) {
    if (vec.empty())
        return;
    auto i = vec.begin();
    print_triple(out, *i++);
    for (; i != vec.end(); ++i) {
        out << ' ';
        print_triple(out, *i);
    }
    out << "\n\n";
}

int isqrt(int n) {
    return static_cast<int>(std::sqrt(n));
}

int main() {
    const int min = 1, max = 13;
    std::vector<triple> solutions90, solutions60, solutions120;

    for (int a = min; a <= max; ++a) {
        int a2 = a * a;
        for (int b = a; b <= max; ++b) {
            int b2 = b * b, ab = a * b;
            int c2 = a2 + b2;
            int c = isqrt(c2);
            if (c <= max && c * c == c2)
                solutions90.emplace_back(a, b, c);
            else {
                c2 = a2 + b2 - ab;
                c = isqrt(c2);
                if (c <= max && c * c == c2)
                    solutions60.emplace_back(a, b, c);
                else {
                    c2 = a2 + b2 + ab;
                    c = isqrt(c2);
                    if (c <= max && c * c == c2)
                        solutions120.emplace_back(a, b, c);
                }
            }
        }
    }

    std::cout << "There are " << solutions60.size() << " solutions for gamma = 60 degrees:\n";
    print_vector(std::cout, solutions60);

    std::cout << "There are " << solutions90.size() << " solutions for gamma = 90 degrees:\n";
    print_vector(std::cout, solutions90);

    std::cout << "There are " << solutions120.size() << " solutions for gamma = 120 degrees:\n";
    print_vector(std::cout, solutions120);

    const int max2 = 10000;
    int count = 0;
    for (int a = min; a <= max2; ++a) {
        for (int b = a + 1; b <= max2; ++b) {
            int c2 = a * a + b * b - a * b;
            int c = isqrt(c2);
            if (c <= max2 && c * c == c2)
                ++count;
        }
    }
    std::cout << "There are " << count << " solutions for gamma = 60 degrees in the range "
        << min << " to " << max2 << " where the sides are not all of the same length.\n";
    return 0;
}


$constant EOF = 1AH       rem  normal end-of-file marker

rem  Convert character to upper case
function upcase(ch = char) = char
   if ch >= 'a' and ch <= 'z' then
       ch = ch - 32
end = ch

rem  Convert string to all upper case characters
function allcaps(source = string) = string
   var p = integer
   for p = 1 to len(source) do
       mid(source,p,1) = upcase(mid(source,p,1))
   next p
end = source

comment
  Preserve console and printer channels (#0 and #1)
  Channel #2 declared as sequential ASCII
end
files d, d, sa(1)

var ch = char
var i = integer
based errcode = integer
base errcode at 103H       rem  S-BASIC stores run-time error code here
var filename = string
var total = real
dim real freq(26)

input "Name of text file to process: "; filename
filename = allcaps(filename)
open #2; filename
on error goto 7_trap    rem  In case input file lacks terminating ^Z

rem  Initialize letter counts to zero
for i = 1 to 26
  freq(i) = 0
next i

rem  Process the file
total = 0
input3 #2; ch
while ch <> EOF do
    begin
        ch = upcase(ch);
        if ch >= "A" and ch <= "Z" then
            begin
                freq(ch - 64) = freq(ch - 64) + 1
                total = total + 1
            end
        input3 #2; ch
    end

goto 8_done      rem  Jump around error trap

7_trap	if errcode <> 15 then
	    begin
	        print "Runtime error = ";errcode
		goto 9_exit
	    end
	rem  otherwise fall through on attempted read past EOF (err = 15)
8_done
	close #2

rem  Report results
print "Letter   Count   Percent"
for I = 1 to 26
    print chr(i+64);"      ";
    print using " ##,###"; freq(i);
    print using "    ##.#"; freq(i) / total * 100
next i

9_exit
end


import io.Source.fromFile

def letterFrequencies(filename: String) =
  fromFile(filename).mkString groupBy (c => c) mapValues (_.length)


/*REXX program computes/display the left factorial (or its dec. width) of N (or a range)*/
parse arg bot top inc .                          /*obtain optional arguments from the CL*/
if bot=='' | bot==","  then bot=   1             /*Not specified:  Then use the default.*/
if top=='' | top==","  then top= bot             /* "      "         "   "   "     "    */
if inc=''  | inc==","  then inc=   1             /* "      "         "   "   "     "    */
tell=  bot<0                                     /*if BOT < 0,   only show # of digits. */
bot= abs(bot)                                    /*use the  │bot│  for the   DO   loop. */
w= length(top)                                   /*width of the largest number request. */
              do j=bot  to top  by inc           /*traipse through the numbers requested*/
              if tell  then say 'left ! of '  right(j,w) " ───► " length(L!(j))  ' digits'
                       else say 'left ! of '  right(j,w) " ───► "        L!(j)
              end   /*j*/                        /* [↑]  show either  L!  or # of digits*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
L!: procedure; parse arg x .;  if x<3  then return x;   $= 4;  != 2    /*some shortcuts.*/
             do #=3  to x-1;   != ! * #          /*compute  L!  for all numbers ─── ► X.*/
             if pos(., !)\==0  then numeric digits digits() * 3 % 2    /*bump dec. digs.*/
             $= $ + !                            /*add the factorial ───►  L!  sum.     */
             end   /*#*/                         /* [↑]  handles gihugeic numbers.      */
    return $                                     /*return the sum  (L!)  to the invoker.*/


string aleph = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

function rfls(integer n, bool count_only=true)
    if n>length(aleph) then ?9/0 end if -- too big...
    if n=1 then return iff(count_only?1:{{1}}) end if
    sequence tn = tagset(n),     -- {1..n}
             vcs = repeat(tn,n), -- valid for cols
             vrs = repeat(tn,n), -- valid for rows
             res = repeat(tn,n)  -- (main workspace/one element of result)
    object result = iff(count_only?0:{})
    vcs[1] = {}     -- (not strictly necessary)
    vrs[1] = {}     --          """
    for i=2 to n do
        res[i] = i & repeat(0,n-1)
        vrs[i][i] = 0
        vcs[i][i] = 0
    end for
    integer r = 2, c = 2
    while true do
        -- place with backtrack:
        -- if we successfully place [n,n] add to results and backtrack
        -- terminate when we fail to place or backtrack from [2,2]
        integer rrc = res[r,c]
        if rrc!=0 then  -- backtrack (/undo)
            if vrs[r][rrc]!=0 then ?9/0 end if  -- sanity check
            if vcs[c][rrc]!=0 then ?9/0 end if  --      ""
            res[r,c] = 0
            vrs[r][rrc] = rrc
            vcs[c][rrc] = rrc
        end if
        bool found = false
        for i=rrc+1 to n do
            if vrs[r][i] and vcs[c][i] then
                res[r,c] = i
                vrs[r][i] = 0
                vcs[c][i] = 0
                found = true
                exit
            end if
        end for
        if found then
            if r=n and c=n then
                if count_only then
                    result += 1
                else
                    result = append(result,res)
                end if
                -- (here, backtracking == not advancing)
            elsif c=n then
                c = 2
                r += 1
            else
                c += 1
            end if
        else
            -- backtrack
            if r=2 and c=2 then exit end if
            c -= 1
            if c=1 then
                r -= 1
                c = n
            end if
        end if
    end while
    return result
end function

procedure reduced_form_latin_squares(integer n)
    sequence res = rfls(n,false)
    for k=1 to length(res) do
        for i=1 to n do
            string line = ""
            for j=1 to n do
                line &= aleph[res[k][i][j]]
            end for
            res[k][i] = line
        end for
        res[k] = join(res[k],"\n")
    end for
    string r = join(res,"\n\n")
    printf(1,"There are %d reduced form latin squares of order %d:\n%s\n",{length(res),n,r})
end procedure

reduced_form_latin_squares(4)
puts(1,"\n")
for n=1 to 6 do
    integer size = rfls(n)
    atom f = factorial(n)*factorial(n-1)*size
    printf(1,"Order %d: Size %-4d x %d! x %d! => Total %d\n", {n, size, n, n-1, f})
end for


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

public static class LawOfCosinesTriples
{
    public static void Main2() {
        PrintTriples(60, 13);
        PrintTriples(90, 13);
        PrintTriples(120, 13);
        PrintTriples(60, 10_000, true, false);
    }

    private static void PrintTriples(int degrees, int maxSideLength, bool notAllTheSameLength = false, bool print = true) {
        string s = $"{degrees} degree triangles in range 1..{maxSideLength}";
        if (notAllTheSameLength) s += " where not all sides are the same";
        Console.WriteLine(s);
        int count = 0;
        var triples = FindTriples(degrees, maxSideLength);
        if (notAllTheSameLength) triples = triples.Where(NotAllTheSameLength);
        foreach (var triple in triples) {
            count++;
            if (print) Console.WriteLine(triple);
        }
        Console.WriteLine($"{count} solutions");
    }

    private static IEnumerable<(int a, int b, int c)> FindTriples(int degrees, int maxSideLength) {
        double radians = degrees * Math.PI / 180;
        int coefficient = (int)Math.Round(Math.Cos(radians) * -2, MidpointRounding.AwayFromZero);
        int maxSideLengthSquared = maxSideLength * maxSideLength;
        return
            from a in Range(1, maxSideLength)
            from b in Range(1, a)
            let cc = a * a + b * b + a * b * coefficient
            where cc <= maxSideLengthSquared
            let c = (int)Math.Sqrt(cc)
            where c * c == cc
            select (a, b, c);
    }

    private static bool NotAllTheSameLength((int a, int b, int c) triple) => triple.a != triple.b || triple.a != triple.c;
}


USING: backtrack formatting kernel locals math math.ranges
sequences sets sorting ;
IN: rosetta-code.law-of-cosines

:: triples ( quot -- seq )
    [
        V{ } clone :> seen
        13 [1,b] dup dup [ amb-lazy ] [email protected] :> ( a b c )
        a sq b sq + a b quot call( x x x -- x ) c sq =
        { b a c } seen member? not and
        must-be-true { a b c } dup seen push
    ] bag-of ;

: show-solutions ( quot angle -- )
    [ triples { } like dup length ] dip rot
    "%d solutions for %d degrees:\n%u\n\n" printf ;

[ * + ] 120
[ 2drop 0 - ] 90
[ * - ] 60 [ show-solutions ] [email protected]


(use-modules (ice-9 format))

(define (char-freq port table)
  (if
   (eof-object? (peek-char port))
   table
   (char-freq port (add-char (read-char port) table))))

(define (add-char char table)
  (cond
   ((null? table) (list (list char 1)))
   ((eq? (caar table) char) (cons (list char (+ (cadar table) 1)) (cdr table)))
   (#t (cons (car table) (add-char char (cdr table))))))

(define (format-table table)
  (for-each (lambda (t) (format #t "~10s~10d~%" (car t) (cadr t))) table))

(define (print-freq filename)
  (format-table (char-freq (open-input-file filename) '())))

(print-freq "letter-frequency.scm")


a = leftFact(0,10,1)
see "" + a + nl

func leftFact f,t,s
     see "------ From " + f + " --To -> " + t +" Step " + s + " -------" + nl
     for i = f to t step s
         leftFact = 1
         fct = 1
         for j = 1 to i - 1
             fct = fct * j
             leftFact = leftFact + fct
         next
         if i >= 1000 see "" + i + " " + len(string(leftFact)) + " digits" + nl
         else see "" + i + " " + leftFact + nl ok
     next


left_fact = Enumerator.new do |y|
  f, lf = 1, 0
  1.step do |n|
    y  << lf #yield left_factorial
    lf += f
    f  *= n
  end
end


a = lftFct(0,10,1)
a = lftFct(20,110,10)
a = lftFct(1000,10000,1000)

function lftFct(f,t,s)
print :print "------ From ";f;" --To-> ";t;" Step ";s;" -------"
for i = f to t step s
	lftFct	= 1
	fct	= 1
	for j = 1 to i-1
		fct	= fct * j
		lftFct	= lftFct + fct
	next j
	if i >= 1000 then
		print i;" ";len(str$(lftFct));" "digits"
	  else
		print i;" ";lftFct
	end if
next i
end function


#[cfg(target_pointer_width = "64")]
type USingle = u32;
#[cfg(target_pointer_width = "64")]
type UDouble = u64;
#[cfg(target_pointer_width = "64")]
const WORD_LEN: i32 = 32;

#[cfg(not(target_pointer_width = "64"))]
type USingle = u16;
#[cfg(not(target_pointer_width = "64"))]
type UDouble = u32;
#[cfg(not(target_pointer_width = "64"))]
const WORD_LEN: i32 = 16;

use std::cmp;

#[derive(Debug,Clone)]
struct BigNum {
    // rep_.size() == 0 if and only if the value is zero.
    // Otherwise, the word rep_[0] keeps the least significant bits.
    rep_: Vec<USingle>,
}

impl BigNum {
    pub fn new(n: USingle) -> BigNum {
        let mut result = BigNum { rep_: vec![] };
        if n > 0 { result.rep_.push(n); }
        result
    }
    pub fn equals(&self, n: USingle) -> bool {
        if n == 0 { return self.rep_.is_empty() }
        if self.rep_.len() > 1 { return false }
        self.rep_[0] == n
    }
    pub fn add_big(&self, addend: &BigNum) -> BigNum {
        let mut result = BigNum::new(0);
        let mut sum = 0 as UDouble;
        let sz1 = self.rep_.len();
        let sz2 = addend.rep_.len();
        for i in 0..cmp::max(sz1, sz2) {
            if i < sz1 { sum += self.rep_[i] as UDouble }
            if i < sz2 { sum += addend.rep_[i] as UDouble }
            result.rep_.push(sum as USingle);
            sum >>= WORD_LEN;
        }
        if sum > 0 { result.rep_.push(sum as USingle) }
        result
    }
    pub fn multiply(&self, factor: USingle) -> BigNum {
        let mut result = BigNum::new(0);
        let mut product = 0 as UDouble;
        for i in 0..self.rep_.len() {
            product += self.rep_[i] as UDouble * factor as UDouble;
            result.rep_.push(product as USingle);
            product >>= WORD_LEN;
        }
        if product > 0 {
            result.rep_.push(product as USingle);
        }
        result
    }
    pub fn divide(&self, divisor: USingle, quotient: &mut BigNum,
        remainder: &mut USingle) {
        quotient.rep_.truncate(0);
        let mut dividend: UDouble;
        *remainder = 0;
        for i in 0..self.rep_.len() {
            let j = self.rep_.len() - 1 - i;
            dividend = ((*remainder as UDouble) << WORD_LEN)
                + self.rep_[j] as UDouble;
            let quo = (dividend / divisor as UDouble) as USingle;
            *remainder = (dividend % divisor as UDouble) as USingle;
            if quo > 0 || j < self.rep_.len() - 1 {
                quotient.rep_.push(quo);
            }
        }
        quotient.rep_.reverse();
    }
    fn to_string(&self) -> String {
        let mut rep = String::new();
        let mut dividend = (*self).clone();
        let mut remainder = 0 as USingle;
        let mut quotient = BigNum::new(0);
        loop {
            dividend.divide(10, &mut quotient, &mut remainder);
            rep.push(('0' as USingle + remainder) as u8 as char);
            if quotient.equals(0) { break; }
            dividend = quotient.clone();
        }
        rep.chars().rev().collect::<String>()
    }
}

use std::fmt;
impl fmt::Display for BigNum {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}

fn lfact(n: USingle) -> BigNum {
    let mut result = BigNum::new(0);
    let mut f = BigNum::new(1);
    for k in 1 as USingle..n + 1 {
        result = result.add_big(&f);
        f = f.multiply(k);
    }
    result
}

fn main() {
    for i in 0..11 {
        println!("!{} = {}", i, lfact(i));
    }
    for i in 2..12 {
        let j = i * 10;
        println!("!{} = {}", j, lfact(j));
    }
    for i in 1..11 {
        let j = i * 1000;
        println!("!{} has {} digits.", j, lfact(j).to_string().len());
    }
}


def dList(n, start):
    start -= 1 # use 0 basing
    a = range(n)
    a[start] = a[0]
    a[0] = start
    a[1:] = sorted(a[1:])
    first = a[1]
    # rescursive closure permutes a[1:]
    r = []
    def recurse(last):
        if (last == first):
            # bottom of recursion. you get here once for each permutation.
            # test if permutation is deranged.
            # yes, save a copy with 1 based indexing
            for j,v in enumerate(a[1:]):
                if j + 1 == v:
                    return # no, ignore it
            b = [x + 1 for x in a]
            r.append(b)
            return
        for i in xrange(last, 0, -1):
            a[i], a[last] = a[last], a[i]
            recurse(last - 1)
            a[i], a[last] = a[last], a[i]
    recurse(n - 1)
    return r

def printSquare(latin,n):
    for row in latin:
        print row
    print

def reducedLatinSquares(n,echo):
    if n <= 0:
        if echo:
            print []
        return 0
    elif n == 1:
        if echo:
            print [1]
        return 1

    rlatin = [None] * n
    for i in xrange(n):
        rlatin[i] = [None] * n
    # first row
    for j in xrange(0, n):
        rlatin[0][j] = j + 1

    class OuterScope:
        count = 0
    def recurse(i):
        rows = dList(n, i)

        for r in xrange(len(rows)):
            rlatin[i - 1] = rows[r]
            justContinue = False
            k = 0
            while not justContinue and k < i - 1:
                for j in xrange(1, n):
                    if rlatin[k][j] == rlatin[i - 1][j]:
                        if r < len(rows) - 1:
                            justContinue = True
                            break
                        if i > 2:
                            return
                k += 1
            if not justContinue:
                if i < n:
                    recurse(i + 1)
                else:
                    OuterScope.count += 1
                    if echo:
                        printSquare(rlatin, n)

    # remaining rows
    recurse(2)
    return OuterScope.count

def factorial(n):
    if n == 0:
        return 1
    prod = 1
    for i in xrange(2, n + 1):
        prod *= i
    return prod

print "The four reduced latin squares of order 4 are:\n"
reducedLatinSquares(4,True)

print "The size of the set of reduced latin squares for the following orders"
print "and hence the total number of latin squares of these orders are:\n"
for n in xrange(1, 7):
    size = reducedLatinSquares(n, False)
    f = factorial(n - 1)
    f *= f * n * size
    print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)


MODULE LAW_OF_COSINES
    IMPLICIT NONE

    CONTAINS

    ! Calculate the third side of a triangle using the cosine rule
    REAL FUNCTION COSINE_SIDE(SIDE_A, SIDE_B, ANGLE)
        INTEGER, INTENT(IN) :: SIDE_A, SIDE_B
        REAL(8), INTENT(IN) :: ANGLE

        COSINE_SIDE = SIDE_A**2 + SIDE_B**2 - 2*SIDE_A*SIDE_B*COS(ANGLE)
        COSINE_SIDE = COSINE_SIDE**0.5
    END FUNCTION COSINE_SIDE

    ! Convert an angle in degrees to radians
    REAL(8) FUNCTION DEG2RAD(ANGLE)
        REAL(8), INTENT(IN) :: ANGLE
        REAL(8), PARAMETER :: PI = 4.0D0*DATAN(1.D0)

        DEG2RAD = ANGLE*(PI/180)
    END FUNCTION DEG2RAD

    ! Sort an array of integers
    FUNCTION INT_SORTED(ARRAY) RESULT(SORTED)
        INTEGER, DIMENSION(:), INTENT(IN) :: ARRAY
        INTEGER, DIMENSION(SIZE(ARRAY)) :: SORTED, TEMP
        INTEGER :: MAX_VAL, DIVIDE

        SORTED = ARRAY
        TEMP = ARRAY
        DIVIDE = SIZE(ARRAY)

        DO WHILE (DIVIDE .NE. 1)
            MAX_VAL = MAXVAL(SORTED(1:DIVIDE))
            TEMP(DIVIDE) = MAX_VAL
            TEMP(MAXLOC(SORTED(1:DIVIDE))) = SORTED(DIVIDE)
            SORTED = TEMP
            DIVIDE = DIVIDE - 1
        END DO
    END FUNCTION INT_SORTED

    ! Append an integer to the end of an array of integers
    SUBROUTINE APPEND(ARRAY, ELEMENT)
        INTEGER, DIMENSION(:), ALLOCATABLE, INTENT(INOUT) :: ARRAY
        INTEGER, DIMENSION(:), ALLOCATABLE :: TEMP
        INTEGER :: ELEMENT
        INTEGER :: I, ISIZE

        IF (ALLOCATED(ARRAY)) THEN
            ISIZE = SIZE(ARRAY)
            ALLOCATE(TEMP(ISIZE+1))

            DO I=1, ISIZE
                TEMP(I) = ARRAY(I)
            END DO

            TEMP(ISIZE+1) = ELEMENT

            DEALLOCATE(ARRAY)

            CALL MOVE_ALLOC(TEMP, ARRAY)
        ELSE
            ALLOCATE(ARRAY(1))
            ARRAY(1) = ELEMENT
        END IF

    END SUBROUTINE APPEND

    ! Check if an array of integers contains a subset
    LOGICAL FUNCTION CONTAINS_ARR(ARRAY, ELEMENT)
        INTEGER, DIMENSION(:), INTENT(IN) :: ARRAY
        INTEGER, DIMENSION(:) :: ELEMENT
        INTEGER, DIMENSION(SIZE(ELEMENT)) :: TEMP, SORTED_ELEMENT
        INTEGER :: I, COUNTER, J

        COUNTER = 0

        ELEMENT = INT_SORTED(ELEMENT)

        DO I=1,SIZE(ARRAY),SIZE(ELEMENT)
            TEMP = ARRAY(I:I+SIZE(ELEMENT)-1)
            DO J=1,SIZE(ELEMENT)
                IF (ELEMENT(J) .EQ. TEMP(J)) THEN
                    COUNTER = COUNTER + 1
                END IF
            END DO

            IF (COUNTER .EQ. SIZE(ELEMENT)) THEN
                CONTAINS_ARR = .TRUE.
                RETURN
            END IF
        END DO

        CONTAINS_ARR = .FALSE.
    END FUNCTION CONTAINS_ARR

    ! Count and print cosine triples for the given angle in degrees
    INTEGER FUNCTION COSINE_TRIPLES(MIN_NUM, MAX_NUM, ANGLE, PRINT_RESULTS) RESULT(COUNTER)
        INTEGER, INTENT(IN) :: MIN_NUM, MAX_NUM
        REAL(8), INTENT(IN) :: ANGLE
        LOGICAL, INTENT(IN) :: PRINT_RESULTS
        INTEGER, DIMENSION(:), ALLOCATABLE :: CANDIDATES
        INTEGER, DIMENSION(3) :: CANDIDATE
        INTEGER :: A, B
        REAL :: C

        COUNTER = 0

        DO A = MIN_NUM, MAX_NUM
            DO B = MIN_NUM, MAX_NUM
                C = COSINE_SIDE(A, B, DEG2RAD(ANGLE))
                IF (C .GT. MAX_NUM .OR. MOD(C, 1.) .NE. 0) THEN
                    CYCLE
                END IF

                CANDIDATE(1) = A
                CANDIDATE(2) = B
                CANDIDATE(3) = C
                IF (.NOT. CONTAINS_ARR(CANDIDATES, CANDIDATE)) THEN
                    COUNTER = COUNTER + 1
                    CALL APPEND(CANDIDATES, CANDIDATE(1))
                    CALL APPEND(CANDIDATES, CANDIDATE(2))
                    CALL APPEND(CANDIDATES, CANDIDATE(3))

                    IF (PRINT_RESULTS) THEN
                        WRITE(*,'(A,I0,A,I0,A,I0,A)') " (", CANDIDATE(1), ", ", CANDIDATE(2), ", ", CANDIDATE(3), ")"
                    END IF
                END IF
            END DO
        END DO
    END FUNCTION COSINE_TRIPLES

END MODULE LAW_OF_COSINES

! Program prints the cosine triples for the angles 90, 60 and 120 degrees
! by using the cosine rule to find the third side of each candidate and
! checking that this is an integer. Candidates are appended to an array
! after the sides have been sorted into ascending order
! the array is repeatedly checked to ensure there are no duplicates.
PROGRAM LOC
    USE LAW_OF_COSINES

    REAL(8), DIMENSION(3) :: TEST_ANGLES = (/90., 60., 120./)
    INTEGER :: I, COUNTER

    DO I = 1,SIZE(TEST_ANGLES)
        WRITE(*, '(F0.0, A)') TEST_ANGLES(I), " degree triangles: "
        COUNTER = COSINE_TRIPLES(1, 13, TEST_ANGLES(I), .TRUE.)
        WRITE(*,'(A, I0)') "TOTAL: ", COUNTER
        WRITE(*,*) NEW_LINE('A')
    END DO

END PROGRAM LOC


$ include "seed7_05.s7i";

const type: charHash is hash [char] integer;

const proc: main is func
  local
    var charHash: numberOfChars is charHash.EMPTY_HASH;
    var char: ch is ' ';
  begin
    ch := getc(IN);
    while ch <> EOF do
      if ch in numberOfChars then
        incr(numberOfChars[ch]);
      else
        numberOfChars @:= [ch] 1;
      end if;
      ch := getc(IN);
    end while;
    for ch range sort(keys(numberOfChars)) do
      writeln(ch <& " " <& numberOfChars[ch]);
    end for;
  end func;


put file "~/Documents/addresses.csv" into source

repeat with each character of source
	if it is a controlChar then next repeat -- skip control characters
	if it is a lowercase then put "." after it -- make keys distinct
	add 1 to counts.(it)
end repeat

repeat with each (theChar, count) in counts
	put char 1 of theChar & " —> " & count
end repeat


object LeftFactorial extends App {

  // this part isn't really necessary, it just shows off Scala's ability
  // to match the mathematical syntax: !n
  implicit class RichInt(n:Int) {
    def unary_!() = factorial.take(n).sum
  }

  val factorial: Stream[BigInt] = 1 #:: factorial.zip(Stream.from(1)).map(n => n._2 * factorial(n._2 - 1))

  for (n <- (0 to 10) ++
            (20 to 110 by 10);
       value = !n) {
    println(s"!${n} = ${value}")
  }
  for (n <- 1000 to 10000 by 1000;
       length = (!n).toString.length) {
    println(s"length !${n} = ${length}")
  }
}


(import (scheme base)     ;; library imports in R7RS style
        (scheme write)
        (srfi 1 lists))

(define (factorial n)
  (fold * 1 (iota n 1)))

(define (left-factorial n)
  (fold + 0 (map factorial (iota n))))

(define (show i r) ; to pretty print the results
  (display "!") (display i) (display " ") (display r) (newline))

;; show left factorials for zero through ten (inclusive)
(for-each
  (lambda (i) (show i (left-factorial i)))
  (iota 11))

;; show left factorials for 20 through 110 (inclusive) by tens
(for-each
  (lambda (i) (show i (left-factorial i)))
  (iota 10 20 10))

;; number of digits in 1000 through 10000 by thousands:
(for-each
  (lambda (i) (show i (string-length (number->string (left-factorial i)))))
  (iota 10 1000 1000))


# utilities: factorial, sub-factorial, derangements
sub  postfix:<!>($n) { (constant f = 1, |[\×] 1..*)[$n] }
sub   prefix:<!>($n) { (1, 0, 1, -> $a, $b { ($++ + 2) × ($b + $a) } ... *)[$n] }
sub derangements(@l) { @l.permutations.grep(-> @p { none(@p Zeqv @l) }) }

sub LS-reduced (Int $n) {
    return [1] if $n == 1;

    my @LS;
    my @l = 1 X+ ^$n;
    my %D = derangements(@l).classify(*.[0]);

    for [X] (^(!$n/($n-1))) xx $n-1 -> $tuple {
        my @d.push: @l;
        @d.push: %D{2}[$tuple[0]];
        LOOP:
        for 3 .. $n -> $x {
            my @try = |%D{$x}[$tuple[$x-2]];
            last LOOP if any @try »==« @d[$_] for 1..@d-1;
            @d.push: @try;
        }
        next unless @d == $n and [==] [Z+] @d;
        @LS.push: @d;
    }
    @LS
}

say .join("\n") ~ "\n" for LS-reduced(4);
for 1..6 -> $n {
    printf "Order $n: Size %-4d x $n! x {$n-1}! => Total %d\n", $_, $_ * $n! * ($n-1)! given LS-reduced($n).elems
}


' version 03-03-2019
' compile with: fbc -s console

#Define max 13

#Define Format(_x)  Right("    " + Str(_x), 4)

Dim As UInteger a, b, c, a2, b2, c2, c60 , c90, c120
Dim As String s60, s90, s120

For a = 1 To max
    a2 = a * a
    For b = a To max
        b2 = b * b
        ' 60 degrees
        c2 = a2 + b * b - a * b
        c = Sqr(c2)
        If c * c = c2 AndAlso c <= max Then
            s60 += Format(a) + Format(b) + Format(c) + Chr(10, 13)
            c60 += 1
        End If
        ' 90 degrees
        c2 = a2 + b * b
        c = Sqr(c2)
        If c * c = c2 AndAlso c <= max Then
            s90 += Format(a) + Format(b) + Format(c) + Chr(10, 13)
            c90 += 1
        End If
        ' 120 degrees
        c2 = a2 + b * b + a * b
        c = Sqr(c2)
        If c * c = c2 AndAlso c <= max Then
            s120 += Format(a) + Format(b) + Format(c) + Chr(10, 13)
            c120 += 1
        End If
    Next
Next

Print Using "###: 60 degree triangles"; c60
Print s60
Print

Print Using "###: 90 degree triangles"; c90
Print s90
Print

Print Using "###: 120 degree triangles"; c120
Print s120
Print

#Undef max
#Define max 10000

c60 = 0
For a = 1 To max
    a2 = a * a
    For b = a +1 To max
        c2 = a2 + b * (b - a)
        c = Sqr(c2)
        If c * c = c2 AndAlso c <= max Then
            c60 += 1
        End If
    Next
Next

Print "For 60 degree triangles in the range [1, 10000]"
Print "There are "; c60; " triangles that have different length for a, b and c"

' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


package main

import "fmt"

type triple struct{ a, b, c int }

var squares13 = make(map[int]int, 13)
var squares10000 = make(map[int]int, 10000)

func init() {
    for i := 1; i <= 13; i++ {
        squares13[i*i] = i
    }
    for i := 1; i <= 10000; i++ {
        squares10000[i*i] = i
    }
}

func solve(angle, maxLen int, allowSame bool) []triple {
    var solutions []triple
    for a := 1; a <= maxLen; a++ {
        for b := a; b <= maxLen; b++ {
            lhs := a*a + b*b
            if angle != 90 {
                switch angle {
                case 60:
                    lhs -= a * b
                case 120:
                    lhs += a * b
                default:
                    panic("Angle must be 60, 90 or 120 degrees")
                }
            }
            switch maxLen {
            case 13:
                if c, ok := squares13[lhs]; ok {
                    if !allowSame && a == b && b == c {
                        continue
                    }
                    solutions = append(solutions, triple{a, b, c})
                }
            case 10000:
                if c, ok := squares10000[lhs]; ok {
                    if !allowSame && a == b && b == c {
                        continue
                    }
                    solutions = append(solutions, triple{a, b, c})
                }
            default:
                panic("Maximum length must be either 13 or 10000")
            }
        }
    }
    return solutions
}

func main() {
    fmt.Print("For sides in the range [1, 13] ")
    fmt.Println("where they can all be of the same length:-\n")
    angles := []int{90, 60, 120}
    var solutions []triple
    for _, angle := range angles {
        solutions = solve(angle, 13, true)
        fmt.Printf("  For an angle of %d degrees", angle)
        fmt.Println(" there are", len(solutions), "solutions, namely:")
        fmt.Printf("  %v\n", solutions)
        fmt.Println()
    }
    fmt.Print("For sides in the range [1, 10000] ")
    fmt.Println("where they cannot ALL be of the same length:-\n")
    solutions = solve(60, 10000, false)
    fmt.Print("  For an angle of 60 degrees")
    fmt.Println(" there are", len(solutions), "solutions.")
}


func letter_frequency(File file) {
    file.read.chars.grep{.match(/[[:alpha:]]/)} \
        .group_by {|letter| letter.downcase}    \
        .map_val  {|_, val| val.len}            \
        .sort_by  {|_, val| -val}
}

var top = letter_frequency(File(__FILE__))
top.each{|pair| say "#{pair[0]}: #{pair[1]}"}


constant iBUFSIZE 500

function main(string filename)
  fsfileinputstream fpi
  integer e, i, aval, zval, cval
  string s, buf, c
  array chars

  e = 0
  fpi [email protected] fsfileinputstream.new(filename, error=e)
  if fpi [email protected]= .nul
    s = "Error, file """ + filename + """ not found{d}{a}"
  else
    chars [email protected] array.new()
    aval = .charval("a")
    zval = .charval("z")
    i = 1
    while i <= 26
      chars[i] = 0
      i = i + 1
    end while
    buf = .lcase(fpi.getstring(iBUFSIZE, 1))
    while not fpi.endofdata and buf > ""
      i = 1
      while i <= .len(buf)
        c = .substr(buf, i, 1)
        cval = .charval(c)
        if cval >= aval and cval <= zval
          chars[cval - aval + 1] = chars[cval - aval + 1] + 1
        end if
        i = i + 1
      end while
      buf = .lcase(fpi.getstring(iBUFSIZE, 1))
    end while

    s = "Character counts for """ + filename + """{d}{a}"
    i = 1
    while i <= chars.count()
      s = s + .char(aval + i - 1) + ": " + .tostr(chars[i], 10) + "{d}{a}"
      i = i + 1
    end while
  end if
end function s


$ include "seed7_05.s7i";
  include "bigint.s7i";

const func bigInteger: leftFact (in integer: n) is func
  result
    var bigInteger: leftFact is 0_;
  local
    var bigInteger: factorial is 1_;
    var integer: i is 0;
  begin
    for i range 1 to n do
      leftFact +:= factorial;
      factorial *:= bigInteger conv i;
    end for;
  end func;

const proc: main is func
  local
    var integer: n is 0;
  begin
    writeln("First 11 left factorials:");
    for n range 0 to 10 do
      write(" " <& leftFact(n));
    end for;
    writeln;
    writeln("20 through 110 (inclusive) by tens:");
    for n range 20 to 110 step 10 do
      writeln(leftFact(n));
    end for;
    writeln;
    writeln("Digits in 1,000 through 10,000 by thousands:");
    for n range 1000 to 10000 step 1000 do
      writeln(length(str(leftFact(n))));
    end for;
    writeln;
  end func;


(* reuse earlier factorial calculations in dfac, apply to listed arguments in cumlfac *)
(* example: left factorial n, is #3 (dfac (0,n-1,1,1) ) *)
(* output list contains (number, factorial, left factorial) *)
(* tested in PolyML *)

val store = ref 0;

val rec dfac = fn
        (from,to,acc,cm) => if from = to then (from,acc,cm) else (store:=(from+1)*acc;dfac (from+1,to,!store,!store+cm ) );

val rec cumlfac = fn
        (x::y::rm) => x :: cumlfac ( dfac (#1 x, #1 y, #2 x, #3 x) :: rm ) |
        rm =>rm ;

val arguments = List.tabulate (10,fn 0=>(0,1,1)|i=>(i,0,0)) @
                List.tabulate (10,fn i=> (10*i+19,0,0) )    @
                List.tabulate ( 10,fn i=> (1000*i+999,0,0));

val result = (~1,0,0)::(cumlfac arguments);

(* done *)
(* display: *)

List.app (fn triple :int*int*int =>
        print(Int.toString (1+ #1 triple ) ^ " : " ^ Int.fmt StringCvt.DEC (#3 triple ) ^" \n" )
        ) (List.take(result,21)  ) ;
List.app (fn triple :int*int*int =>
        print( Int.toString (1+ #1 triple ) ^ " : " ^ Int.toString  (size(Int.toString (#3 triple ))) ^" \n" ) ) (List.drop(result,21)  );


import BigInt

func factorial<T: BinaryInteger>(_ n: T) -> T {
  guard n != 0 else {
    return 1
  }

  return stride(from: n, to: 0, by: -1).reduce(1, *)
}

prefix func ! <T: BinaryInteger>(n: T) -> T {
  guard n != 0 else {
    return 0
  }

  return stride(from: 0, to: n, by: 1).lazy.map(factorial).reduce(0, +)
}

for i in 0...10 {
  print("!\(i) = \(!i)")
}

print()

for i in stride(from: BigInt(20), through: 110, by: 10) {
  print("!\(i) = \(!i)")
}

print()

print("!1000 = \((!BigInt(1000)).description.count) digit number")

print()

for i in stride(from: BigInt(2000), through: 10_000, by: 1000) {
  print("!\(i) = \((!i).description.count) digit number")
}


proc leftfact {n} {
    set s 0
    for {set i [set f 1]} {$i <= $n} {incr i} {
	incr s $f
	set f [expr {$f * $i}]
    }
    return $s
}

for {set i 0} {$i <= 110} {incr i [expr {$i>9?10:1}]} {
    puts "!$i = [leftfact $i]"
}
for {set i 1000} {$i <= 10000} {incr i 1000} {
    puts "!$i has [string length [leftfact $i]] digits"
}


def printSquare(a)
    for row in a
        print row, "\n"
    end
    print "\n"
end

def dList(n, start)
    start = start - 1 # use 0 based indexing
    a = Array.new(n) {|i| i}
    a[0], a[start] = a[start], a[0]
    a[1..] = a[1..].sort
    first = a[1]

    r = []
    recurse = lambda {|last|
        if last == first then
            # bottom of recursion, reached once for each permutation
            # test if permutation is deranged
            a[1..].each_with_index {|v, j|
                if j + 1 == v then
                    return # no, ignore it
                end
            }
            # yes, save a copy with 1 based indexing
            b = a.map { |i| i + 1 }
            r << b
            return
        end

        i = last
        while i >= 1 do
            a[i], a[last] = a[last], a[i]
            recurse.call(last - 1)
            a[i], a[last] = a[last], a[i]
            i = i - 1
        end
    }

    recurse.call(n - 1)
    return r
end

def reducedLatinSquares(n, echo)
    if n <= 0 then
        if echo then
            print "[]\n\n"
        end
        return 0
    end
    if n == 1 then
        if echo then
            print "[1]\n\n"
        end
        return 1
    end

    rlatin = Array.new(n) { Array.new(n, Float::NAN)}

    # first row
    for j in 0 .. n - 1
        rlatin[0][j] = j + 1
    end

    count = 0
    recurse = lambda {|i|
        rows = dList(n, i)

        for r in 0 .. rows.length - 1
            rlatin[i - 1] = rows[r].dup
            catch (:outer) do
                for k in 0 .. i - 2
                    for j in 1 .. n - 1
                        if rlatin[k][j] == rlatin[i - 1][j] then
                            if r < rows.length - 1 then
                                throw :outer
                            end
                            if i > 2 then
                                return
                            end
                        end
                    end
                end
                if i < n then
                    recurse.call(i + 1)
                else
                    count = count + 1
                    if echo then
                        printSquare(rlatin)
                    end
                end
            end
        end
    }

    # remaining rows
    recurse.call(2)
    return count
end

def factorial(n)
    if n == 0 then
        return 1
    end
    prod = 1
    for i in 2 .. n
        prod = prod * i
    end
    return prod
end

print "The four reduced latin squares of order 4 are:\n"
reducedLatinSquares(4, true)

print "The size of the set of reduced latin squares for the following orders\n"
print "and hence the total number of latin squares of these orders are:\n"
for n in 1 .. 6
    size = reducedLatinSquares(n, false)
    f = factorial(n - 1)
    f = f * f * n * size
    print "Order %d Size %-4d x %d! x %d! => Total %d\n" % [n, size, n, n - 1, f]
end


import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.Monoid ((<>))

triangles
  :: (Map.Map Int Int -> Int -> Int -> Int -> Int -> Maybe Int)
  -> Int
  -> [(Int, Int, Int)]
triangles f n =
  let mapRoots = Map.fromList $ ((,) =<< (^ 2)) <$> [1 .. n]
  in Set.elems $
     foldr
       (\(suma2b2, a, b) triSet ->
           (case f mapRoots suma2b2 (a * b) a b of
              Just c -> Set.insert (a, b, c) triSet
              _ -> triSet))
       (Set.fromList [])
       ([1 .. n] >>=
        (\a -> (flip (,,) a =<< (a * a +) . (>>= id) (*)) <$> [1 .. a]))

-- TESTS ------------------------------------------------------------------------

f90, f60, f60ne, f120 :: Map.Map Int Int -> Int -> Int -> Int -> Int -> Maybe Int
f90 dct x2 ab a b = Map.lookup x2 dct

f60 dct x2 ab a b = Map.lookup (x2 - ab) dct

f120 dct x2 ab a b = Map.lookup (x2 + ab) dct

f60ne dct x2 ab a b
  | a == b = Nothing
  | otherwise = Map.lookup (x2 - ab) dct

main :: IO ()
main = do
  putStrLn
    (unlines $
     "Triangles of maximum side 13\n" :
     zipWith
       (\f n ->
           let solns = triangles f 13
           in show (length solns) <> " solutions for " <> show n <>
              " degrees:\n" <>
              unlines (show <$> solns))
       [f120, f90, f60]
       [120, 90, 60])
  putStrLn "60 degrees - uneven triangles of maximum side 10000. Total:"
  print $ length $ triangles f60ne 10000


bagOfChars := 'someFile' asFilename contentsAsString asBag.
bag sortedCounts
    select:[:assoc | assoc value isLetter ]
    thenDo:[:assoc | assoc printCR].


import Foundation

let dictPath: String

switch CommandLine.arguments.count {
case 2:
  dictPath = CommandLine.arguments[1]
case _:
  dictPath = "/usr/share/dict/words"
}

let wordsData = FileManager.default.contents(atPath: dictPath)!
let allWords = String(data: wordsData, encoding: .utf8)!
let words = allWords.components(separatedBy: "\n")
let counts = words.flatMap({ $0.map({ ($0, 1) }) }).reduce(into: [:], { $0[$1.0, default: 0] += $1.1 })

for (char, count) in counts {
  print("\(char): \(count)")
}


import "/fmt" for Fmt
import "/big" for BigInt

var lfacts = List.filled(12, BigInt.zero)
var lfact = BigInt.one
var sum = BigInt.zero

for (i in 1..10) {
    sum = sum + lfact
    lfacts[i] = sum
    lfact = lfact * i
}
System.print("Left factorials from 0 to 10:")
for (i in 0..10) System.write(" %(lfacts[i])")

for (i in 11..110) {
    sum = sum + lfact
    if (i%10 == 0) lfacts[i/10] = sum
    lfact = lfact * i
}
System.print("\n\nLeft factorials from 20 to 110 by tens:")
for (i in 2..11) Fmt.print(" !$-3d -> $s", i * 10, lfacts[i])

for (i in 111..10000) {
    sum = sum + lfact
    if (i%1000 == 0) lfacts[i/1000] = sum
    lfact = lfact * i
}
System.print("\nLengths of left factorals from 1000 to 10000 by thousands:")
for (i in 1..10) Fmt.print(" !$-5d -> $5s", i * 1000, lfacts[i].toString.count)


var BN=Import("zklBigNum");

fcn leftFact(n){
   [1..n].reduce(fcn(p,n,rf){ p+=rf.value; rf.set(rf.value*n); p },
      BN(0),Ref(BN(1)));
}


Option Strict On

Imports Matrix = System.Collections.Generic.List(Of System.Collections.Generic.List(Of Integer))

Module Module1

    Sub Swap(Of T)(ByRef a As T, ByRef b As T)
        Dim u = a
        a = b
        b = u
    End Sub

    Sub PrintSquare(latin As Matrix)
        For Each row In latin
            Dim it = row.GetEnumerator
            Console.Write("[")
            If it.MoveNext Then
                Console.Write(it.Current)
            End If
            While it.MoveNext
                Console.Write(", ")
                Console.Write(it.Current)
            End While
            Console.WriteLine("]")
        Next
        Console.WriteLine()
    End Sub

    Function DList(n As Integer, start As Integer) As Matrix
        start -= 1 REM use 0 based indexes
        Dim a = Enumerable.Range(0, n).ToArray
        a(start) = a(0)
        a(0) = start
        Array.Sort(a, 1, a.Length - 1)
        Dim first = a(1)
        REM recursive closure permutes a[1:]
        Dim r As New Matrix

        Dim Recurse As Action(Of Integer) = Sub(last As Integer)
                                                If last = first Then
                                                    REM bottom of recursion. you get here once for each permutation
                                                    REM test if permutation is deranged.
                                                    For j = 1 To a.Length - 1
                                                        Dim v = a(j)
                                                        If j = v Then
                                                            Return REM no, ignore it
                                                        End If
                                                    Next
                                                    REM yes, save a copy with 1 based indexing
                                                    Dim b = a.Select(Function(v) v + 1).ToArray
                                                    r.Add(b.ToList)
                                                    Return
                                                End If
                                                For i = last To 1 Step -1
                                                    Swap(a(i), a(last))
                                                    Recurse(last - 1)
                                                    Swap(a(i), a(last))
                                                Next
                                            End Sub
        Recurse(n - 1)
        Return r
    End Function

    Function ReducedLatinSquares(n As Integer, echo As Boolean) As ULong
        If n <= 0 Then
            If echo Then
                Console.WriteLine("[]")
                Console.WriteLine()
            End If
            Return 0
        End If
        If n = 1 Then
            If echo Then
                Console.WriteLine("[1]")
                Console.WriteLine()
            End If
            Return 1
        End If

        Dim rlatin As New Matrix
        For i = 0 To n - 1
            rlatin.Add(New List(Of Integer))
            For j = 0 To n - 1
                rlatin(i).Add(0)
            Next
        Next
        REM first row
        For j = 0 To n - 1
            rlatin(0)(j) = j + 1
        Next

        Dim count As ULong = 0
        Dim Recurse As Action(Of Integer) = Sub(i As Integer)
                                                Dim rows = DList(n, i)

                                                For r = 0 To rows.Count - 1
                                                    rlatin(i - 1) = rows(r)
                                                    For k = 0 To i - 2
                                                        For j = 1 To n - 1
                                                            If rlatin(k)(j) = rlatin(i - 1)(j) Then
                                                                If r < rows.Count - 1 Then
                                                                    GoTo outer
                                                                End If
                                                                If i > 2 Then
                                                                    Return
                                                                End If
                                                            End If
                                                        Next
                                                    Next
                                                    If i < n Then
                                                        Recurse(i + 1)
                                                    Else
                                                        count += 1UL
                                                        If echo Then
                                                            PrintSquare(rlatin)
                                                        End If
                                                    End If
outer:
                                                    While False
                                                        REM empty
                                                    End While
                                                Next
                                            End Sub

        REM remiain rows
        Recurse(2)
        Return count
    End Function

    Function Factorial(n As ULong) As ULong
        If n <= 0 Then
            Return 1
        End If
        Dim prod = 1UL
        For i = 2UL To n
            prod *= i
        Next
        Return prod
    End Function

    Sub Main()
        Console.WriteLine("The four reduced latin squares of order 4 are:")
        Console.WriteLine()
        ReducedLatinSquares(4, True)

        Console.WriteLine("The size of the set of reduced latin squares for the following orders")
        Console.WriteLine("and hence the total number of latin squares of these orders are:")
        Console.WriteLine()
        For n = 1 To 6
            Dim nu As ULong = CULng(n)

            Dim size = ReducedLatinSquares(n, False)
            Dim f = Factorial(nu - 1UL)
            f *= f * nu * size
            Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f)
        Next
    End Sub

End Module


load 'trig stats'
RHS=: *:                               NB. right-hand-side of Cosine Law
LHS=: +/@:*:@] - [email protected]@[ * 2 * */@]  NB. Left-hand-side of Cosine Law

solve=: 4 :0
  adjsides=. >: 2 combrep y
  oppside=. >: i. y
  idx=. (RHS oppside) i. x LHS"1 adjsides
  adjsides ((#~ idx ~: #) ,. ({~ idx -. #)@]) oppside
)


public class LawOfCosines {

    public static void main(String[] args) {
        generateTriples(13);
        generateTriples60(10000);
    }

    private static void generateTriples(int max) {
        for ( int coeff : new int[] {0, -1, 1} ) {
            int count = 0;
            System.out.printf("Max side length %d, formula:  a*a + b*b %s= c*c%n", max, coeff == 0 ? "" : (coeff<0 ? "-"  : "+") + " a*b ");
            for ( int a = 1 ; a <= max ; a++ ) {
                for ( int b = 1 ; b <= a ; b++ ) {
                    int val = a*a + b*b + coeff*a*b;
                    int c = (int) (Math.sqrt(val) + .5d);
                    if ( c > max ) {
                        break;
                    }
                    if ( c*c == val ) {
                        System.out.printf("  (%d, %d, %d)%n", a, b ,c);
                        count++;
                    }
                }
            }
            System.out.printf("%d triangles%n", count);
        }
    }

    private static void generateTriples60(int max) {
        int count = 0;
        System.out.printf("%nExtra Credit.%nMax side length %d, sides different length, formula:  a*a + b*b - a*b = c*c%n", max);
        for ( int a = 1 ; a <= max ; a++ ) {
            for ( int b = 1 ; b < a ; b++ ) {
                int val = a*a + b*b - a*b;
                int c = (int) (Math.sqrt(val) + .5d);
                if ( c*c == val ) {
                    count++;
                }
            }
        }
        System.out.printf("%d triangles%n", count);
    }

}


proc letterHistogram {fileName} {
    # Initialize table (in case of short texts without every letter)
    for {set i 97} {$i<=122} {incr i} {
        set frequency([format %c $i]) 0
    }
    # Iterate over characters in file
    set f [open $fileName]
    foreach c [split [read $f] ""] {
        # Count them if they're alphabetic
        if {[string is alpha $c]} {
            incr frequency([string tolower $c])
        }
    }
    close $f
    # Print the histogram
    parray frequency
}

letterHistogram the/sample.txt


$$ MODE TUSCRIPT
words = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt")

DICT letters create
MODE {}
COMPILE
LOOP word=words
 letters=SPLIT (word,|":?:")
 LOOP letter=letters
  DICT letters ADD/QUIET/COUNT letter
 ENDLOOP
ENDLOOP
ENDCOMPILE
DICT letters unload letter,size,cnt

index    =DIGIT_INDEX (cnt)
index    =REVERSE (index)
letter   =INDEX_SORT (letter,index)
cnt      =INDEX_SORT (cnt,index)
frequency=JOIN (letter," --- ",cnt)

*{frequency}


import "/sort" for Sort
import "/math" for Int
import "/fmt" for Fmt

// generate derangements of first n numbers, with 'start' in first place.
var dList = Fn.new { |n, start|
    var r = []
    start = start - 1 // use 0 basing
    var a = [0] * n
    for (i in 1...n) a[i] = i
    a[start] = a[0]
    a[0] = start
    Sort.quick(a, 1, a.count - 1, false)
    var first = a[1]
    var recurse // recursive closure permutes a[1..-1]
    recurse = Fn.new { |last|
        if (last == first) {
            // bottom of recursion.  you get here once for each permutation.
            // test if permutation is deranged.
            var j = 1
            for (v in a.skip(1)) {
                if (j == v) return // no, ignore it
                j = j + 1
            }
            // yes, save a copy
            var b = a.toList
            for (i in 0...b.count) b[i] = b[i] + 1  // change back to 1 basing
            r.add(b)
            return
        }
        var i = last
        while (i >= 1) {
            var t = a[i]
            a[i] = a[last]
            a[last] = t
            recurse.call(last-1)
            t = a[i]
            a[i] = a[last]
            a[last] = t
            i = i - 1
        }
    }
    recurse.call(n-1)
    return r
}

var printSquare = Fn.new { |latin, n|
    System.print(latin.join("\n"))
    System.print()
}

var reducedLatinSquare = Fn.new { |n, echo|
    if (n <= 0) {
        if (echo) System.print("[]\n")
        return 0
    }
    if (n == 1) {
        if (echo) System.print("[1]\n")
        return 1
    }
    var rlatin = List.filled(n, null)
    for (i in 0...n) rlatin[i] = List.filled(n, 0)
    // first row
    for (j in 0...n) rlatin[0][j] = j + 1
    var count = 0
    var recurse // // recursive closure to compute reduced latin squares and count or print them
    recurse = Fn.new { |i|
        var rows = dList.call(n, i) // get derangements of first n numbers, with 'i' first.
        for (r in 0...rows.count) {
            var outer = false
            for (rr in 0...rows[r].count) rlatin[i-1][rr] = rows[r][rr]
            var k = 0
            while (k < i-1) {
                var j = 1
                while (j < n) {
                    if (rlatin[k][j] == rlatin[i-1][j]) {
                        if (r < rows.count - 1) {
                            outer = true
                            break
                        } else if (i > 2) {
                            return
                        }
                    }
                    j = j + 1
                }
                if (outer) break
                k = k + 1
            }
            if (!outer) {
                if (i < n) {
                    recurse.call(i + 1)
                } else {
                    count = count + 1
                    if (echo) printSquare.call(rlatin, n)
                }
            }
        }
    }

    // remaining rows
    recurse.call(2)
    return count
}

System.print("The four reduced latin squares of order 4 are:\n")
reducedLatinSquare.call(4, true)

System.print("The size of the set of reduced latin squares for the following orders")
System.print("and hence the total number of latin squares of these orders are:\n")
for (n in 1..6) {
    var size = reducedLatinSquare.call(n, false)
    var f = Int.factorial(n-1)
    f = f * f * n * size
    Fmt.print("Order $d: Size $-4d x $d! x $d! => Total $d", n, size, n, n-1, f)
}