with Ada.Text_IO;

procedure Letter_Frequency is
   Counters: array (Character) of Natural := (others => 0); -- initialize all Counters to 0
   C:        Character;
   File:     Ada.Text_IO.File_Type;

begin
   Ada.Text_IO.Open(File, Mode => Ada.Text_IO.In_File, Name => "letter_frequency.adb");
   while not Ada.Text_IO.End_Of_File(File) loop
      Ada.Text_IO.Get(File, C);
      Counters(C) := Counters(C) + 1;
   end loop;

   for I in Counters'Range loop
      if Counters(I) > 0 then
            Ada.Text_IO.Put_Line("'" & I & "':" & Integer'Image(Counters(I)));
      end if;
   end loop;
end Letter_Frequency;


import ctype

var letters = new int [26]

var s = openin (args[0])
while (!s.eof()) {
    var ch = s.getchar()
    if (s.eof()) {
        break
    }
    if (ctype.isalpha (ch)) {
        var n = cast<int>(ctype.tolower(ch) - 'a')
        ++letters[n]
    }
}

foreach i letters.size() {
    println (cast<char>('a' + i) + " " + letters[i])
}


file f;
index x;
integer c;

f.affix("unixdict.txt");

while ((c = f.pick) ^ -1) {
    x[c] += 1;
}

c = 'A';
while (c <= 'Z') {
    o_form("%c: /w5/\n", c, x[c] += x[c + 'a' - 'A'] += 0);
    c += 1;
}


BEGIN
   [0:max abs char]INT histogram;
   FOR i FROM 0 TO max abs char DO histogram[i] := 0 OD;
   FILE input file;
   STRING input file name = "Letter_frequency.a68";
   IF open (input file, input file name, stand in channel) /= 0 THEN
      put (stand error, ("Cannot open ", input file name, newline));
      stop
   ELSE
      on file end (input file, (REF FILE f) BOOL: (close (f); GOTO finished))
   FI;
   DO
      STRING s;
      get (input file, (s, newline));
      FOR i TO UPB s DO
	 CHAR c = s[i];
	 IF "A" <= c AND c <= "Z" OR "a" <= c AND c <= "z" THEN
	    histogram[ABS c] PLUSAB 1
	 FI
     OD
   OD;
   close (input file);
finished:
   FOR i FROM ABS "A" TO ABS "Z" DO printf (($a3xg(0)l$, REPR i, histogram[i])) OD;
   FOR i FROM ABS "a" TO ABS "z" DO printf (($a3xg(0)l$, REPR i, histogram[i])) OD
END


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

on letterFrequencyinFile(theFile)
    -- Read the file as an NSString, letting the system guess the encoding.
    set fileText to current application's class "NSString"'s stringWithContentsOfFile:(POSIX path of theFile) ¬
        usedEncoding:(missing value) |error|:(missing value)
    -- Get the NSString's non-letter delimited runs, lower-cased, as an AppleScript list of texts.
    -- The switch to vanilla objects is for speed and the ability to extract 'characters'.
    set nonLetterSet to current application's class "NSCharacterSet"'s letterCharacterSet()'s invertedSet()
    script o
        property letterRuns : (fileText's lowercaseString()'s componentsSeparatedByCharactersInSet:(nonLetterSet)) as list
    end script

    -- Extract the characters from the runs and add them to an NSCountedSet to have the occurrences of each value counted.
    -- No more than 50,000 characters are extracted in one go to avoid slowing or freezing the script.
    set countedSet to current application's class "NSCountedSet"'s new()
    repeat with i from 1 to (count o's letterRuns)
        set thisRun to item i of o's letterRuns
        set runLength to (count thisRun)
        repeat with i from 1 to runLength by 50000
            set j to i + 49999
            if (j > runLength) then set j to runLength
            tell countedSet to addObjectsFromArray:(characters i thru j of thisRun)
        end repeat
    end repeat

    -- Work through the counted set's contents and build a list of records showing how many of what it received.
    set output to {}
    repeat with thisLetter in countedSet's allObjects()
        set thisCount to (countedSet's countForObject:(thisLetter))
        set end of output to {letter:thisLetter, |count|:thisCount}
    end repeat

    -- Derive an array of dictionaries from the list and sort it on the letters.
    set output to current application's class "NSMutableArray"'s arrayWithArray:(output)
    set byLetter to current application's class "NSSortDescriptor"'s sortDescriptorWithKey:("letter") ¬
        ascending:(true) selector:("localizedStandardCompare:")
    tell output to sortUsingDescriptors:({byLetter})

    -- Convert back to a list of records and return the result.
    return output as list
end letterFrequencyinFile

-- Test with the text file for the "Word frequency" task.
set theFile to ((path to desktop as text) & "135-0.txt") as alias
return letterFrequencyinFile(theFile)


source: {
The Red Death had long devastated the country.
No pestilence had ever been so fatal, or so hideous.
Blood was its Avator and its seal—the redness and the horror of blood.
There were sharp pains, and sudden dizziness,
and then profuse bleeding at the pores, with dissolution.
The scarlet stains upon the body and especially upon the face of the victim,
were the pest ban which shut him out from the aid and from the sympathy of his fellow-men.
And the whole seizure, progress and termination of the disease,
were the incidents of half an hour.
}

valid: split "abcdefghijklmnopqrstuvwxyz"
frequencies: #[]

loop split lower source 'ch [
    if in? ch valid [
        if not? key? frequencies ch ->
            set frequencies ch 0

        set frequencies ch (get frequencies ch)+1
    ]
]

inspect.muted frequencies


LetterFreq(Var) {
	Loop, 26
	{
		StrReplace(Var, Chr(96+A_Index), , Count)
		if Count
			out .= Chr(96+A_Index) ": " Count "`n"
	}
	return out
}

var := "The dog jumped over the lazy fox"
var2 := "foo bar"
Msgbox, % LetterFreq(var)
Msgbox, % LetterFreq(var2)


Func _Letter_frequency($Path, $fcase = True, $fspecial_chars = True)
	Local $hFile, $sRead, $iupto, $iStart, $iCount
	If Not $fcase Then $fcase = False
	If Not $fspecial_chars Then
		$iStart = 64
		If Not $fcase Then
			$iupto = 26
		Else
			$iupto = 58
		EndIf
	Else
		$iStart = 31
		$iupto = 224
	EndIf
	$hFile = FileOpen($Path, 0)
	$sRead = FileRead($hFile)
	FileClose($hFile)
	For $i = 1 To $iupto
		If Not $fspecial_chars Then
			If $iStart + $i > 90 And $iStart + $i < 97 Then ContinueLoop
		EndIf
		$sRead = StringReplace($sRead, Chr($iStart + $i), "", 0, $fcase)
		$iCount = @extended
		If $iCount > 0 Then ConsoleWrite(Chr($iStart + $i) & " : " & $iCount & @CRLF)
	Next
EndFunc   ;==>_Letter_frequency


# usage: awk -f letters.awk HolyBible.txt

BEGIN { FS="" }
      { for(i=1;i<=NF;i++) m[$i]++}
END   { for(i in m) printf("%9d %-14s\n", m[i],i) }


txt$ = LOAD$("bible.txt")

FOR x = 97 TO 122
    PRINT CHR$(x-32), " ", CHR$(x), " : ", COUNT(txt$, x-32), " - ", COUNT(txt$, x)
NEXT


      DIM cnt%(255)

      file% = OPENIN("C:\unixdict.txt")
      IF file%=0 ERROR 100, "Could not open file"

      REPEAT
        A$ = GET$#file%
        L% = LEN(A$)
        IF L% THEN
          FOR I% = 1 TO L%
            cnt%(ASCMID$(A$,I%)) += 1
          NEXT
        ENDIF
      UNTIL EOF#file%
      CLOSE #file%

      FOR c% = &41 TO &5A
        PRINT CHR$(c%)CHR$(c%+32) ": " cnt%(c%)+cnt%(c%+32)
      NEXT


get "libhdr"

let start() be
$(  let count = vec 255
    let file = findinput("unixdict.txt")

    for i = 0 to 255 do i!count := 0

    selectinput(file)
    $(  let ch = rdch()
        if ch = endstreamch then break
        ch!count := ch!count + 1
    $) repeat

    for i = 'A' to 'Z' do
    $(  let n = i!count + (i|32)!count
        unless n = 0 do
            writef("%C%C: %I5*N", i, i|32, n)
    $)

    endread()
$)


(lc=
  counts c
.     fil$(!arg,r)                        {open file for reading}
    & 0:?counts
    &   whl
      ' ( fil$:?c                         {read a byte}
        &     ( !c:(~<A:~>Z|~<a:~>z)
              | 0
              )
            + !counts
          : ?counts                       {simply add any found letter to the sum}
        )
    & fil$(,SET,-1)                       {close the file by seeking to impossible file position.}
  | !counts                               {return the sum}
);

lc$"valid.bra"                            {example: count letters in Bracmat's validation suite.}


/* declare array */
int frequency[26];
int ch;
FILE* txt_file = fopen ("a_text_file.txt", "rt");

/* init the freq table: */
for (ch = 0; ch < 26; ch++)
    frequency[ch] = 0;

while (1) {
    ch = fgetc(txt_file);
    if (ch == EOF) break; /* end of file or read error.  EOF is typically -1 */

    /* assuming ASCII; "letters" means "a to z" */
    if ('a' <= ch && ch <= 'z')      /* lower case */
        frequency[ch-'a']++;
    else if ('A' <= ch && ch <= 'Z') /* upper case */
        frequency[ch-'A']++;
}


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

class Program
{
    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)
    {
        var dictionary = new SortedDictionary<TItem, int>();
        foreach (var item in items)
        {
            if (dictionary.ContainsKey(item))
            {
                dictionary[item]++;
            }
            else
            {
                dictionary[item] = 1;
            }
        }
        return dictionary;
    }

    static void Main(string[] arguments)
    {
        var file = arguments.FirstOrDefault();
        if (File.Exists(file))
        {
            var text = File.ReadAllText(file);
            foreach (var entry in GetFrequencies(text))
            {
                Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
            }
        }
    }
}


#include <fstream>
#include <iostream>

int main()
{
	std::ifstream input("filename.txt", std::ios_base::binary);
	if (!input)
	{
		std::cerr << "error: can't open file\n";
		return -1;
	}

	size_t count[256];
	std::fill_n(count, 256, 0);

	for (char c; input.get(c); ++count[uint8_t(c)]) // process input file
		; // empty loop body

	for (size_t i = 0; i < 256; ++i)
	{
		if (count[i] && isgraph(i)) // non-zero counts of printable characters
		{
			std::cout << char(i) << " = " << count[i] << '\n';
		}
	}
}


(println (sort-by second >
			(frequencies (map #(java.lang.Character/toUpperCase %)
					  (filter #(java.lang.Character/isLetter %) (slurp "text.txt"))))))


(defun letter-freq (file)
  (with-open-file (stream file)
    (let ((str (make-string (file-length stream)))
	  (arr (make-array 256 :element-type 'integer :initial-element 0)))
      (read-sequence str stream)
      (loop for c across str do (incf (aref arr (char-code c))))
      (loop for c from 32 to 126 for i from 1 do
	    (format t "~c: ~d~a"
		    (code-char c) (aref arr c)
		    (if (zerop (rem i 8)) #\newline #\tab))))))

(letter-freq "test.lisp")


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Letter-Frequency.
       AUTHOR.  Bill Gunshannon.
       INSTALLATION.  Home.
       DATE-WRITTEN.  12 December 2021.
      ************************************************************
      ** Program Abstract:
      **   A rather simplistic program to do the kind of thing
      **   that COBOL does really well.
      ************************************************************

       ENVIRONMENT DIVISION.

       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
            SELECT Text-File ASSIGN TO "File.txt"
                 ORGANIZATION IS LINE SEQUENTIAL.

       DATA DIVISION.

       FILE SECTION.

       FD  Text-File
           DATA RECORD IS Record-Name.
       01  Record-Name           PIC X(80).

       WORKING-STORAGE SECTION.

       01 Eof                   PIC X     VALUE 'F'.

       01  Letter-cnt.
           05  A-cnt            PIC 9(5)    VALUE 0.
           05  B-cnt            PIC 9(5)    VALUE 0.
           05  C-cnt            PIC 9(5)    VALUE 0.
           05  D-cnt            PIC 9(5)    VALUE 0.
           05  E-cnt            PIC 9(5)    VALUE 0.
           05  F-cnt            PIC 9(5)    VALUE 0.
           05  G-cnt            PIC 9(5)    VALUE 0.
           05  H-cnt            PIC 9(5)    VALUE 0.
           05  I-cnt            PIC 9(5)    VALUE 0.
           05  J-cnt            PIC 9(5)    VALUE 0.
           05  K-cnt            PIC 9(5)    VALUE 0.
           05  L-cnt            PIC 9(5)    VALUE 0.
           05  M-cnt            PIC 9(5)    VALUE 0.
           05  N-cnt            PIC 9(5)    VALUE 0.
           05  O-cnt            PIC 9(5)    VALUE 0.
           05  P-cnt            PIC 9(5)    VALUE 0.
           05  Q-cnt            PIC 9(5)    VALUE 0.
           05  R-cnt            PIC 9(5)    VALUE 0.
           05  S-cnt            PIC 9(5)    VALUE 0.
           05  T-cnt            PIC 9(5)    VALUE 0.
           05  U-cnt            PIC 9(5)    VALUE 0.
           05  V-cnt            PIC 9(5)    VALUE 0.
           05  W-cnt            PIC 9(5)    VALUE 0.
           05  X-cnt            PIC 9(5)    VALUE 0.
           05  Y-cnt            PIC 9(5)    VALUE 0.
           05  Z-cnt            PIC 9(5)    VALUE 0.

       01  Letter-disp.
           05  A-cnt            PIC ZZZZ9.
           05  B-cnt            PIC ZZZZ9.
           05  C-cnt            PIC ZZZZ9.
           05  D-cnt            PIC ZZZZ9.
           05  E-cnt            PIC ZZZZ9.
           05  F-cnt            PIC ZZZZ9.
           05  G-cnt            PIC ZZZZ9.
           05  H-cnt            PIC ZZZZ9.
           05  I-cnt            PIC ZZZZ9.
           05  J-cnt            PIC ZZZZ9.
           05  K-cnt            PIC ZZZZ9.
           05  L-cnt            PIC ZZZZ9.
           05  M-cnt            PIC ZZZZ9.
           05  N-cnt            PIC ZZZZ9.
           05  O-cnt            PIC ZZZZ9.
           05  P-cnt            PIC ZZZZ9.
           05  Q-cnt            PIC ZZZZ9.
           05  R-cnt            PIC ZZZZ9.
           05  S-cnt            PIC ZZZZ9.
           05  T-cnt            PIC ZZZZ9.
           05  U-cnt            PIC ZZZZ9.
           05  V-cnt            PIC ZZZZ9.
           05  W-cnt            PIC ZZZZ9.
           05  X-cnt            PIC ZZZZ9.
           05  Y-cnt            PIC ZZZZ9.
           05  Z-cnt            PIC ZZZZ9.

       PROCEDURE DIVISION.

       Main-Program.
           OPEN INPUT  Text-File
           PERFORM UNTIL Eof = 'T'
              READ  Text-File
                    AT END MOVE 'T' to Eof
              END-READ
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING A-cnt OF Letter-cnt  FOR ALL 'A'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING B-cnt OF Letter-cnt  FOR ALL 'B'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING C-cnt OF Letter-cnt  FOR ALL 'C'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING D-cnt OF Letter-cnt  FOR ALL 'D'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING E-cnt OF Letter-cnt  FOR ALL 'E'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING F-cnt OF Letter-cnt  FOR ALL 'F'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING G-cnt OF Letter-cnt  FOR ALL 'G'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING H-cnt OF Letter-cnt  FOR ALL 'H'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING I-cnt OF Letter-cnt  FOR ALL 'I'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING J-cnt OF Letter-cnt  FOR ALL 'J'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING K-cnt OF Letter-cnt  FOR ALL 'K'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING L-cnt OF Letter-cnt  FOR ALL 'L'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING M-cnt OF Letter-cnt  FOR ALL 'M'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING N-cnt OF Letter-cnt  FOR ALL 'N'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING O-cnt OF Letter-cnt  FOR ALL 'O'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING P-cnt OF Letter-cnt  FOR ALL 'P'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING Q-cnt OF Letter-cnt  FOR ALL 'Q'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING R-cnt OF Letter-cnt  FOR ALL 'R'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING S-cnt OF Letter-cnt  FOR ALL 'S'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING T-cnt OF Letter-cnt  FOR ALL 'T'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING U-cnt OF Letter-cnt  FOR ALL 'U'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING V-cnt OF Letter-cnt  FOR ALL 'V'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING W-cnt OF Letter-cnt  FOR ALL 'W'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING X-cnt OF Letter-cnt  FOR ALL 'X'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING Y-cnt OF Letter-cnt  FOR ALL 'Y'
           INSPECT FUNCTION UPPER-CASE(Record-Name)
                   TALLYING Z-cnt OF Letter-cnt  FOR ALL 'Z'
           END-PERFORM.
           CLOSE Text-File.
           MOVE CORRESPONDING Letter-cnt To Letter-disp.
           DISPLAY 'Letter Frequency Distribution'.
           DISPLAY '-----------------------------'.
           DISPLAY 'A : ' A-cnt OF Letter-disp '          '
                   'N : ' N-cnt OF Letter-disp.
           DISPLAY 'B : ' B-cnt OF Letter-disp '          '
                   'O : ' O-cnt OF Letter-disp.
           DISPLAY 'C : ' C-cnt OF Letter-disp '          '
                   'P : ' P-cnt OF Letter-disp.
           DISPLAY 'D : ' D-cnt OF Letter-disp '          '
                   'Q : ' Q-cnt OF Letter-disp.
           DISPLAY 'E : ' E-cnt OF Letter-disp '          '
                   'R : ' R-cnt OF Letter-disp.
           DISPLAY 'F : ' F-cnt OF Letter-disp '          '
                   'S : ' S-cnt OF Letter-disp.
           DISPLAY 'G : ' G-cnt OF Letter-disp '          '
                   'T : ' T-cnt OF Letter-disp.
           DISPLAY 'H : ' H-cnt OF Letter-disp '          '
                   'U : ' U-cnt OF Letter-disp.
           DISPLAY 'I : ' I-cnt OF Letter-disp '          '
                   'V : ' V-cnt OF Letter-disp.
           DISPLAY 'J : ' J-cnt OF Letter-disp '          '
                   'W : ' W-cnt OF Letter-disp.
           DISPLAY 'K : ' K-cnt OF Letter-disp '          '
                   'X : ' X-cnt OF Letter-disp.
           DISPLAY 'L : ' L-cnt OF Letter-disp '          '
                   'Y : ' Y-cnt OF Letter-disp.
           DISPLAY 'M : ' M-cnt OF Letter-disp '          '
                   'Z : ' Z-cnt OF Letter-disp.
           STOP RUN.

       END-PROGRAM.


MODULE LetterFrecuency;
IMPORT Files,StdLog,Strings;

PROCEDURE Do*;
VAR
	loc: Files.Locator;
	fd: Files.File;
	rd: Files.Reader;
	x: BYTE;
	frecuency: ARRAY 26 OF LONGINT;
	c: CHAR;
	i: INTEGER;
BEGIN
	loc := Files.dir.This("BBTest/Mod");
	fd := Files.dir.Old(loc,"LetterFrecuency.odc",FALSE);
	rd := fd.NewReader(NIL);

	(* init the frecuency array *)
	FOR i := 0 TO LEN(frecuency) - 1 DO frecuency[i] := 0 END;

	(* collect frecuencies *)
	WHILE ~rd.eof DO
		rd.ReadByte(x);c := CAP(CHR(x));
		(* convert vowels with diacritics *)
		CASE ORD(c) OF
			 193: c := 'A';
			|201: c := 'E';
			|205: c := 'I';
			|211: c := 'O';
			|218: c := 'U';
			ELSE
		END;
		IF (c >= 'A') & (c <= 'Z') THEN
			INC(frecuency[ORD(c) - ORD('A')]);
		END
	END;

	(* show data *)
	FOR i := 0 TO LEN(frecuency) - 1 DO
		StdLog.Char(CHR(i + ORD('A')));StdLog.String(":> ");StdLog.Int(frecuency[i]);
		StdLog.Ln
	END
END Do;
END LetterFrecuency.


include "cowgol.coh";
include "argv.coh";
include "file.coh";

# Get filename from command line
ArgvInit();
var file := ArgvNext();
if file == (0 as [uint8]) then
    print("error: no file name\n");
    ExitWithError();
end if;

# Open the file
var fcb: FCB;
if FCBOpenIn(&fcb, file) != 0 then
    print("error: cannot open file\n");
    ExitWithError();
end if;

# Counters for each letter
var letterCount: uint32[26];
MemZero(&letterCount as [uint8], @bytesof letterCount);

# Count every letter
var len := FCBExt(&fcb);
while len != 0 loop
    len := len - 1;
    var ch := (FCBGetChar(&fcb) | 32) - 'a';
    if ch >= @sizeof letterCount then
        continue;
    end if;
    letterCount[ch] := letterCount[ch] + 1;
end loop;

# Close the file
var foo := FCBClose(&fcb);

# Print value for each letter
ch := 0;
while ch < @sizeof letterCount loop
    print_char(ch + 'A');
    print(": ");
    print_i32(letterCount[ch]);
    print_nl();
    ch := ch + 1;
end loop;


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

    uint[26] frequency;

    foreach (const buffer; "unixdict.txt".File.byChunk(2 ^^ 15))
        foreach (immutable c; buffer.filter!isAlpha)
            frequency[c.toLower - 'a']++;

    writefln("%(%(%s, %),\n%)", frequency[].chunks(10));
}


proc nonrec main() void:
    file() infile;
    [256] char linebuf;
    [256] word count;
    *char line;
    char c;
    byte i;
    word n;
    channel input text filech;
    channel input text linech;

    for i from 0 upto 255 do count[i] := 0 od;
    line := &linebuf[0];

    open(filech, infile, "unixdict.txt");
    while readln(filech; line) do
        open(linech, line);
        while read(linech; c) do
            i := pretend(c, byte);
            count[i] := count[i] + 1
        od;
        close(linech)
    od;
    close(filech);

    for c from 'A' upto 'Z' do
        i := pretend(c, byte);
        n := count[i] + count[i | 32];
        writeln(c, pretend(i | 32, char), ": ", n:5)
    od
corp


;; bump count when letter added
(define (hash-counter hash key )
		;; (set! key (string-downcase key)) - if ignore case wanted
		(putprop hash (1+ (or (getprop hash key) 0 )) key))

;;  apply to exploded string
;;  and sort result
(define (hash-compare a b) ( < (first a) (first b)))
(define (count-letters hash string)
		(map (curry hash-counter hash) (string->list string))
		(list-sort hash-compare (symbol-plist hash)))


class
	APPLICATION

create
	make

feature {NONE} -- Initialization

	make
			-- Read from the file and print frequencies.
		local
			file: PLAIN_TEXT_FILE
		do
			create file.make_open_read("input.txt")
			file.read_stream(file.count)
			file.close
			across get_frequencies(file.last_string) as f loop
				print(f.key.out + ": " + f.item.out + "%N")
			end
		end

feature -- Access

	get_frequencies (s: STRING): HASH_TABLE[INTEGER, CHARACTER]
			-- Hash table of counts for alphabetic characters in `s'.
		local
			char: CHARACTER
		do
			create Result.make(0)
			across s.area as st loop
				char := st.item
				if char.is_alpha then
					if Result.has(char) then
						Result.force(Result.at(char) + 1, char)
					else
						Result.put (1, char)
					end
				end
			end
		end
end


file = hd(System.argv)

File.read!(file)
|> String.upcase
|> String.graphemes
|> Enum.filter(fn c -> c =~ ~r/[A-Z]/ end)
|> Enum.reduce(Map.new, fn c,acc -> Map.update(acc, c, 1, &(&1+1)) end)
|> Enum.sort_by(fn {_k,v} -> -v end)
|> Enum.each(fn {k,v} -> IO.puts "#{k}  #{v}" end)


%% Implemented by Arjun Sunel
-module(letter_frequency).
-export([main/0, letter_freq/1]).
main() ->
	case  file:read_file("file.txt") of
		{ok, FileData} ->
			letter_freq(binary_to_list(FileData));
		_FileNotExist ->
			io:format("File do not exist~n")
	end.

letter_freq(Data) ->
	lists:foreach(fun(Char) ->
					LetterCount = lists:foldl(fun(Element, Count) ->
											case Element =:= Char of
												true ->
													Count+1;
												false ->
													Count
											end
										end, 0, Data),

					case LetterCount >0 of
						true ->
							io:format("~p	:	~p~n", [[Char], LetterCount]);
						false ->
							io:format("")
					end
				end,  lists:seq(0, 222)).


PROGRAM LETTER

DIM CNT[255]

BEGIN

      OPEN("I",1,"f:\errev30\erre.hlp")

      REPEAT
        GET(#1,A$)
        L%=LEN(A$)
        IF L%>0 THEN
          FOR I%=1 TO L% DO
            A%=ASC(MID$(A$,I%))
            CNT[A%]+=1
          END FOR
        END IF
      UNTIL EOF(1)
      CLOSE(1)

      FOR C%=$41 TO $5A DO
        PRINT(CHR$(C%);CHR$(C%+32);": ";CNT[C%]+CNT[C%+32])
      END FOR

END PROGRAM


-- LetterFrequency.ex
-- Count frequency of each letter in own source code.

include std/console.e
include std/io.e
include std/text.e

sequence letters = repeat(0,26)

sequence content = read_file("LetterFrequency.ex")

content = lower(content)

for i = 1 to length(content) do
	if content[i] > 96 and content[i] < 123 then
		letters[content[i]-96] += 1
	end if
end for

for i = 1 to 26 do
	printf(1,"%s:  %d\n",{i+96,letters[i]})
end for

if getc(0) then end if


let alphabet =
    ['A'..'Z'] |> Set.ofList

let letterFreq (text : string) =
    text.ToUpper().ToCharArray()
    |> Array.filter (fun x -> alphabet.Contains(x))
    |> Seq.countBy (fun x -> x)
    |> Seq.sort

let v = "Now is the time for all good men to come to the aid of the party"

let res = letterFreq v

for (letter, freq) in res do
    printfn "%A, %A" letter freq


USING: hashtables locals io assocs kernel io.encodings.utf8 io.files formatting ;
IN: count-letters

<PRIVATE

: count-from-stream ( -- counts )
  52 <hashtable>
  [ read1 dup ] [ over inc-at ] while
  drop ;

: print-counts ( counts -- )
  [ "%c: %d\n" printf ] assoc-each ;

PRIVATE>

: count-letters ( filename -- )
  utf8 [ count-from-stream ] with-file-reader
    print-counts ;


#APPTYPE CONSOLE

'Open a text file and count the occurrences of each letter.
FUNCTION countBytes(fileName AS STRING)
	DIM c AS STRING
	DIM ascii[]
	DIM handle AS INTEGER = FILEOPEN(fileName, BINARY)
	WHILE NOT FILEEOF(handle)
		c = FILEGETC(handle)
		IF c = "" THEN EXIT WHILE
		ascii[ASC] = ascii[ASC(c)] + 1
	WEND
	FILECLOSE(handle)
	RETURN ascii
END SUB

DIM counters = countBytes(COMMAND(1))
FOR DIM i = LBOUND(counters) TO UBOUND(counters)
	PRINT i, TAB, IIF(i <= 32, i, CHR(i)), TAB, counters[i]
NEXT

PAUSE


create counts 26 cells allot

: freq ( filename -- )
  counts 26 cells erase
  slurp-file bounds do
    i [email protected] 32 or [char] a -
    dup 0 26 within if
      cells counts +
      1 swap +!
    else drop then
  loop
  26 0 do
    cr [char] ' emit  [char] a i + emit  ." ': "
    counts i cells + @ .
  loop ;

s" example.txt" freq


-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Sat May 18 18:09:46

a=./F && make $a && $a < configuration.file
f95 -Wall -ffree-form F.F -o F
          92          21          17          24          82          19          19          22          67           0           2          27          27          57          55          31           1          61          43          60          20           6           2           0          10           0

Compilation finished at Sat May 18 18:09:46


' FB 1.05.0 Win64

Dim a(65 to 90) As Integer  ' array to hold frequency of each letter, all elements zero initially
Dim fileName As String = "input.txt"
Dim s As String
Dim i As Integer
Open fileName For Input As #1

While Not Eof(1)
  Line Input #1, s
  s = UCase(s)
  For i = 0 To Len(s) - 1
    a(s[i]) += 1
  Next
Wend

Close #1

Print "The frequency of each letter in the file "; fileName; " is as follows:"
Print
For i = 65 To 90
  If a(i) > 0 Then
    Print Chr(i); " : "; a(i)
  End If
Next
Print
Print "Press any key to quit"
Sleep


Public Sub Form_Open()
Dim sData As String = File.Load("data.txt")
Dim iCount, iSpaces, iLetters, iOther As Integer
Dim bPunctuation As Boolean

For iCount = 1 To Len(sData)
  If InStr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", UCase(Mid(sData, iCount, 1))) Then
    Inc iLetters
    bPunctuation = True
  End If
   If Mid(sData, icount, 1) = " " Then
    Inc iSpaces
    bPunctuation = True
  End If
  If bPunctuation = False Then Inc iOther
  bPunctuation = False
Next

Message("Text contains " & Len(sData) & " characters\n" & iLetters & " Letters\n" & iSpaces & " Spaces\n" & iOther & " Punctuation, newlines etc.")

End


package main

import (
    "fmt"
    "io/ioutil"
    "sort"
    "unicode"
)

const file = "unixdict.txt"

func main() {
    bs, err := ioutil.ReadFile(file)
    if err != nil {
        fmt.Println(err)
        return
    }
    m := make(map[rune]int)
    for _, r := range string(bs) {
        m[r]++
    }
    // answer is now in m.  sort and format output:
    lfs := make(lfList, 0, len(m))
    for l, f := range m {
        lfs = append(lfs, &letterFreq{l, f})
    }
    sort.Sort(lfs)
    fmt.Println("file:", file)
    fmt.Println("letter  frequency")
    for _, lf := range lfs {
        if unicode.IsGraphic(lf.rune) {
            fmt.Printf("   %c    %7d\n", lf.rune, lf.freq)
        } else {
            fmt.Printf("%U  %7d\n", lf.rune, lf.freq)
        }
    }
}

type letterFreq struct {
    rune
    freq int
}
type lfList []*letterFreq

func (lfs lfList) Len() int { return len(lfs) }
func (lfs lfList) Less(i, j int) bool {
    switch fd := lfs[i].freq - lfs[j].freq; {
    case fd < 0:
        return false
    case fd > 0:
        return true
    }
    return lfs[i].rune < lfs[j].rune
}
func (lfs lfList) Swap(i, j int) {
    lfs[i], lfs[j] = lfs[j], lfs[i]
}


def frequency = { it.inject([:]) { map, value -> map[value] = (map[value] ?: 0) + 1; map } }

frequency(new File('frequency.groovy').text).each { key, value ->
    println "'$key': $value"
}


PROCEDURE Main()
   LOCAL s := hb_MemoRead( Left( __FILE__ , At( ".", __FILE__ )) +"prg")
   LOCAL c, n, i
   LOCAL a := {}

   FOR EACH c IN s
      IF Asc( c ) > 31
         AAdd( a, c )
      ENDIF
   NEXT
   a := ASort( a )
   i := 1
   WHILE i <= Len( a )
      c := a[i] ; n := 1
      i++
      IF i < Len(a) .AND. c == a[i]
         WHILE c == a[i]
            n++ ; i++
         END
      ENDIF
      ?? "'" + c + "'" + "=" + hb_NtoS( n ) + " "
   END

   RETURN


import Data.List (group,sort)
import Control.Arrow ((&&&))
main = interact (show . map (head &&& length) . group . sort)


link printf

procedure main(A)
every PrintCount(CountLetters(!A))
end

procedure CountLetters(fn)  #: Return case insensitive count of letters
   K := table(0)
   if f := open(fn,"r") then {
      every c := !map(|read(f)) do
         if any(&lcase,c) then K[c] +:= 1
      close(f)
      return K
      }
   else write(&errout,"Unable to open file ",fn)
end

procedure PrintCount(T)    #: Print the letters
every c := key(T) do
   printf("%s - %d\n",c,T[c])
end


100 PROGRAM "Letters.bas"
110 NUMERIC LETT(65 TO 90)
120 FOR I=65 TO 90
130   LET LETT(I)=0
140 NEXT
150 LET EOF=0
160 OPEN #1:"list.txt"
170 WHEN EXCEPTION USE IOERROR
180   DO
190     GET #1:A$
200     LET A$=UCASE$(A$)
210     IF A$>="A" AND A$<="Z" THEN LET LETT(ORD(A$))=LETT(ORD(A$))+1
220   LOOP UNTIL EOF
230 END WHEN
240 FOR I=65 TO 90
250   PRINT CHR$(I);":";LETT(I),
260 NEXT
270 HANDLER IOERROR
280   LET EOF=-1
290   CLOSE #1
300   CONTINUE
310 END HANDLER


ltrfreq=: 3 : 0
  letters=. u: 65 + i.26  NB. upper case letters
  <: #/.~ letters (, -. -.~) toupper fread y
)


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class LetterFreq {
	public static int[] countLetters(String filename) throws IOException{
		int[] freqs = new int[26];
		BufferedReader in = new BufferedReader(new FileReader(filename));
		String line;
		while((line = in.readLine()) != null){
			line = line.toUpperCase();
			for(char ch:line.toCharArray()){
				if(Character.isLetter(ch)){
					freqs[ch - 'A']++;
				}
			}
		}
		in.close();
		return freqs;
	}

	public static void main(String[] args) throws IOException{
		System.out.println(Arrays.toString(countLetters("filename.txt")));
	}
}


(function(txt) {

    var cs = txt.split(''),
        i = cs.length,
        dct =  {},
        c = '',
        keys;

    while (i--) {
        c = cs[i];
        dct[c] = (dct[c] || 0) + 1;
    }

    keys = Object.keys(dct);
    keys.sort();
    return keys.map(function (c) { return [c, dct[c]]; });

})("Not all that Mrs. Bennet, however, with the assistance of her five\
daughters, could ask on the subject, was sufficient to draw from her\
husband any satisfactory description of Mr. Bingley. They attacked him\
in various ways--with barefaced questions, ingenious suppositions, and\
distant surmises; but he eluded the skill of them all, and they were at\
last obliged to accept the second-hand intelligence of their neighbour,\
Lady Lucas. Her report was highly favourable. Sir William had been\
delighted with him. He was quite young, wonderfully handsome, extremely\
agreeable, and, to crown the whole, he meant to be at the next assembly\
with a large party. Nothing could be more delightful! To be fond of\
dancing was a certain step towards falling in love; and very lively\
hopes of Mr. Bingley's heart were entertained.");


# Input: an array of strings.
# Output: an object with the strings as keys,
# the values of which are the corresponding frequencies.
def counter:
  reduce .[] as $item ( {}; .[$item] += 1 ) ;

# For neatness we sort the keys:
explode | map( [.] | implode ) | counter | . as $counter
 | keys | sort[] | [., $counter[.] ]


using DataStructures

function letterfreq(file::AbstractString; fltr::Function=(_) -> true)
    sort(Dict(counter(filter(fltr, read(file, String)))))
end

display(letterfreq("src/Letter_frequency.jl"; fltr=isletter))


// version 1.1.2

import java.io.File

fun main(args: Array<String>) {
    val text = File("input.txt").readText().toLowerCase()
    val letterMap = text.filter { it in 'a'..'z' }.groupBy { it }.toSortedMap()
    for (letter in letterMap) println("${letter.key} = ${letter.value.size}")
    val sum = letterMap.values.sumBy { it.size }
    println("\nTotal letters = $sum")
}


#!/bin/ksh

# Count the occurrences of each character

 ######
# main #
 ######

typeset -iA freqCnt
while read; do
	for ((i=0; i<${#REPLY}; i++)); do
		(( freqCnt[${REPLY:i:1}]++ ))
	done
done < $0		## Count chars of this code file

for ch in "${!freqCnt[@]}"; do
	[[ ${ch} == ?(\S) ]] && print -- "${ch}  ${freqCnt[${ch}]}"
done


{script
// W.frequency is added to the lambdatalk dictionary via the {script ...} special form

LAMBDATALK.DICT['W.frequency'] = function() {

// 1) simply copied from the rosetta.org #Javascript entry
  var frequency = function(txt) {
    var cs  = txt.split(''),
          i = cs.length,
        dct = {},
          c = '';
    while (i--) {
        c = cs[i];
        dct[c] = (dct[c] || 0) + 1;
    }
    var keys = Object.keys(dct);
    keys.sort();
    return keys.map(function (c) { return [c, dct[c]]; });
  };

// 2) then interfaced with lambdatalk
  var args = arguments[0].trim().replace( /\s+/g, "␣" );

  var output = frequency( args );

  for (var a=[], b=[], i=0; i< output.length; i++) {
    a.push( output[i][0] );
    b.push( output[i][1] );
  }

  var pair = "{cons {A.new " + a.join(" ") +
                 "} {A.new " + b.join(" ") + "}}"

  return LAMBDATALK.eval_forms( pair );
};
}

{def S3
Not all that Mrs. Bennet, however, with the assistance of her five daughters, could ask on the subject, was sufficient to draw from her husband any satisfactory description of Mr. Bingley. They attacked him in various ways--with barefaced questions, ingenious suppositions, and distant surmises; but he eluded the skill of them all, and they were at last obliged to accept the second-hand intelligence of their neighbour, Lady Lucas. Her report was highly favourable. Sir William had been delighted with him. He was quite young, wonderfully handsome, extremely agreeable, and, to crown the whole, he meant to be at the next assembly with a large party. Nothing could be more delightful! To be fond of dancing was a certain step towards falling in love; and very lively hopes of Mr. Bingley's heart were entertained.
}
-> S3
{def S3.freq {W.frequency {S3}}}
-> S3.freq

characters:  {car {S3.freq}}
->  [!,',,,-,.,;,B,H,L,M,N,S,T,W,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,␣]

frequencies: {cdr {S3.freq}}
-> [1,1,13,3,9,2,3,2,2,3,2,1,2,1,53,13,17,29,82,17,16,36,44,1,3,34,11,41,40,8,2,35,39,55,20,7,17,2,16,132]
}


val .countLetters = f(.s) {
    for[=h{}] .s2 in split(replace(.s, RE/\P{L}/)) {
        _for[.s2; 0] += 1
    }
}

val .counts = .countLetters(readfile "./fuzz.txt")
writeln join "\n", map f(.k) $"\.k;: \.counts[.k];", keys .counts


local(
	str 	= 'Hello world!',
	freq	= map
)
// as a loop. arguably quicker than query expression
loop(#str->size) => {
	#freq->keys !>> #str->get(loop_count) ?
		#freq->insert(#str->get(loop_count) = #str->values->find(#str->get(loop_count))->size)
}

// or
local(
	str 	= 'Hello world!',
	freq	= map
)
// as query expression, less code
with i in #str->values where #freq->keys !>> #i do => {
	#freq->insert(#i = #str->values->find(#i)->size)
}

// output #freq
with elem in #freq->keys do => {^
	'"'+#elem+'": '+#freq->find(#elem)+'\r'
^}


    open "text.txt" for input as #i
        txt$ =input$( #i, lof( #i))
        Le =len( txt$)
    close #i

    dim LetterFreqy( 255)

    '   txt$ =upper$( txt$)

    for i =1 to Le
        char =asc( mid$( txt$, i, 1))
        if char >=32 then LetterFreqy( char) =LetterFreqy( char) +1
    next i

    for j =32 to 255
        if LetterFreqy( j) <>0 then print " Character #"; j, "("; chr$( j);_
         ") appeared "; using( "##.##", 100 *LetterFreqy( j) /Le); "% of the time."
    next j

    end


-- Return entire contents of named file
function readFile (filename)
  local file = assert(io.open(filename, "r"))
  local contents = file:read("*all")
  file:close()
  return contents
end

-- Return a closure to keep track of letter counts
function tally ()
  local t = {}

  -- Add x to tally if supplied, return tally list otherwise
  local function count (x)
    if x then
      if t[x] then
        t[x] = t[x] + 1
      else
        t[x] = 1
      end
    else
      return t
    end
  end

  return count
end

-- Main procedure
local letterCount = tally()
for letter in readFile(arg[1]):gmatch("%a") do
  letterCount(letter)
end
for k, v in pairs(letterCount()) do
  print(k, v)
end


document file1$={Open a text file and count the occurrences of each letter.
		Some of these programs count all characters (including punctuation), but some only count letters A to Z
		}
const Ansi=3, nl$=chr$(13)+chr$(10), Console=-2
save.doc file1$, "checkdoc.txt", Ansi
open "checkdoc.txt" for input as F
buffer onechar as byte
m=0
dim m(65 to 90)
while not eof(#F)
	get #F, onechar
	a$=chr$(eval(onechar,0))
	if a$ ~ "[A-Za-z]" then
		m++
		m(asc(ucase$(a$)))++
	end if
end while
close #F
document Export$
for i=65 to 90
	if m(i)>0 then Export$=format$("{0} - {1:2:4}%",chr$(i),m(i)/m*100)+nl$
next
print #Console, Export$
clipboard Export$


function u = letter_frequency(t)
	if ischar(t)
		t = abs(t);
	end;
	A = sparse(t+1,1,1,256,1);
	printf('"%c":%i\n',[find(A)-1,A(A>0)]')
end


// define a list to hold characters and amounts
characters = list()
amounts = list()

// define the alphabet as a string to check only letters and numbers
alpha = "abcdefghijklmnopqrstuvwxyz0123456789"

// get the filename as an argument
fname = args[len(args) - 1]

// read the entire file into a string
contents = new(Nanoquery.IO.File, fname).readAll()

// loop through all the characters in the array
for i in range(0, len(contents) - 1)
	// get the character to check
	toCheck = str(contents[i]).toLowerCase()

	// check if the current character is in the array
	if ((alpha .contains. toCheck) && (characters .contains. toCheck))
		// if it's there, increment its amount
		index = characters[toCheck]
		amounts[index] = amounts[index] + 1
	else
		if (alpha .contains. toCheck)
			// if it's not, add it
			append characters toCheck
			append amounts 0
		end
	end if
end for

// output the amounts
println format("%-20s %s", "Character", "Amount")
println "=" * 30
for i in range(0, len(characters) - 1)
	println format("%-20s %d", characters[i], amounts[i])
end for


/* NetRexx ************************************************************
* 22.05.2013 Walter Pachl  translated from REXX
**********************************************************************/
options replace format comments java crossref symbols nobinary

  parse arg dsn .
  if dsn = '' then
    dsn = 'test.txt'
  cnt=0
  totChars=0                         /*count of the total num of chars*/
  totLetters=0                       /*count of the total num letters.*/
  indent=' '.left(20)                /*used for indentation of output.*/
  lines = scanFile(dsn)
  loop l_ = 1 to lines[0]
    line = lines[l_]

    Say '>'line'<' line.length       /* that's in test.txt            */
    /*
    lrx=left_right(line)
    Parse lrx leftx rightx
    Say ' 'leftx
    Say ' 'rightx
    */
    loop k=1 for line.length()       /*loop over characters           */
      totChars=totChars+1            /*Increment total number of chars*/
      c=line.substr(k,1)             /*get character number k         */
      cnt[c]=cnt[c]+1                /*increment the character's count*/
      End
    end l_

  w=totChars.length                  /*used for right-aligning counts.*/
  say 'file -----' dsn "----- has" lines[0] 'records.'
  say 'file -----' dsn "----- has" totChars 'characters.'
  Loop L=0 to 255                    /* display nonzero letter counts */
    c=l.d2c                          /* the character in question     */
    if cnt[c]>0 & c.datatype('M')>0 Then Do /* was found in the file  */
                                     /* and is a latin letter         */
      say indent "(Latin) letter " c 'count:' cnt[c].right(w) /* tell */
      totLetters=totLetters+cnt[c]   /* increment number of letters   */
      End
    End

  say 'file -----' dsn "----- has" totLetters '(Latin) letters.'
  say '                           other charactes follow'
  other=0
  loop m=0 to 255                    /* now for non-letters           */
    c=m.d2c                          /* the character in question     */
    y=c.c2x                          /* the hex representation        */
    if cnt[c]>0 & c.datatype('M')=0 Then Do /* was found in the file  */
                                     /* and is not a latin letter     */
      other=other+cnt[c]             /* increment count               */
      _=cnt[c].right(w)              /* prepare output of count       */
      select                         /*make the character viewable.   */
       when c<<' ' | m==255 then say indent "'"y"'x character count:" _
       when c==' '          then say indent "blank character count:" _
       otherwise                 say indent "   " c 'character count:' _
       end
     end
   end
  say 'file -----' dsn "----- has" other 'other characters.'
  say 'file -----' dsn "----- has" totLetters 'letters.'

-- Read a file and return contents as a Rexx indexed string
method scanFile(dsn) public static returns Rexx

  fileLines = ''
  do
    inFile = File(dsn)
    inFileScanner = Scanner(inFile)
    loop l_ = 1 while inFileScanner.hasNext()
      fileLines[0] = l_
      fileLines[l_] = inFileScanner.nextLine()
      end l_
    inFileScanner.close()

  catch ex = FileNotFoundException
    ex.printStackTrace
  end

  return fileLines


F left_fact(n)
   BigInt result = 0
   BigInt factorial = 1
   L(i) 1 .. n
      result += factorial
      factorial *= i
   R result

print(‘First 11 left factorials:’)
print((0..10).map(i -> left_fact(i)))
print("\n20 through 110 (inclusive) by tens:")
L(i) (20..110).step(10)
   print(left_fact(i))
print("\nDigits in 1,000 through 10,000 by thousands:")
print((1000..10000).step(1000).map(i -> String(left_fact(i)).len))


import tables, os

var t = initCountTable[char]()
for l in paramStr(1).lines:
  for c in l:
    t.inc(c)
echo t


use IO;

bundle Default {
  class Test {
    function : Main(args : String[]) ~ Nil {
      freqs := CountLetters("filename.txt");
      for(i := 'A'; i < 'Z'; i += 1;) {
        Console->Print(i->As(Char))->Print("=>")->PrintLine(freqs[i - 'A']);
      };
    }

    function : CountLetters(filename : String) ~ Int[] {
      freqs := Int->New[26];
      reader := FileReader->New(filename);
      while(reader->IsEOF() <> true) {
        line := reader->ReadString()->ToUpper();
        each(i : line) {
          ch := line->Get(i);
          if(ch->IsChar()){
            index := ch - 'A';
            freqs[index] := freqs[index] + 1;
          };
        };
      };
      reader->Close();

      return freqs;
    }
  }
}


# set the precision of LONG LONG INT - large enough for !n up to ! 10 000 #
PR precision 36000 PR
# stores left factorials in an array #
# we calculate the left factorials, storing their values in the "values" array #
# if step is <= 1, we store we store every left factorial, otherwise we store !x when x MOD step = 0 #
# note this means values[ 0 ] is always !0 #
PROC get left factorials = ( REF[]LONG LONG INT values, INT step )VOID:
     BEGIN
         INT store position        := LWB values;
         INT max values            := UPB values;
         LONG LONG INT result      := 0;
         LONG LONG INT factorial k := 1;
         FOR k FROM 0
         WHILE
             IF IF step <= 1 THEN TRUE ELSE k MOD step = 0 FI THEN
                 values[ store position ] := result;
                 store position +:= 1
             FI;
             store position <= max values
         DO
             result      +:= factorial k;
             factorial k *:= ( k + 1 )
         OD
     END # get left factorials # ;

# returns the number of digits in n #
OP DIGITCOUNT = ( LONG LONG INT n )INT:
   BEGIN
        INT result := 1;
        LONG LONG INT v := ABS n;
        WHILE v > 100 000 000 DO
            result +:= 8;
            v OVERAB 100 000 000
        OD;
        WHILE v > 10 DO
            result +:= 1;
            v OVERAB 10
        OD;
        result
   END # DIGITCOUNT # ;

BEGIN
    print( ( "!n for n = 0(1)10", newline ) );
    [ 0 : 10 ]LONG LONG INT v;
    get left factorials( v, 1 );
    FOR i FROM 0 TO UPB v DO
        print( ( whole( v[ i ], 0 ), newline ) )
    OD
END;

BEGIN
    print( ( "!n for n = 20(10)110", newline ) );
    [ 0 : 11 ]LONG LONG INT v;
    get left factorials( v, 10 );
    FOR i FROM 2 TO UPB v DO
        print( ( whole( v[ i ], 0 ), newline ) )
    OD
END;

BEGIN
    print( ( "digit counts of !n for n = 1000(1000)10 000", newline ) );
    [ 0 : 10 ]LONG LONG INT v;
    get left factorials( v, 1 000 );
    FOR i FROM 1 TO UPB v DO
        print( ( whole( DIGITCOUNT v[ i ], 0 ), newline ) )
    OD
END


#import <Foundation/Foundation.h>

int main (int argc, const char *argv[]) {
  @autoreleasepool {

    NSData *data = [NSData dataWithContentsOfFile:@(argv[1])];
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSCountedSet *countedSet = [[NSCountedSet alloc] init];
    NSUInteger len = [string length];
    for (NSUInteger i = 0; i < len; i++) {
      unichar c = [string characterAtIndex:i];
      if ([[NSCharacterSet letterCharacterSet] characterIsMember:c])
        [countedSet addObject:@(c)];
    }
    for (NSNumber *chr in countedSet) {
      NSLog(@"%C => %lu", (unichar)[chr integerValue], [countedSet countForObject:chr]);
    }

  }
  return 0;
}


let () =
  let ic = open_in Sys.argv.(1) in
  let base = int_of_char 'a' in
  let arr = Array.make 26 0 in
  try while true do
    let c = Char.lowercase(input_char ic) in
    let ndx = int_of_char c - base in
    if ndx < 26 && ndx >= 0 then
      arr.(ndx) <- succ arr.(ndx)
  done
  with End_of_file ->
    close_in ic;
    for i=0 to 25 do
      Printf.printf "%c -> %d\n" (char_of_int(i + base)) arr.(i)
    done


#!/usr/bin/gawk -Mf
function left_factorial(num) {
	result=0
	adder=1
	if (num==0) return(0)
	for (k = 1; k <=num; k++) {
		result = result + adder
		adder = adder * k
	}
	return(result)
}

BEGIN {
	for (i = 0; i <= 10; i++) {
		print "!" i " = " left_factorial(i)
	}
	for (i = 20; i<= 110; i+=10) {
		print "!" i " = " left_factorial(i)
	}
	for (i = 1000; i<= 10000; i+=1000) {
		print "!" i " has " length(left_factorial(i)) " digits"
	}
      }


      INSTALL @lib$+"BB4WMAPMLIB" : PROCMAPM_Init : MAPM_Dec%=200

      Result$="0" : A$="1"
      FOR I%=0 TO 10000
        IF I% Result$=FNMAPM_Add(Result$,A$) : A$=FNMAPM_Multiply(A$,STR$I%)

        IF I% < 111 IF I% MOD 10 = 0 OR I% < 11 PRINT "!";I% " = " FNMAPM_FormatDec(Result$,0)

        IF I% > 999 IF I% MOD 1000 = 0 PRINT "!";I% " has " LENFNMAPM_FormatDec(Result$,0) " digits"
      NEXT
      END


( ( leftFact
  =   result factorial i
    .   0:?result
      & 1:?factorial
      & 0:?i
      &   whl
        ' ( !i+1:~>!arg:?i
          & !factorial+!result:?result
          & !factorial*!i:?factorial
          )
      & !result
  )
& ( iterate
  =   from to step c fun
    .   !arg:(?from.?to.?step.?fun)
      & !from+-1*!step:?from
      & !step:?c
      &   whl
        ' ( !step+!from:~>!to:?from
          & !fun$(leftFact$!from)
          )
      &
  )
& out$"First 11 left factorials:"
& iterate$(0.10.1.out)
& out$"
20 through 110 (inclusive) by tens:"
& iterate$(20.110.10.out)
& out$"
Digits in 1,000 through 10,000 by thousands:"
&   iterate
  $ ( 1000
    . 10000
    . 1000
    . ([email protected](!arg:? [?L)&out$!L)
    )
)


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

void mpz_left_fac_ui(mpz_t rop, unsigned long op)
{
    mpz_t t1;
    mpz_init_set_ui(t1, 1);
    mpz_set_ui(rop, 0);

    size_t i;
    for (i = 1; i <= op; ++i) {
        mpz_add(rop, rop, t1);
        mpz_mul_ui(t1, t1, i);
    }

    mpz_clear(t1);
}

size_t mpz_digitcount(mpz_t op)
{
    /* mpz_sizeinbase can not be trusted to give accurate base 10 length */
    char *t    = mpz_get_str(NULL, 10, op);
    size_t ret = strlen(t);
    free(t);
    return ret;
}

int main(void)
{
    mpz_t t;
    mpz_init(t);
    size_t i;

    for (i = 0; i <= 110; ++i) {
        if (i <= 10 || i % 10 == 0) {
            mpz_left_fac_ui(t, i);
            gmp_printf("!%u = %Zd\n", i, t);
        }
    }

    for (i = 1000; i <= 10000; i += 1000) {
        mpz_left_fac_ui(t, i);
        printf("!%u has %u digits\n", i, mpz_digitcount(t));
    }

    mpz_clear(t);
    return 0;
}


(define source (bytes->string (file->bytestream "letter_frequency.scm"))) ; utf-8
(define dict (lfold (lambda (ff char)
                     (put ff char (+ 1 (get ff char 0))))
               {}
               (str-iter source)))
; that's all.

; just print the dictionary in human readable format:
(for-each (lambda (kv)
            (let* ((key value kv))
               (case key
                  (#\newline
                     (display "NEWLINE"))
                  (#\tab
                     (display "TAB"))
                  (#\space
                     (display "SPACE"))
                  ((< key #\space) => (lambda (_)
                     (display "char ") (display key)))
                  (else
                     (display (string key))))
               (display " --> ")
               (display value))
            (print))
   (ff->alist dict))


indexbase 0

sys a,e,i,c[255]

string s=getfile "t.txt"

e=len s

for i=1 to e
  a=asc(s,i)
  ++c(a)
next

cr=chr(13)+chr(10)
pr="Char Frequencies" cr cr
for i=32 to 255
  pr+=chr(i) chr(9) c(i) cr
next

print pr
'putfile "CharCount.txt",pr


using System;
using System.Numerics;

namespace LeftFactorial
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(string.Format("!{0} = {1}", i, LeftFactorial(i)));
            }

            for (int j = 20; j <= 110; j += 10)
            {
                Console.WriteLine(string.Format("!{0} = {1}", j, LeftFactorial(j)));
            }

            for (int k = 1000; k <= 10000; k += 1000)
            {
                Console.WriteLine(string.Format("!{0} has {1} digits", k, LeftFactorial(k).ToString().Length));
            }

            Console.ReadKey();
        }

        private static BigInteger Factorial(int number)
        {
            BigInteger accumulator = 1;

            for (int factor = 1; factor <= number; factor++)
            {
                accumulator *= factor;
            }

            return accumulator;
        }

        private static BigInteger LeftFactorial(int n)
        {
            BigInteger result = 0;

            for (int i = 0; i < n; i++)
            {
                result += Factorial(i);
            }

            return result;
        }
    }
}


#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
using namespace std;

#if 1 // optimized for 64-bit architecture
typedef unsigned long usingle;
typedef unsigned long long udouble;
const int word_len = 32;
#else // optimized for 32-bit architecture
typedef unsigned short usingle;
typedef unsigned long udouble;
const int word_len = 16;
#endif

class bignum {
private:
    // rep_.size() == 0 if and only if the value is zero.
    // Otherwise, the word rep_[0] keeps the least significant bits.
    vector<usingle> rep_;
public:
    explicit bignum(usingle n = 0) { if (n > 0) rep_.push_back(n); }
    bool equals(usingle n) const {
        if (n == 0) return rep_.empty();
        if (rep_.size() > 1) return false;
        return rep_[0] == n;
    }
    bignum add(usingle addend) const {
        bignum result(0);
        udouble sum = addend;
        for (size_t i = 0; i < rep_.size(); ++i) {
            sum += rep_[i];
            result.rep_.push_back(sum & (((udouble)1 << word_len) - 1));
            sum >>= word_len;
        }
        if (sum > 0) result.rep_.push_back((usingle)sum);
        return result;
    }
    bignum add(const bignum& addend) const {
        bignum result(0);
        udouble sum = 0;
        size_t sz1 = rep_.size();
        size_t sz2 = addend.rep_.size();
        for (size_t i = 0; i < max(sz1, sz2); ++i) {
            if (i < sz1) sum += rep_[i];
            if (i < sz2) sum += addend.rep_[i];
            result.rep_.push_back(sum & (((udouble)1 << word_len) - 1));
            sum >>= word_len;
        }
        if (sum > 0) result.rep_.push_back((usingle)sum);
        return result;
    }
    bignum multiply(usingle factor) const {
        bignum result(0);
        udouble product = 0;
        for (size_t i = 0; i < rep_.size(); ++i) {
            product += (udouble)rep_[i] * factor;
            result.rep_.push_back(product & (((udouble)1 << word_len) - 1));
            product >>= word_len;
        }
        if (product > 0)
            result.rep_.push_back((usingle)product);
        return result;
    }
    void divide(usingle divisor, bignum& quotient, usingle& remainder) const {
        quotient.rep_.resize(0);
        udouble dividend = 0;
        remainder = 0;
        for (size_t i = rep_.size(); i > 0; --i) {
            dividend = ((udouble)remainder << word_len) + rep_[i - 1];
            usingle quo = (usingle)(dividend / divisor);
            remainder = (usingle)(dividend % divisor);
            if (quo > 0 || i < rep_.size())
                quotient.rep_.push_back(quo);
        }
        reverse(quotient.rep_.begin(), quotient.rep_.end());
    }
};

ostream& operator<<(ostream& os, const bignum& x);

ostream& operator<<(ostream& os, const bignum& x) {
    string rep;
    bignum dividend = x;
    bignum quotient;
    usingle remainder;
    while (true) {
        dividend.divide(10, quotient, remainder);
        rep += (char)('0' + remainder);
        if (quotient.equals(0)) break;
        dividend = quotient;
    }
    reverse(rep.begin(), rep.end());
    os << rep;
    return os;
}

bignum lfact(usingle n);

bignum lfact(usingle n) {
    bignum result(0);
    bignum f(1);
    for (usingle k = 1; k <= n; ++k) {
        result = result.add(f);
        f = f.multiply(k);
    }
    return result;
}

int main() {
    for (usingle i = 0; i <= 10; ++i) {
        cout << "!" << i << " = " << lfact(i) << endl;
    }

    for (usingle i = 20; i <= 110; i += 10) {
        cout << "!" << i << " = " << lfact(i) << endl;
    }

    for (usingle i = 1000; i <= 10000; i += 1000) {
        stringstream ss;
        ss << lfact(i);
        cout << "!" << i << " has " << ss.str().size()
            << " digits." << endl;
    }
}


program letterFrequency(input, output);
var
	chart: array[char] of 0..maxInt value [otherwise 0];
	c: char;
begin
	{ parameter-less EOF checks for EOF(input) }
	while not EOF do
	begin
		read(c);
		chart[c] := chart[c] + 1
	end;

	{ now, chart[someLetter] gives you the letter’s frequency }
end.


(ns left-factorial
  (:gen-class))

(defn left-factorial [n]
  " Compute by updating the state [fact summ] for each k, where k equals 1 to n
    Update is next state is [k*fact (summ+k)"
  (second
    (reduce (fn [[fact summ] k]
              [(*' fact k) (+ summ fact)])
            [1 0] (range 1 (inc n)))))

(doseq [n (range 11)]
  (println (format "!%-3d = %5d" n (left-factorial n))))

(doseq [n (range 20 111 10)]
(println (format "!%-3d = %5d" n (biginteger (left-factorial n)))))

(doseq [n (range 1000 10001 1000)]
  (println (format "!%-5d has %5d digits" n (count (str (biginteger (left-factorial n)))))))


(defun fact (n)
  (reduce #'* (loop for i from 1 to n collect i)))

(defun left-fac (n)
  (reduce #'+ (loop for i below n collect (fact i))))

(format t "0 -> 10~&")
(format t "~a~&" (loop for i upto 10 collect (left-fac i)))
(format t "20 -> 110 by 10~&")
(format t "~{~a~&~}" (loop for i from 20 upto 110 by 10 collect (left-fac i)))
(format t "1000 -> 10000 by 1000~&")
(format t "~{~a digits~&~}" (loop for i from 1000 upto 10000 by 1000 collect (length (format nil "~a" (left-fac i)))))


while (<>) { $cnt{lc chop}++ while length }
print "$_: ", $cnt{$_}//0, "\n" for 'a' .. 'z';


with javascript_semantics
sequence lc = repeat(0,#7E)
--string text = get_text(command_line()[$])
string text = join(unix_dict(17))
for i=1 to length(text) do
    integer ch = text[i]
    if ch=-1 then exit end if
    if ch>=' ' and ch<#7F then
        lc[ch] += 1
    end if
end for

integer count = 0
for i=' ' to #7E do
    if lc[i]!=0 then
        count = mod(count+1,10)
        printf(1,"'%c': %-2d%s",{i,lc[i],iff(count=0?"\n":"  ")})
    end if
end for


import std.stdio, std.bigint, std.range, std.algorithm, std.conv;

BigInt leftFact(in uint n) pure nothrow /*@safe*/ {
    BigInt result = 0, factorial = 1;
    foreach (immutable i; 1 .. n + 1) {
        result += factorial;
        factorial *= i;
    }
    return result;
}

void main() {
    writeln("First 11 left factorials:\n", 11.iota.map!leftFact);
    writefln("\n20 through 110 (inclusive) by tens:\n%(%s\n%)",
             iota(20, 111, 10).map!leftFact);
    writefln("\nDigits in 1,000 through 10,000 by thousands:\n%s",
             iota(1_000, 10_001, 1_000).map!(i => i.leftFact.text.length));
}


(lib 'bigint)
(define (!n n)
	(if (zero? n)  0
	(+ (!n (1- n)) (factorial (1- n)))))
(remember '!n)


defmodule LeftFactorial do
  def calc(0), do: 0
  def calc(n) do
    {result, _factorial} = Enum.reduce(1..n, {0, 1}, fn i,{res, fact} ->
      {res + fact, fact * i}
    end)
    result
  end
end

Enum.each(0..10, fn i ->
  IO.puts "!#{i} = #{LeftFactorial.calc(i)}"
end)
Enum.each(Enum.take_every(20..110, 10), fn i ->
  IO.puts "!#{i} = #{LeftFactorial.calc(i)}"
end)
Enum.each(Enum.take_every(1000..10000, 1000), fn i ->
  digits = LeftFactorial.calc(i) |> to_char_list |> length
  IO.puts "!#{i} has #{digits} digits"
end)


0 255 repeat var ascCodes

"unixdict.txt" "r" fopen var file

file 0 < not
if
	true
	while
		file fgets
		dup 0 < not
		if
			len 1 swap 2 tolist
			for
				var i
				i get ascCodes over get 1 + rot set var ascCodes
			endfor
			drop
			true
		else
			drop
			false
		endif
	endwhile

	ascCodes len
	for
		var i
		i get
		if
			i tochar print " = " print i get print nl
		endif
	endfor
	file fclose
endif


go =>
  % removing '\n' first
  Chars = delete_all(read_file_chars("unixdict.txt"),'\n'),
  M = letter_freq(Chars),
  println(M.sort_map(values).reverse).

% Get the letter frequency
letter_freq(S) = Map =>
  Map = new_map(),
  foreach(C in S)
    Map.put(C,Map.get(C,0)+1)
  end.

% Different sorting function on maps
sort_map(Map,values) = [K=V:_=(K=V) in sort([V=(K=V): K=V in Map])].
sort_map(Map,keys)   = sort([KV : KV in Map]).
sort_map(Map)        = sort_map(Map,keys).


// Generate Sequence of Left Factorials: Nigel Galloway, March 5th., 2019.
let LF=Seq.unfold(fun (Σ,n,g)->Some(Σ,(Σ+n,n*g,g+1I))) (0I,1I,1I)


USING: formatting fry io kernel math math.factorials
math.functions math.parser math.ranges sequences ;
IN: rosetta-code.left-factorials

: left-factorial ( n -- m ) <iota> [ n! ] map-sum ;

: print-left-factorials ( seq quot -- )
    '[
        dup left-factorial @
        [ number>string "!" prepend ] dip
        "%6s   %-6d\n" printf
    ] each nl ; inline

: digit-count ( n -- count ) log10 >integer 1 + ;

: part1 ( -- ) 11 <iota> [ ] print-left-factorials ;

: part2 ( -- ) 20 110 10 <range> [ ] print-left-factorials ;

: part3 ( -- )
    "Number of digits for" print
    1,000 10,000 1,000 <range>
    [ digit-count ] print-left-factorials ;

: main ( -- ) part1 part2 part3 ;

MAIN: main


36000 CONSTANT #DIGITS  \ Enough for !10000
CREATE S #DIGITS ALLOT  S #DIGITS ERASE  VARIABLE S#
CREATE F #DIGITS ALLOT  F #DIGITS ERASE  VARIABLE F#
1 F C!  1 F# !  \ F = 1 = 0!

\ "Bignums": represented by two cells on the stack:
\ 1) An address pointing to the least-significant unit
\ 2) An integer size representing the number of character-size units
: mod/   /mod swap ;
: B+ ( addr u addr' u' -- u'')  \ Add the second "bignum" into the first
   over + >R  -rot over + >R ( addr' addr R:end' R:end)
   swap >R 0 over R>  ( addr 0 addr addr' R:end' R:end)
   \ 0: Assume second has equal or more digits, as in our problem
   BEGIN over [email protected] < WHILE  \ 1: add all digits from S
     dup >R [email protected] swap dup >R [email protected] ( addr c a a' R:end' R:end R:addr'* R:addr*)
     + +  10 mod/ [email protected] C!  R> 1+ R> 1+
   REPEAT R> drop  ( addr c addr* addr'* R:end')
   BEGIN dup [email protected] < WHILE   \ 2: add any remaining digits from F
     dup >R [email protected] swap >R        ( addr c a' R:end' R:addr'* R:addr*)
     +    10 mod/ [email protected] C!  R> 1+ R> 1+
   REPEAT R> drop drop  ( addr c addr*)
   BEGIN over WHILE       \ 3: add any carry digits
     >R 10 mod/ ( addr m d R:addr*) [email protected] C! R> 1+
   REPEAT  rot - nip ;  \ calculate travel distance, discard 0 carry
: B* ( addr u u' -- u'')  \ Multiply "bignum" inplace by U'
   0 2swap over >R dup >R bounds  ( u' 0 addr+u addr R:addr R:u)
   DO ( u' c) over I [email protected] * +  10 mod/ I C! LOOP
   nip R> BEGIN ( c u) over WHILE  \ insert carry, may have multiple digits
     >R  10 mod/  [email protected] swap R> [email protected] + ( m u d addr+u R:addr) C!  1+
   REPEAT  nip R> ( u'' addr) drop ;
: .B ( addr u)  over +  BEGIN 1-  \ print bignum
     dup [email protected] [char] 0 + EMIT  over over >=
   UNTIL  drop drop ;
: .!n   0 <# #s [char] ! hold #> 6 over - spaces type space ;
: REPORT ( n)
   dup 10 <=  over dup  20 111 within  swap 10 mod 0= and or
   IF .!n [char] = emit space S S# @ .B cr
   ELSE dup 1000 mod 0=
     IF .!n ." has " S# @ . ." digits" cr
     ELSE drop THEN
   THEN ;
: GO   0 REPORT
   1 BEGIN dup 10000 <=
   WHILE
     S S# @  F F# @      B+ S# !
     dup REPORT
     dup     F F# @  rot B* F# !
   1+ REPEAT  drop ;


      MODULE LAIROTCAF	!Calculates "left factorials".
       CONTAINS		!The usual suspects.
        INTEGER*8 FUNCTION FACT(N)	!Factorial, the ordinary.
         INTEGER N	!The number won't ever get far.
         INTEGER I	!The stepper.
          FACT = 1	!Here we go.
          DO I = 2,N		!Does nothing for N < 2.
            FACT = FACT*I		!Perhaps this overflows.
            IF (FACT.LE.0) STOP "Factorial: Overflow!"	!Two's complement arithmetic.
          END DO		!No longer any IF OVERFLOW tests.
        END FUNCTION FACT	!Simple enough.

        INTEGER*8 FUNCTION LFACT(N)	!Left factorial.
         INTEGER N	!This number won't get far either.
         INTEGER K	!A stepper.
          LFACT = 0	!Here we go.
          DO K = 0,N - 1	!Apply the definition.
            LFACT = LFACT + FACT(K)	!Perhaps this overflows.
            IF (LFACT.LE.0) STOP "Lfact: Overflow!"	!Unreliable test.
          END DO		!On to the next step in the summation.
        END FUNCTION LFACT	!No attempts at saving effort.
      END MODULE LAIROTCAF	!Just the minimum.

      PROGRAM POKE
      USE LAIROTCAF
      INTEGER I

      WRITE (6,*) "Left factorials, from 0 to 10..."
      DO I = 0,10
        WRITE (6,1) I,LFACT(I)
    1   FORMAT ("!",I0,T6,I0)
      END DO

      WRITE (6,*) "Left factorials, from 20 to 110 by tens..."
      DO I = 20,110,10
        WRITE (6,1) I,LFACT(I)
      END DO
      END


(let Freq NIL
   (in "file.txt"
      (while (char) (accu 'Freq @ 1)) )
   (sort Freq) )


string all = Stdio.read_file("README.md");
mapping res = ([]);
foreach(all/1, string char)
    res[char]++;
write("%O\n", res);


frequencies: procedure options (main);
   declare tallies(26) fixed binary static initial ((26) 0);
   declare alphabet character (26) static initial
      ('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
   declare c character (1), i fixed binary;
   declare in file;

   open file (in) title ('/LETTER.DAT,type(text),recsize(200)') input;

   on endfile (in) go to prepare_list;

   do while('1'b);
      get file (in) edit (c) (a(1)); put edit (c) (a);
      i = index(alphabet, c);
      if i > 0 then tallies(i) = tallies(i) + 1;
   end;

prepare_list:
   put skip list('Letter', 'Frequency');
   do i = 1 to 26;
      if tallies(i) > 0 then
         put skip list (substr(alphabet, i, 1), tallies(i));
   end;
end frequencies;


' FB 1.05.0 Win64

#include "gmp.bi"

Sub leftFactorial(rop As __mpz_struct, op As ULong)
  Dim As __mpz_struct t1
  mpz_init_set_ui(@t1, 1)
  mpz_set_ui(@rop, 0)
  For i As ULong = 1 To op
    mpz_add(@rop, @rop, @t1)
    mpz_mul_ui(@t1, @t1, i)
  Next
  mpz_clear(@t1)
End Sub

Function digitCount(op As __mpz_struct) As ULong
  Dim As ZString Ptr t = mpz_get_str(0, 10, @op)
  Dim As ULong ret = Len(*t)
  Deallocate(t)
  Return ret
End Function

Dim As __mpz_struct t
mpz_init(@t)

For i As ULong = 0 To 110
  If i <= 10 OrElse i Mod 10 = 0 Then
    leftFactorial(t, i)
    gmp_printf(!"!%u = %Zd\n", i, @t)
  End If
Next

Print

For i As ULong = 1000 To 10000 Step 1000
  leftFactorial(t, i)
  Print "!"; Str(i); " has "; digitCount(t); " digits"
Next

mpz_clear(@t)
Print
Print "Press any key to quit"
Sleep


leftFactorial[n] :=
{
   sum = 0
   for k = 0 to n-1
      sum = sum + k!

   return sum
}

println["Zero through ten"]
for n = 0 to 10
   println["$n\t" + leftFactorial[n]]

println["\n20 through 110"]
for n = 20 to 110 step 10
   println["$n\t" + leftFactorial[n]]

println["\nlength of 1000 through 10000"]
for n = 1000 to 10000 step 1000
   println["$n has " + length[toString[leftFactorial[n]]] + " digits"]


package main

import (
    "fmt"
    "math/big"
)

func main() {
    fmt.Print("!0 through !10: 0")
    one := big.NewInt(1)
    n := big.NewInt(1)
    f := big.NewInt(1)
    l := big.NewInt(1)
    next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) }
    for ; ; next() {
        fmt.Print(" ", l)
        if n.Int64() == 10 {
            break
        }
    }
    fmt.Println()
    for {
        for i := 0; i < 10; i++ {
            next()
        }
        fmt.Printf("!%d: %d\n", n, l)
        if n.Int64() == 110 {
            break
        }
    }
    fmt.Println("Lengths of !1000 through !10000 by thousands:")
    for i := 110; i < 1000; i++ {
        next()
    }
    for {
        fmt.Print(" ", len(l.String()))
        if n.Int64() == 10000 {
            break
        }
        for i := 0; i < 1000; i++ {
            next()
        }
    }
    fmt.Println()
}


function frequency ($string) {
    $arr = $string.ToUpper().ToCharArray() |where{$_ -match '[A-KL-Z]'}
    $n = $arr.count
    $arr | group | foreach{
        [pscustomobject]@{letter = "$($_.name)"; frequency  = "$([math]::round($($_.Count/$n),5))"; count = "$($_.count)"}
    } | sort letter
}
$file = "$($MyInvocation.MyCommand.Name )" #Put the name of your file here
frequency $(get-content $file -Raw)


frequency(File) :-
	read_file_to_codes(File, Code, []),

	% we only keep alphabetic codes
	include(my_code_type, Code, LstCharCode),

	% we translate char_codes into uppercase atoms.
	maplist(my_upcase, LstCharCode, LstChar),

	% sort and pack the list
	msort(LstChar, SortLstChar),
	packList(SortLstChar, Freq),
	maplist(my_write, Freq).

my_write([Num, Atom]) :-
	swritef(A, '%3r', [Num]),
	writef('Number of %w :%w\n', [Atom, A]).

my_code_type(Code) :-
	code_type(Code, alpha).

my_upcase(CharCode, UpChar) :-
	char_code(Atom, CharCode),
	upcase_atom(Atom, UpChar).

:- use_module(library(clpfd)).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ?- packList([a,a,a,b,c,c,c,d,d,e], L).
%  L = [[3,a],[1,b],[3,c],[2,d],[1,e]] .
%
% ?- packList(R,  [[3,a],[1,b],[3,c],[2,d],[1,e]]).
% R = [a,a,a,b,c,c,c,d,d,e] .
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
packList([],[]).

packList([X],[[1,X]]) :-
	!.

packList([X|Rest],[XRun|Packed]):-
	run(X,Rest, XRun,RRest),
	packList(RRest,Packed).

run(Var,[],[1,Var],[]).

run(Var,[Var|LRest],[N1, Var],RRest):-
	N #> 0,
	N1 #= N + 1,
	run(Var,LRest,[N, Var],RRest).

run(Var,[Other|RRest], [1,Var],[Other|RRest]):-
	dif(Var,Other).


leftFact :: [Integer]
leftFact = scanl (+) 0 fact

fact :: [Integer]
fact = scanl (*) 1 [1 ..]

main :: IO ()
main =
  mapM_
    putStrLn
    [ "0 ~ 10:"
    , show $ (leftFact !!) <$> [0 .. 10]
    , ""
    , "20 ~ 110 by tens:"
    , unlines $ show . (leftFact !!) <$> [20,30 .. 110]
    , ""
    , "length of 1,000 ~ 10,000 by thousands:"
    , show $ length . show . (leftFact !!) <$> [1000,2000 .. 10000]
    , ""
    ]


procedure main()
    every writes(lfact(0 | !10)," ")
    write()
    write()
    every write(lfact(20 to 110 by 10))
    write()
    every writes(*lfact(1000 to 10000 by 1000)," ")
    write()
end

procedure lfact(n)
    r := 0
    f := 1
    every (i := !n, r +:= .f, f *:= .i)
    return r
end


Procedure countLetters(Array letterCounts(1), textLine.s)
  ;counts only letters A -> Z, uses index 0 of letterCounts() to keep a total of all counts
  Protected i, lineLength = Len(textLine), letter

  textLine = UCase(textLine)
  For i = 1 To lineLength
    letter = Asc(Mid(textLine, i, 1)) - 'A' + 1
    If letter >= 1 And letter <= 26
      letterCounts(letter) + 1 ;tally individual letter count
      letterCounts(0) + 1      ;increment total letter count
    EndIf
  Next
EndProcedure

If OpenConsole()
  Define filename.s, fileID, i
  filename = OpenFileRequester("Select text file to examine", "*.txt", "Text (*.txt)|*.txt;|All files (*.*)|*.*", 0)
  fileID = 0
  If ReadFile(fileID, filename)
    Dim letterCounts(26) ;A - Z only, index 0 contains the total of all letter counts

    Define textLine.s
    While Not Eof(fileID)
      textLine = ReadString(fileID)
      countLetters(letterCounts(), textLine)
    Wend
    CloseFile(fileID)

    PrintN("File: " + filename + #CRLF$)
    PrintN("Letter  %Freq  Count")
    For i = 1 To 26
      Print("  " + Chr(64 + i) + "     ")
      Print(RSet(StrF(100 * letterCounts(i) / letterCounts(0), 1), 5, " ") + "  ")
      PrintN(Str(letterCounts(i)))
    Next
    PrintN(#CRLF$ + "Total letter count in file: " + Str(letterCounts(0)))
  EndIf

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


import java.math.BigInteger;

public class LeftFac{
	public static BigInteger factorial(BigInteger n){
		BigInteger ans = BigInteger.ONE;
		for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){
			ans = ans.multiply(x);
		}
		return ans;
	}

	public static BigInteger leftFact(BigInteger n){
		BigInteger ans = BigInteger.ZERO;
		for(BigInteger k = BigInteger.ZERO; k.compareTo(n.subtract(BigInteger.ONE)) <= 0; k = k.add(BigInteger.ONE)){
			ans = ans.add(factorial(k));
		}
		return ans;
	}

	public static void main(String[] args){
		for(int i = 0; i <= 10; i++){
			System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i)));
		}

		for(int i = 20; i <= 110; i += 10){
			System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i)));
		}

		for(int i = 1000; i <= 10000; i += 1000){
			System.out.println("!" + i + " has " + leftFact(BigInteger.valueOf(i)).toString().length() + " digits");
		}
	}
}


F dList(n, =start)
   start--
   V a = Array(0 .< n)
   a[start] = a[0]
   a[0] = start
   a.sort_range(1..)
   V first = a[1]
   [[Int]] r
   F recurse(Int last) -> N
      I (last == @first)
         L(v) @a[1..]
            I L.index + 1 == v
               R
         V b = @a.map(x -> x + 1)
         @r.append(b)
         R
      L(i) (last .< 0).step(-1)
         swap(&@a[i], &@a[last])
         @recurse(last - 1)
         swap(&@a[i], &@a[last])
   recurse(n - 1)
   R r

F printSquare(latin, n)
   L(row) latin
      print(row)
   print()

F reducedLatinSquares(n, echo)
   I n <= 0
      I echo
         print(‘[]’)
      R 0
   E I n == 1
      I echo
         print([1])
      R 1

   V rlatin = [[0] * n] * n
   L(j) 0 .< n
      rlatin[0][j] = j + 1

   V count = 0
   F recurse(Int i) -> N
      V rows = dList(@n, i)

      L(r) 0 .< rows.len
         @rlatin[i - 1] = rows[r]
         V justContinue = 0B
         V k = 0
         L !justContinue & k < i - 1
            L(j) 1 .< @n
               I @rlatin[k][j] == @rlatin[i - 1][j]
                  I r < rows.len - 1
                     justContinue = 1B
                     L.break
                  I i > 2
                     R
            k++
         I !justContinue
            I i < @n
               @recurse(i + 1)
            E
               @count++
               I @echo
                  printSquare(@rlatin, @n)

   recurse(2)
   R count

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

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")
L(n) 1..6
   V size = reducedLatinSquares(n, 0B)
   V f = factorial(n - 1)
   f *= f * n * size
   print(‘Order #.: Size #<4 x #.! x #.! => Total #.’.format(n, size, n, n - 1, f))


import collections, sys

def filecharcount(openfile):
    return sorted(collections.Counter(c for l in openfile for c in l).items())

f = open(sys.argv[1])
print(filecharcount(f))


  [ [] 26 times [ 0 join ] ]  is makecountnest (     --> [ )

  [ char A char Z 1+ within ] is ischar        (   c --> b )

  [ char A -
    2dup peek 1+ unrot poke ] is tallychar     ( [ c --> [ )

  [ makecountnest swap
    witheach
      [ upper dup ischar iff
          tallychar
        else drop ] ]         is countchars    (   $ --> [ )

  [ say "Letter count:" cr
    witheach
      [ say "  "
        i^ char A + emit
            say ":" echo
            cr ] ]            is echocount     (   [ -->   )

   [ sharefile 0 = if
       [ $ " not found."
         join fail ]
     countchars
     echocount ]              is fileletters  (    $ -->   )


leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1)

@show leftfactorial.(0:10)
@show ndigits.(leftfactorial.(big.(1000:1000:10_000)))


// version 1.0.6

import java.math.BigInteger

fun leftFactorial(n: Int): BigInteger {
    if (n == 0) return BigInteger.ZERO
    var fact = BigInteger.ONE
    var sum = fact
    for (i in 1 until n) {
        fact *= BigInteger.valueOf(i.toLong())
        sum += fact
    }
    return sum
}

fun main(args: Array<String>) {
    for (i in 0..110)
        if (i <= 10 || (i % 10) == 0)
            println("!${i.toString().padEnd(3)} = ${leftFactorial(i)}")
    println("\nLength of the following left factorials:")
    for (i in 1000..10000 step 1000)
        println("!${i.toString().padEnd(5)} has ${leftFactorial(i).toString().length} digits")
}


'''1) defining !n'''

{def !n                                                     // the main function's name

 {def !n.mem {A.new 0 1 2}}                                 // initializing a global array
                                                            // memorizing the computed values of !n
 {def !n.set                                                // computing and storing the values
  {lambda {:n}
   {A.set! :n                                               // assign at n
           {long_mult :n {A.get {- :n 1} {!n.mem}} }        // product of n and computed value at n-1
           {!n.mem}}}}                                      // in the global array

 {def !n.get                                                // getting a value
  {lambda {:n}
   {A.get :n {if {W.equal? {A.get :n {!n.mem}} undefined}   // if it doesn't exist
              then {!n.set :n}                              // then compute it
              else {!n.mem}}}}}                             // else get it from the global array

 {lambda {:n}                                               // the main function's body
  {if {< :n 2}                                              // if n=0 and n=1
  then :n                                                   // then return 0 or 1
  else {S.reduce long_add                                   // apply add_long to
                 1 {S.map !n.get {S.serie 1 {- :n 1}}}}}}}  // the sequence of computed values

'''2) the task'''

A) computing !n from 2 to 10 takes about 4ms

{S.map {lambda {:n} {br}!n(:n) = {!n :n}}
       {S.serie 0 10}}
->
!n(0) = 0
!n(1) = 1
!n(2) = 2
!n(3) = 4
!n(4) = 10
!n(5) = 34
!n(6) = 154
!n(7) = 874
!n(8) = 5914
!n(9) = 46234
!n(10) = 409114

B) computing !n from 20 to 110 with step 10 takes about 25ms

{S.map {lambda {:n} {br}!n(:n) = {!n :n}}
       {S.serie 20 110 10}}
->
!n(20) = 128425485935180314
!n(30) = 9157958657951075573395300940314
!n(40) = 20935051082417771847631371547939998232420940314
!n(50) = 620960027832821612639424806694551108812720525606160920420940314
!n(60) = 141074930726669571000530822087000522211656242116439949000980378746128920420940314
!n(70) = 173639511802987526699717162409282876065556519849603157850853034644815111221599509216528920420940314
!n(80) = 906089587987695346534516804650290637694024830011956365184327674619752094289696314882008531991840922336528920420940314
!n(90) = 16695570072624210767034167688394623360733515163575864136345910335924039962404869510225723072235842668787507993136908442336528920420940314
!n(100) = 942786239765826579160595268206839381354754349601050974345395410407078230249590414458830117442618180732911203520208889371641659121356556442336528920420940314
!n(110) = 145722981061585297004706728001906071948635199234860720988658042536179281328615541936083296163475394237524337422204397431927131629058103519228197429698252556442336528920420940314

C) computing !n from 1000 to 1000 with step 1000 takes about 87 seconds

1) compute n! from 1 to 10000 and store in MEM   // about 86 seconds
{def foo {!n 10000}} -> foo

2) take 10 values from MEM                       // about 1ms
{S.map {lambda {:n}
                {br}Digits of !n(:n) = {W.length {A.get {- :n 1} {MEM}}}}
        {S.serie 1000 10000 1000}}
->
Digits of !n(1000) = 2565
Digits of !n(2000) = 5733
Digits of !n(3000) = 9128
Digits of !n(4000) = 12670
Digits of !n(5000) = 16322
Digits of !n(6000) = 20062
Digits of !n(7000) = 23875
Digits of !n(8000) = 27749
Digits of !n(9000) = 31678
Digits of !n(10000) = 35656


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

namespace LatinSquares {
    using matrix = List<List<int>>;

    class Program {
        static void Swap<T>(ref T a, ref T b) {
            var t = a;
            a = b;
            b = t;
        }

        static matrix DList(int n, int start) {
            start--; // use 0 basing
            var a = Enumerable.Range(0, n).ToArray();
            a[start] = a[0];
            a[0] = start;
            Array.Sort(a, 1, a.Length - 1);
            var first = a[1];
            // recursive closure permutes a[1:]
            matrix r = new matrix();
            void recurse(int last) {
                if (last == first) {
                    // bottom of recursion. you get here once for each permutation.
                    // test if permutation is deranged.
                    for (int j = 1; j < a.Length; j++) {
                        var v = a[j];
                        if (j == v) {
                            return; //no, ignore it
                        }
                    }
                    // yes, save a copy with 1 based indexing
                    var b = a.Select(v => v + 1).ToArray();
                    r.Add(b.ToList());
                    return;
                }
                for (int i = last; i >= 1; i--) {
                    Swap(ref a[i], ref a[last]);
                    recurse(last - 1);
                    Swap(ref a[i], ref a[last]);
                }
            }
            recurse(n - 1);
            return r;
        }

        static ulong ReducedLatinSquares(int n, bool echo) {
            if (n <= 0) {
                if (echo) {
                    Console.WriteLine("[]\n");
                }
                return 0;
            } else if (n == 1) {
                if (echo) {
                    Console.WriteLine("[1]\n");
                }
                return 1;
            }

            matrix rlatin = new matrix();
            for (int i = 0; i < n; i++) {
                rlatin.Add(new List<int>());
                for (int j = 0; j < n; j++) {
                    rlatin[i].Add(0);
                }
            }
            // first row
            for (int j = 0; j < n; j++) {
                rlatin[0][j] = j + 1;
            }

            ulong count = 0;
            void recurse(int i) {
                var rows = DList(n, i);

                for (int r = 0; r < rows.Count; r++) {
                    rlatin[i - 1] = rows[r];
                    for (int k = 0; k < i - 1; k++) {
                        for (int j = 1; j < n; j++) {
                            if (rlatin[k][j] == rlatin[i - 1][j]) {
                                if (r < rows.Count - 1) {
                                    goto outer;
                                }
                                if (i > 2) {
                                    return;
                                }
                            }
                        }
                    }
                    if (i < n) {
                        recurse(i + 1);
                    } else {
                        count++;
                        if (echo) {
                            PrintSquare(rlatin, n);
                        }
                    }
                outer: { }
                }
            }

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

        static void PrintSquare(matrix latin, int n) {
            foreach (var row in latin) {
                var it = row.GetEnumerator();
                Console.Write("[");
                if (it.MoveNext()) {
                    Console.Write(it.Current);
                }
                while (it.MoveNext()) {
                    Console.Write(", {0}", it.Current);
                }
                Console.WriteLine("]");
            }
            Console.WriteLine();
        }

        static ulong Factorial(ulong n) {
            if (n <= 0) {
                return 1;
            }
            ulong prod = 1;
            for (ulong i = 2; i < n + 1; i++) {
                prod *= i;
            }
            return prod;
        }

        static void Main() {
            Console.WriteLine("The four reduced latin squares of order 4 are:\n");
            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:\n");
            for (int n = 1; n < 7; n++) {
                ulong nu = (ulong)n;

                var size = ReducedLatinSquares(n, false);
                var f = Factorial(nu - 1);
                f *= f * nu * size;
                Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f);
            }
        }
    }
}


' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
'  Program CountCar                                   '
'                                                     '
'  This program counts how many distinct characters   '
'  have a text file specified by the user.            '
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' OPTION EXPLICIT  ' Remove comment in VB-DOS

' Register
TYPE regChar
  Character AS STRING * 3
  Count AS LONG
END TYPE

' Var
DIM iChar AS INTEGER
DIM iCL AS INTEGER
DIM iCountChars AS INTEGER
DIM iFile AS INTEGER
DIM i AS INTEGER
DIM lMUC AS LONG
DIM iMUI AS INTEGER
DIM lLUC AS LONG
DIM iLUI AS INTEGER
DIM iMaxIdx AS INTEGER
DIM iP AS INTEGER
DIM iPause AS INTEGER
DIM iPMI AS INTEGER
DIM iPrint AS INTEGER
DIM lHowMany AS LONG
DIM lTotChars AS LONG
DIM sTime AS SINGLE
DIM strFile AS STRING
DIM strTxt AS STRING
DIM strDate AS STRING
DIM strTime AS STRING
DIM strKey AS STRING
CONST LngReg = 256
CONST Letters = 1
CONST FALSE = 0
CONST TRUE = NOT FALSE

'------Main program cycle

' Initialize variables
strDate = DATE$
strTime = TIME$
iFile = FREEFILE

DO
  CLS
  PRINT "This program counts letters or characters in a text file."
  PRINT
  INPUT "File to open: ", strFile
  OPEN strFile FOR BINARY AS #iFile
  IF LOF(iFile) > 0 THEN
    PRINT "Count: 1) Letters 2) Characters (1 or 2)";
    DO
      strKey = INKEY$
    LOOP UNTIL strKey = "1" OR strKey = "2"
    PRINT ". Option selected: "; strKey
    iCL = VAL(strKey)
    sTime = TIMER
    iP = POS(0)
    lHowMany = LOF(iFile)
    strTxt = SPACE$(LngReg)

    IF iCL = Letters THEN
      iMaxIdx = 26
    ELSE
      iMaxIdx = 255
    END IF

    IF iMaxIdx <> iPMI THEN
      iPMI = iMaxIdx
      REDIM rChar(0 TO iMaxIdx) AS regChar

      FOR i = 0 TO iMaxIdx
        IF iCL = Letters THEN
          strTxt = CHR$(i + 65)
          IF i = 26 THEN strTxt = CHR$(165)
        ELSE
          SELECT CASE i
            CASE 0: strTxt = "nul"
            CASE 7: strTxt = "bel"
            CASE 9: strTxt = "tab"
            CASE 10: strTxt = "lf"
            CASE 11: strTxt = "vt"
            CASE 12: strTxt = "ff"
            CASE 13: strTxt = "cr"
            CASE 28: strTxt = "fs"
            CASE 29: strTxt = "gs"
            CASE 30: strTxt = "rs"
            CASE 31: strTxt = "us"
            CASE 32: strTxt = "sp"
            CASE ELSE: strTxt = CHR$(i)
          END SELECT
        END IF
        rChar(i).Character = strTxt
      NEXT i
    ELSE
      FOR i = 0 TO iMaxIdx
        rChar(i).Count = 0
      NEXT i
    END IF

    PRINT "Looking for ";
    IF iCL = Letters THEN PRINT "letters.";  ELSE PRINT "characters.";
    PRINT " File is"; STR$(lHowMany); " in size. Working"; : COLOR 23: PRINT "..."; : COLOR (7)
    DO WHILE LOC(iFile) < LOF(iFile)
      IF LOC(iFile) + LngReg > LOF(iFile) THEN
        strTxt = SPACE$(LOF(iFile) - LOC(iFile))
      END IF
      GET #iFile, , strTxt
      FOR i = 1 TO LEN(strTxt)
        IF iCL = Letters THEN
          iChar = ASC(UCASE$(MID$(strTxt, i, 1)))
          SELECT CASE iChar
            CASE 164: iChar = 165
            CASE 160: iChar = 65
            CASE 130, 144: iChar = 69
            CASE 161: iChar = 73
            CASE 162: iChar = 79
            CASE 163, 129: iChar = 85
          END SELECT
          iChar = iChar - 65

          ' Validates if iChar is a letter
          IF iChar >= 0 AND iChar <= 25 THEN
            rChar(iChar).Count = rChar(iChar).Count + 1
          ELSEIF iChar = 100 THEN ' CHR$(165)
            rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1
          END IF
        ELSE
          iChar = ASC(MID$(strTxt, i, 1))
          rChar(iChar).Count = rChar(iChar).Count + 1
        END IF
      NEXT i
    LOOP
    CLOSE #iFile

    ' Show the characters found
    lMUC = 0
    iMUI = 0
    lLUC = 2147483647
    iLUI = 0
    iPrint = FALSE
    lTotChars = 0
    iCountChars = 0
    iPause = FALSE
    CLS
    IF iCL = Letters THEN PRINT "Letters found: ";  ELSE PRINT "Characters found: ";
    FOR i = 0 TO iMaxIdx
      ' Most Used Character
      IF lMUC < rChar(i).Count THEN
        lMUC = rChar(i).Count
        iMUI = i
      END IF

      ' Print character
      IF rChar(i).Count > 0 THEN
        strTxt = ""
        IF iPrint THEN strTxt = ", " ELSE iPrint = TRUE
        strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character))
        strTxt = strTxt + "=" + LTRIM$(STR$(rChar(i).Count))
        iP = POS(0)
        IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN
          PRINT ","
          IF CSRLIN >= 23 AND NOT iPause THEN
            iPause = TRUE
            PRINT "Press a key to continue..."
            DO
              strKey = INKEY$
            LOOP UNTIL strKey <> ""
          END IF
          strTxt = MID$(strTxt, 3)
        END IF
        PRINT strTxt;
        lTotChars = lTotChars + rChar(i).Count
        iCountChars = iCountChars + 1

        ' Least Used Character
        IF lLUC > rChar(i).Count THEN
          lLUC = rChar(i).Count
          iLUI = i
        END IF
      END IF
    NEXT i

    PRINT "."

    ' Shows the summary
    PRINT
    PRINT "File analyzed....................: "; strFile
    PRINT "Looked for.......................: "; : IF iCL = Letters THEN PRINT "Letters" ELSE PRINT "Characters"
    PRINT "Total characters in file.........:"; lHowMany
    PRINT "Total characters counted.........:"; lTotChars
    IF iCL = Letters THEN PRINT "Characters discarded on count....:"; lHowMany - lTotChars
    PRINT "Distinct characters found in file:"; iCountChars; "of"; iMaxIdx + 1
    PRINT "Most used character was..........: ";
      iPrint = FALSE
      FOR i = 0 TO iMaxIdx
        IF rChar(i).Count = lMUC THEN
          IF iPrint THEN PRINT ", ";  ELSE iPrint = TRUE
          PRINT RTRIM$(LTRIM$(rChar(i).Character));
        END IF
      NEXT i
    PRINT " ("; LTRIM$(STR$(rChar(iMUI).Count)); " times)"
    PRINT "Least used character was.........: ";
      iPrint = FALSE
      FOR i = 0 TO iMaxIdx
        IF rChar(i).Count = lLUC THEN
          IF iPrint THEN PRINT ", ";  ELSE iPrint = TRUE
          PRINT RTRIM$(LTRIM$(rChar(i).Character));
        END IF
      NEXT i
      PRINT " ("; LTRIM$(STR$(rChar(iLUI).Count)); " times)"
    PRINT "Time spent in the process........:"; TIMER - sTime; "seconds"
  ELSE
    ' File does not exist
    CLOSE #iFile
    KILL strFile
    PRINT
    PRINT "File does not exist."
  END IF

  ' Again?
  PRINT
  PRINT "Again? (Y/n)"
  DO
    strTxt = UCASE$(INKEY$)
  LOOP UNTIL strTxt = "N" OR strTxt = "Y" OR strTxt = CHR$(13) OR strTxt = CHR$(27)
LOOP UNTIL strTxt = "N" OR strTxt = CHR$(27)

CLS
PRINT "End of execution."
PRINT "Start time: "; strDate; " "; strTime; ", end time: "; DATE$; " "; TIME$; "."
END
' ---End of main program cycle


-- Lua bindings for GNU bc
require("bc")

-- Return table of factorials from 0 to n
function facsUpTo (n)
    local f, fList = bc.number(1), {}
    fList[0] = 1
    for i = 1, n do
        f = bc.mul(f, i)
        fList[i] = f
    end
    return fList
end

-- Return left factorial of n
function leftFac (n)
    local sum = bc.number(0)
    for k = 0, n - 1 do sum = bc.add(sum, facList[k]) end
    return bc.tostring(sum)
end

-- Main procedure
facList = facsUpTo(10000)
for i = 0, 10 do print("!" .. i .. " = " .. leftFac(i)) end
for i = 20, 110, 10 do print("!" .. i .. " = " .. leftFac(i)) end
for i = 1000, 10000, 1000 do
    print("!" .. i .. " contains " .. #leftFac(i) .. " digits")
end


left_factorial := n -> add(k!, k = 1 .. n - 1);
seq(left_factorial(i), i = 1 .. 10);
seq(left_factorial(i), i = 20 .. 110, 10);
seq(length(left_factorial(i)), i = 1000 .. 10000, 1000);


left[n_] := left[n] = Sum[k!, {k, 0, n - 1}]
Print["left factorials 0 through 10:"]
Print[left /@ Range[0, 10] // TableForm]
Print["left factorials 20 through 110, by tens:"]
Print[left /@ Range[20, 110, 10] // TableForm]
Print["Digits in left factorials 1,000 through 10,000, by thousands:"]
Print[Length[IntegerDigits[left[#]]] & /@ Range[1000, 10000, 1000] // TableForm]


#include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>

typedef std::vector<std::vector<int>> matrix;

matrix dList(int n, int start) {
    start--; // use 0 basing

    std::vector<int> a(n);
    std::iota(a.begin(), a.end(), 0);
    a[start] = a[0];
    a[0] = start;
    std::sort(a.begin() + 1, a.end());
    auto first = a[1];
    // recursive closure permutes a[1:]
    matrix r;
    std::function<void(int)> recurse;
    recurse = [&](int last) {
        if (last == first) {
            // bottom of recursion you get here once for each permutation.
            // test if permutation is deranged.
            for (size_t j = 1; j < a.size(); j++) {
                auto v = a[j];
                if (j == v) {
                    return; //no, ignore it
                }
            }
            // yes, save a copy with 1 based indexing
            std::vector<int> b;
            std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; });
            r.push_back(b);
            return;
        }
        for (int i = last; i >= 1; i--) {
            std::swap(a[i], a[last]);
            recurse(last - 1);
            std::swap(a[i], a[last]);
        }
    };
    recurse(n - 1);
    return r;
}

void printSquare(const matrix &latin, int n) {
    for (auto &row : latin) {
        auto it = row.cbegin();
        auto end = row.cend();
        std::cout << '[';
        if (it != end) {
            std::cout << *it;
            it = std::next(it);
        }
        while (it != end) {
            std::cout << ", " << *it;
            it = std::next(it);
        }
        std::cout << "]\n";
    }
    std::cout << '\n';
}

unsigned long reducedLatinSquares(int n, bool echo) {
    if (n <= 0) {
        if (echo) {
            std::cout << "[]\n";
        }
        return 0;
    } else if (n == 1) {
        if (echo) {
            std::cout << "[1]\n";
        }
        return 1;
    }

    matrix rlatin;
    for (int i = 0; i < n; i++) {
        rlatin.push_back({});
        for (int j = 0; j < n; j++) {
            rlatin[i].push_back(j);
        }
    }
    // first row
    for (int j = 0; j < n; j++) {
        rlatin[0][j] = j + 1;
    }

    unsigned long count = 0;
    std::function<void(int)> recurse;
    recurse = [&](int i) {
        auto rows = dList(n, i);

        for (size_t r = 0; r < rows.size(); r++) {
            rlatin[i - 1] = rows[r];
            for (int k = 0; k < i - 1; k++) {
                for (int j = 1; j < n; j++) {
                    if (rlatin[k][j] == rlatin[i - 1][j]) {
                        if (r < rows.size() - 1) {
                            goto outer;
                        }
                        if (i > 2) {
                            return;
                        }
                    }
                }
            }
            if (i < n) {
                recurse(i + 1);
            } else {
                count++;
                if (echo) {
                    printSquare(rlatin, n);
                }
            }
        outer: {}
        }
    };

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

unsigned long factorial(unsigned long n) {
    if (n <= 0) return 1;
    unsigned long prod = 1;
    for (unsigned long i = 2; i <= n; i++) {
        prod *= i;
    }
    return prod;
}

int main() {
    std::cout << "The four reduced lating squares of order 4 are:\n";
    reducedLatinSquares(4, true);

    std::cout << "The size of the set of reduced latin squares for the following orders\n";
    std::cout << "and hence the total number of latin squares of these orders are:\n\n";
    for (int n = 1; n < 7; n++) {
        auto size = reducedLatinSquares(n, false);
        auto f = factorial(n - 1);
        f *= f * n * size;
        std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n';
    }

    return 0;
}


letter.frequency <- function(filename)
{
    file <- paste(readLines(filename), collapse = '')
    chars <- strsplit(file, NULL)[[1]]
    summary(factor(chars))
}


#lang racket
(require math)

(define (letter-frequencies ip)
  (count-samples
   (port->list read-char ip)))

(letter-frequencies (open-input-string "abaabdc"))


import iterutils, bigints

proc lfact: iterator: BigInt =
  result = iterator: BigInt =
    yield 0.initBigInt
    var
      fact = 1.initBigInt
      sum = 0.initBigInt
      n = 1.initBigInt
    while true:
      sum += fact
      fact *= n
      n += 1
      yield sum

echo "first 11:\n  "
for i in lfact().slice(last = 10):
  echo "  ", i

echo "20 through 110 (inclusive) by tens:"
for i in lfact().slice(20, 110, 10):
  echo "  ", i

echo "Digits in 1,000 through 10,000 (inclusive) by thousands:"
for i in lfact().slice(1_000, 10_000, 1_000):
  echo "  ", ($i).len


: leftFact  | i | 0 1 rot loop: i [ tuck + swap i * ] drop ;


#!perl
use 5.010;
use strict;
use warnings;
use bigint;

sub leftfact {
	my ($n) = @_;
	state $cached = 0;
	state $factorial = 1;
	state $leftfact = 0;
	if( $n < $cached ) {
		($cached, $factorial, $leftfact) = (0, 1, 0);
	}
	while( $n > $cached ) {
		$leftfact += $factorial;
		$factorial *= ++$cached;
	}
	return $leftfact;
}

printf "!%d = %s\n", $_, leftfact($_) for 0 .. 10, map $_*10, 2..11;
printf "!%d has %d digits.\n", $_, length leftfact($_) for map $_*1000, 1..10;