program Abbreviations_Automatic;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.Generics.Collections,
  System.IOUtils;

function DistinctStrings(strs: TArray<string>): TArray<string>;
begin
  var l := length(strs);
  var _set := TDictionary<string, Boolean>.Create;
  SetLength(result, 0);
  for var str in strs do
  begin
    if not _set.ContainsKey(str) then
    begin
      SetLength(result, Length(result) + 1);
      result[High(result)] := str;
      _set.AddOrSetValue(str, true);
    end;
  end;
  _set.free;
end;

function takeRunes(s: string; n: Integer): string;
begin
  var i := 0;
  for var j := 0 to s.Length - 1 do
  begin
    if i = n then
      exit(s.Substring(0, j));
    inc(i);
  end;
  Result := s;
end;

begin
  var lines := TFile.ReadAllLines('days_of_week.txt');

  var lineCount := 0;
  while lineCount < length(Lines) do
  begin
    var line := lines[lineCount].Trim;
    inc(lineCount);
    if line.IsEmpty then
    begin
      Writeln;
      Continue;
    end;

    var days := line.Split([' '], TStringSplitOptions.ExcludeEmpty);
    var daysLen := Length(days);
    if daysLen <> 7 then
    begin
      Writeln('There aren''t 7 days in line', lineCount);
      Readln;
      halt;
    end;

    if Length(distinctStrings(days)) <> 7 then
    begin
      writeln(' infinity ', line);
      Continue;
    end;

    var abbrevLen := 0;
    while True do
    begin
      var abbrevs: TArray<string>;
      SetLength(abbrevs, daysLen);

      for var i := 0 to daysLen - 1 do
        abbrevs[i] := takeRunes(days[i], abbrevLen);

      if Length(distinctStrings(abbrevs)) = 7 then
      begin
        Writeln(abbrevLen.ToString.PadLeft(2).PadRight(3), line);
        Break;
      end;

      inc(abbrevLen);
    end;

  end;
  Readln;
end.


import java.math.BigInteger;
import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
import static java.lang.Math.min;

public class Test {

    static List<BigInteger> cumu(int n) {
        List<List<BigInteger>> cache = new ArrayList<>();
        cache.add(asList(BigInteger.ONE));

        for (int L = cache.size(); L < n + 1; L++) {
            List<BigInteger> r = new ArrayList<>();
            r.add(BigInteger.ZERO);
            for (int x = 1; x < L + 1; x++)
                r.add(r.get(r.size() - 1).add(cache.get(L - x).get(min(x, L - x))));
            cache.add(r);
        }
        return cache.get(n);
    }

    static List<BigInteger> row(int n) {
        List<BigInteger> r = cumu(n);
        return range(0, n).mapToObj(i -> r.get(i + 1).subtract(r.get(i)))
                .collect(toList());
    }

    public static void main(String[] args) {
        System.out.println("Rows:");
        for (int x = 1; x < 11; x++)
            System.out.printf("%2d: %s%n", x, row(x));

        System.out.println("\nSums:");
        for (int x : new int[]{23, 123, 1234}) {
            List<BigInteger> c = cumu(x);
            System.out.printf("%s %s%n", x, c.get(c.size() - 1));
        }
    }
}


set words = "A'BARK'BOOK'TREAT'COMMON'SQUAD'CONFUSE"
set result = *
loop word = words
   set blocks = "BO'XK'DQ'CP'NA'GT'RE'TG'QD'FS'JW'HU'VI'AN'OB'ER'FS'LY'PC'ZM"
   set wordx = split (word, |"~</~")
   set cond = "true"
   loop char = wordx
      set n = filter_index (blocks, "~*{char}*~", -)
      if (n.eq."") then
         set cond = "false"
         exit
      endif
      set n2 = select (n, 1)
      set n3 = select (blocks, #n2, blocks)
   endloop
   set out = concat (word, " ", cond)
   set result = append (result, out)
endloop


@(do
   (defvar blocks '((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G)
                    (Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R)
                    (F S) (L Y) (P C) (Z M)))

   ;; Define and build hash which maps each letter that occurs in blocks
   ;; to a list of the blocks in which that letter occurs.

   (defvar alpha2blocks [hash-uni [group-by first blocks]
                                  [group-by second blocks]
                                  append])

   ;; convert, e.g. "abc" -> (A B C)
   ;; intern -- convert a string to an interned symbol "A" -> A
   ;; tuples -- turn string into 1-element tuples: "ABC" -> ("A" "B" "C")
   ;; square brackets around mapcar -- Lisp-1 style evaluation, allowing
   ;;   the intern function binding to be treated as a variable binding.

   (defun string-to-syms (str)
     [mapcar intern (tuples 1 (upcase-str str))])

   ;; Recursive part of algorithm working purely with Lisp symbols.
   ;; alpha -- single symbol denoting a letter
   ;; [alpha2blocks alpha] -- look up list of blocks for given letter
   ;; (memq item list) -- is item a member of list, under eq equality?
   ;; (remq item list) -- remove items from list which are eq to item.

   (defun can-make-word-guts (letters blocks)
     (cond
       ((null letters) t)
       ((null blocks) nil)
       (t (let ((alpha (first letters)))
            (each ((bl [alpha2blocks alpha]))
              (if (and (memq bl blocks)
                       (can-make-word-guts (rest letters)
                                           (remq bl blocks)))
                (return-from can-make-word-guts t)))))))

   (defun can-make-word (str)
     (can-make-word-guts (string-to-syms str) blocks)))
@(repeat)
@w
@(output)
>>> can_make_word("@(upcase-str w)")
@(if (can-make-word w) "True" "False")
@(end)
@(end)


print(sum(input().split(‘ ’, group_delimiters' 1B).map(i -> Int(i))))


*        A+B                       29/08/2015
APLUSB   CSECT
         USING  APLUSB,R12
         LR     R12,R15
         OPEN   (MYDATA,INPUT)
LOOP     GET    MYDATA,PG          read a single record
         XDECI  R4,PG              input A, in register 4
         XDECI  R5,PG+12           input B, in register 5
         AR     R4,R5              A+B, add register 5 to register 4, R4=R4+R
         XDECO  R4,PG+24           edit A+B
         XPRNT  PG,36              print A+B
         B      LOOP               repeat
ATEND    CLOSE  MYDATA
RETURN   XR     R15,R15
         BR     R14
         LTORG
MYDATA   DCB    LRECL=24,RECFM=FT,EODAD=ATEND,DDNAME=MYFILE
PG       DS     CL24               record
         DC     CL12' '
         YREGS
         END    APLUSB


-module(abbreviateweekdays).
-export([ main/0 ]).

uniq(L,Acc) ->
    io:fwrite("Min = ~p",[Acc]),
    io:fwrite(" Abbr:~p~n",[ sets:to_list(L) ]).

uniq(_, L, Acc) ->
    Abbr = [string:substr(X,1,Acc) || X <- L],
    %  list of abbrevs, starting with substring 1,1:
    TempSet = sets:from_list( Abbr ),
    TempSize = sets:size(TempSet),
    if
      TempSize =:= 7 ->
        uniq(TempSet,Acc);
      true  -> uniq(0, L, Acc+1)
     end.

read_lines(Device, Acc) when Acc < 19 ->
   case file:read_line(Device) of
    {ok, Line} ->
      Tokenized = string:tokens(Line," "),
      uniq(0,Tokenized,1),
      read_lines(Device, Acc + 1);
     eof ->
       io:fwrite("~p~n",["Done"])
    end;

read_lines(Device, 19) ->
       io:fwrite("~p~n",["Done"]).

main() ->
  {ok, Device} = (file:open("weekdays.txt", read)),
  read_lines(Device, 1).


(function () {
    var cache = [
        [1]
    ];
//this was never needed.
   /* function PyRange(start, end, step) {
        step = step || 1;
        if (!end) {
            end = start;
            start = 0;
        }
        var arr = [];
        for (var i = start; i < end; i += step) arr.push(i);
        return arr;
    }*/

    function cumu(n) {
        var /*ra = PyRange(cache.length, n + 1),*/ //Seems there is a better version for this
            r, l, x, Aa, Mi;
       // for (ll in ra) { too pythony
       for (l=cache.length;l<n+1;l++) {
            r = [0];
//            l = ra[ll];
//            ran = PyRange(1, l + 1);
//            for (xx in ran) {
            for(x=1;x<l+1;x++){
//                x = ran[xx];
                r.push(r[r.length - 1] + (Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x])[(Mi = Math.min(x, l - x)) < 0 ? Aa.length - Mi : Mi]);
            }
            cache.push(r);
        }
        return cache[n];
    }

    function row(n) {
        var r = cumu(n),
//            rra = PyRange(n),
            leArray = [],
            i;
//        for (ii in rra) {
        for (i=0;i<n;i++) {
//            i = rra[ii];
            leArray.push(r[i + 1] - r[i]);
        }
        return leArray;
    }

    console.log("Rows:");
    for (iterator = 1; iterator < 12; iterator++) {
        console.log(row(iterator));
    }

// PL clearly this was not tested:
//    console.log("Sums")[23, 123, 1234, 12345].foreach(function (a) {
    console.log("Sums");
    [23, 123, 1234, 12345].forEach(function (a) {
        var s = cumu(a);
        console.log(a, s[s.length - 1]);
    });
})()


#include <Core/Core.h>
#include <stdio.h>
#include <ctype.h>
//C++
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <cctype>

//C++
typedef std::pair<char,char> item_t;
typedef std::vector<item_t> list_t;

//C
using namespace Upp;

int can_make_words(char **b, char *word)
{
	int i, ret = 0, c = toupper(*word);

	if (!c) return 1;
	if (!b[0]) return 0;

	for (i = 0; b[i] && !ret; i++) {
		if (b[i][0] != c && b[i][1] != c) continue;
		Swap(b[i], b[0]);  // It needs to be Swap and not SWAP
		ret = can_make_words(b + 1, word + 1);
		Swap(b[i], b[0]);  // It needs to be Swap instead of SWAP
	}
	return ret;
}

//C++

bool can_create_word(const std::string& w, const list_t& vals) {
	std::set<uint32_t> used;
	while (used.size() < w.size()) {
		const char c = toupper(w[used.size()]);
		uint32_t x = used.size();
		for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) {
			if (used.find(i) == used.end()) {
				if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) {
					used.insert(i);
					break;
				}
			}
		}
		if (x == used.size()) break;
	}
	return used.size() == w.size();
}

// U++
CONSOLE_APP_MAIN
{
	// C
	char* blocks[] =
	{
		(char*)"BO", (char*)"XK", (char*)"DQ", (char*)"CP",
		(char*)"NA", (char*)"GT", (char*)"RE", (char*)"TG",
		(char*)"QD", (char*)"FS", (char*)"JW", (char*)"HU",
		(char*)"VI", (char*)"AN", (char*)"OB", (char*)"ER",
		(char*)"FS", (char*)"LY", (char*)"PC", (char*)"ZM", 0
	};

	char *words[] =
	{
		(char*)"", (char*)"A", (char*)"BARK", (char*)"BOOK",
		(char*)"TREAT", (char*)"COMMON", (char*)"SQUAD", (char*)"Confuse", 0
	};

	char **w;
	for (w = words; *w; w++)
		printf("%s\t%d\n", *w, can_make_words(blocks, *w));

	printf("\n");

	// C++
	list_t vals{ {'B', 'O'}, {'X', 'K'}, {'D', 'Q'}, {'C', 'P'},
		{'N', 'A'}, {'G', 'T'}, {'R', 'E'}, {'T', 'G'}, {'Q', 'D'},
		{'F', 'S'}, {'J', 'W'}, {'H', 'U'}, {'V', 'I'}, {'A', 'N'},
		{'O', 'B'}, {'E', 'R'}, {'F', 'S'}, {'L', 'Y'}, {'P', 'C'},
		{'Z', 'M'}
	};
	std::vector<std::string> wordsb{"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"};
	for (const std::string& w : wordsb) {
		std::cout << w << ": " << std::boolalpha << can_create_word(w, vals) << ".\n";
	}
	std::cout << "\n";

	const Vector<String>& cmdline = CommandLine();
	for(int i = 0; i < cmdline.GetCount(); i++) {
	}

}


	dad	b	; HL += BC (i.e., add BC reg pair to HL reg pair)
	dad	d	; HL += DE
	dad	h	; HL += HL (also known as "mul HL by two")
	dad	sp	; HL += SP (actually the only way to get at SP at all)


let fN g=let rec fN n=if g|>List.map(fun(g:string)->g.[0..n])|>Set.ofList|>Set.count=(List.length g) then (n+1) else fN(n+1)
         fN 0


USING: formatting io io.encodings.utf8 io.files kernel math
sequences sets splitting ;
IN: rosetta-code.abbreviations-automatic

: map-head ( seq n -- seq' ) [ short head ] curry map ;

: unique? ( seq n -- ? ) map-head all-unique? ;

: (abbr-length) ( seq -- n )
    1 [ 2dup unique? ] [ 1 + ] until nip ;

: abbr-length ( str -- n/str )
    [ "" ] [ " " split (abbr-length) ] if-empty ;

: show ( str -- ) dup abbr-length swap " %2u  %s\n" printf ;

: labels ( -- )
    "Min." "abbr" "Days of the week" "%s\n%s%32s\n" printf ;

: line ( n -- ) [ "=" write ] times ;

: header ( -- ) labels 4 line bl 75 line nl ;

: body ( -- ) [ show ] each-line ;

: abbreviations ( -- )
    header "day-names.txt" utf8 [ body ] with-file-reader ;

MAIN: abbreviations


package main

import(
    "bufio"
    "fmt"
    "os"
    "strings"
)

func distinctStrings(strs []string) []string {
    len := len(strs)
    set := make(map[string]bool, len)
    distinct := make([]string, 0, len)
    for _, str := range strs {
        if !set[str] {
            distinct = append(distinct, str)
            set[str] = true
        }
    }
    return distinct
}

func takeRunes(s string, n int) string {
    i := 0
    for j := range s {
        if i == n {
            return s[:j]
        }
        i++
    }
    return s
}

func main() {
    file, err := os.Open("days_of_week.txt")
    if err != nil {
        fmt.Println("Unable to open file.")
        return
    }
    defer file.Close()
    reader := bufio.NewReader(file)
    lineCount := 0
    for {
        line, err := reader.ReadString('\n')
        if err != nil { // end of file reached
            return
        }
        line = strings.TrimSpace(line)
        lineCount++
        if line == "" {
            fmt.Println()
            continue
        }
        days := strings.Fields(line)
        daysLen := len(days)
        if (len(days) != 7) {
            fmt.Println("There aren't 7 days in line", lineCount)
            return
        }
        if len(distinctStrings(days)) != 7 { // implies some days have the same name
            fmt.Println(" ∞ ", line)
            continue
        }
        for abbrevLen := 1; ; abbrevLen++ {
            abbrevs := make([]string, daysLen)
            for i := 0; i < daysLen; i++ {
                abbrevs[i] = takeRunes(days[i], abbrevLen)
            }
            if len(distinctStrings(abbrevs)) == 7 {
                fmt.Printf("%2d  %s\n", abbrevLen, line)
                break
            }
        }
    }
}


using Combinatorics, StatsBase

namesofline(n) = counts([x[1] for x in integer_partitions(n)])

function centerjustpyramid(n)
    maxwidth = length(string(namesofline(n)))
    for i in 1:n
        s = string(namesofline(i))
        println(" " ^ div(maxwidth - length(s), 2), s)
    end
end

centerjustpyramid(25)

const cachecountpartitions = Dict{BigInt,BigInt}()
function countpartitions(n::BigInt)
    if n < 0
        0
    elseif n < 2
        1
    elseif (np = get(cachecountpartitions, n, 0)) > 0
        np
    else
        np = 0
        sgn = 1
        for k = 1:n
            np += sgn * (countpartitions(n - (k*(3k-1)) >> 1) + countpartitions(n - (k*(3k+1)) >> 1))
            sgn = -sgn
        end
        cachecountpartitions[n] = np
    end
end

G(n) = countpartitions(BigInt(n))

for g in [23, 123, 1234, 12345]
    @time println("\nG($g) is $(G(g))")
end


import java.lang.Math.min
import java.math.BigInteger
import java.util.ArrayList
import java.util.Arrays.asList

fun namesOfGod(n: Int): List<BigInteger> {
    val cache = ArrayList<List<BigInteger>>()
    cache.add(asList(BigInteger.ONE))

    (cache.size..n).forEach { l ->
        val r = ArrayList<BigInteger>()
        r.add(BigInteger.ZERO)

        (1..l).forEach { x ->
            r.add(r[r.size - 1] + cache[l - x][min(x, l - x)])
        }
        cache.add(r)
    }
    return cache[n]
}

fun row(n: Int) = namesOfGod(n).let { r -> (0 until n).map { r[it + 1] - r[it] } }

fun main(args: Array<String>) {
    println("Rows:")
    (1..25).forEach {
        System.out.printf("%2d: %s%n", it, row(it))
    }

    println("\nSums:")
    intArrayOf(23, 123, 1234, 1234).forEach {
        val c = namesOfGod(it)
        System.out.printf("%s %s%n", it, c[c.size - 1])
    }
}


can_build_word() {
    if [[ $1 ]]; then
        can_build_word_rec "$1" BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM
    else
        return 1
    fi
}

can_build_word_rec() {
    [[ -z $1 ]] && return 0

    local -u word=$1       # uppercase the first parameter
    shift
    local blocks=("[email protected]")

    # see if we have a block for the first letter
    local letter=${word:0:1} indices=() i
    for (( i=0; i<${#blocks[@]}; i++ )); do
        if [[ ${blocks[i]} == *$letter* ]]; then
            indices+=($i)
        fi
    done
    (( ${#indices[@]} == 0 )) && return 1

    local tmp
    for i in ${indices[@]}; do
        tmp=( "${blocks[@]}" )
        unset "tmp[$i]"
        can_build_word_rec "${word:1}" "${tmp[@]}" && return 0
    done

    return 1
}

words=( "" A BARK Book treat COMMON Squad confuse )
for word in "${words[@]}"; do
    can_build_word "$word" "${blocks[@]}" && ans=yes || ans=no
    printf "%s\t%s\n" "$word" $ans
done


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program addAetB.s   */

/*******************************************/
/* Constantes                              */
/*******************************************/
.equ STDOUT, 1                // linux output
.equ WRITE,  64               // call system Linux 64 bits
.equ EXIT,   93               // call system Linux 64 bits

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessError:     .asciz "Error : addAetB <number1> <number2>\n"
szMessResult:  .asciz "Result = "
szRetourLigne: .asciz "\n"
/*******************************************/
/* Uninitialized data                       */
/*******************************************/
.bss
sZoneConv:                   .skip 100
.text
.global main
main:
    mov fp,sp                     // fp <- adresse début
    ldr x0,[fp]                   // load parameters number in command line
    cmp x0,3                      // number in command line
    blt 99f                       // no -> error
    ldr x0,[fp,16]                // recup address of number 1 in command line
    bl conversionAtoD             // convert string in number in registre x0
    mov x1,x0                     // save number1
    ldr x0,[fp,24]                // recup address of number 2 in command line
    bl conversionAtoD             // convert string in number in registre x0
    mov x2,x0                     // save number2

    add x0,x1,x2                  // addition number1 number2
    ldr x1,qAdrsZoneConv
    bl conversion10S              // result decimal conversion
    ldr x0,qAdrszMessResult
    bl affichageMess              // call function display
    ldr x0,qAdrsZoneConv
    bl affichageMess              // call function display
    ldr x0, qAdrszRetourLigne
    bl affichageMess
    mov x0,0                      // return code OK
    b 100f
99:
    ldr x0, qAdrszMessError       // adresse of message
    bl affichageMess              // call function
    mov x0,1                      // return code error
100:                              // standard end programm
    mov x8,EXIT                   // request to exit program
    svc 0                         // perform the system call
qAdrszMessError:             .quad szMessError
qAdrszMessResult:            .quad szMessResult
qAdrsZoneConv:               .quad sZoneConv
qAdrszRetourLigne:           .quad szRetourLigne
/******************************************************************/
/*     String display with  size compute                          */
/******************************************************************/
/* x0 contains string address (string ended with zero binary) */
affichageMess:
    stp x0,x1,[sp,-16]!        // save  registers
    stp x2,x8,[sp,-16]!        // save  registers
    mov x2,0                   // size counter
1:                             // loop start
    ldrb w1,[x0,x2]            // load a byte
    cbz w1,2f                  // if zero -> end string
    add x2,x2,#1               // else increment counter
    b 1b                       // and loop
2:                             // x2 =  string size
    mov x1,x0                  // string address
    mov x0,STDOUT              // output Linux standard
    mov x8,WRITE               // code call system "write"
    svc 0                      // call systeme Linux
    ldp x2,x8,[sp],16          // restaur  2 registres
    ldp x0,x1,[sp],16          // restaur  2 registres
    ret                        // retour adresse lr x30
/******************************************************************/
/*     Decimal conversion signed                             */
/******************************************************************/
/* x0 contains the value  */
/* x1 contains the address of receiving area  length >= 21 */
/* the receiving area return a string ascii left aligned */
/* et avec un zero final */
/* x0 return length string whitout zero final  */
.equ LGZONECONV,   21
conversion10S:
    stp x5,lr,[sp,-16]!        // save  registers
    stp x3,x4,[sp,-16]!        // save  registers
    stp x1,x2,[sp,-16]!        // save  registers
    cmp x0,0                   // is negative ?
    bge 11f                    // no
    mov x3,'-'                 // yes
    neg x0,x0                  // number inversion
    b 12f
11:
    mov x3,'+'                 // positive number
12:
    strb w3,[x1]
    mov x4,#LGZONECONV         // position last digit
    mov x5,#10                 // decimal conversion
1:                             // loop conversion start
    mov x2,x0                  // copy starting number or successive quotients
    udiv x0,x2,x5              // division by ten
    msub x3,x0,x5,x2           //compute remainder
    add x3,x3,#48              // conversion ascii
    sub x4,x4,#1               // previous position
    strb w3,[x1,x4]            // store digit
    cbnz x0,1b                 // end if quotient = zero

    mov x2,LGZONECONV          // compute string length (21 - dernière position)
    sub x0,x2,x4               // no instruction rsb in 64 bits !!!
                               // move result to area begin
    cmp x4,1
    beq 3f                     // full area ?
    mov x2,1                   // no -> begin area
2:
    ldrb w3,[x1,x4]            // load a digit
    strb w3,[x1,x2]            // and store at begin area
    add x4,x4,#1               // last position
    add x2,x2,#1               // et begin last postion
    cmp x4,LGZONECONV - 1      // end ?
    ble 2b                     // no -> loop
3:
    mov w3,0
    strb w3,[x1,x2]            // zero final
    add x0,x0,1                // string length must take into account the sign
100:
    ldp x1,x2,[sp],16          // restaur  2 registers
    ldp x3,x4,[sp],16          // restaur  2 registers
    ldp x5,lr,[sp],16          // restaur  2 registers
    ret                        // return address lr x30
/******************************************************************/
/*     conversion ascii string to number                          */
/******************************************************************/
/* x0 contains string address ended by 0x0 or 0xA */
/* x0 return the number  */
conversionAtoD:
    stp x5,lr,[sp,-16]!        // save  registers
    stp x3,x4,[sp,-16]!        // save  registers
    stp x1,x2,[sp,-16]!        // save  registers
    mov x1,#0
    mov x2,#10             // factor ten
    mov x4,x0              // save address in x4
    mov x3,#0              // positive signe by default
    mov x0,#0              // init résult to zéro
    mov x5,#0
1:                         // loop to remove space at begin of string
    ldrb w5,[x4],1         // load in w5 string octet
    cbz w5,100f            // string end -> end routine
    cmp w5,#0x0A           // string end -> end routine
    beq 100f
    cmp w5,#' '            // space ?
    beq 1b                 // yes -> loop
2:
    cmp x5,#'-'            // first character is -
    bne 3f
    mov x3,#1              // negative number
    b 4f                   // previous position
3:                         // begin loop compute digit
    cmp x5,#'0'            // character not a digit
    blt 4f
    cmp x5,#'9'            // character not a digit
    bgt 4f
                           // character is a digit
    sub w5,w5,#48

    mul x0,x2,x0           // multiply last result by factor
    smulh x1,x2,x0         // hight
    cbnz x1,99f            // overflow ?
    add x0,x0,x5           // no -> add to result
4:
    ldrb w5,[x4],1         // load new octet and increment to one
    cbz w5,5f              // string end -> end routine
    cmp w5,#0xA            // string end ?
    bne 3b                 // no -> loop
5:
    cmp x3,#1              // test register x3 for signe
    cneg x0,x0,eq          // if equal egal negate value
    cmn x0,0               // carry to zero no error
    b 100f
99:                        // overflow
    adr x0,szMessErrDep
    bl  affichageMess
    cmp x0,0               // carry to one  error
    mov x0,#0              // if error return zéro
100:
    ldp x1,x2,[sp],16      // restaur  2 registers
    ldp x3,x4,[sp],16      // restaur  2 registers
    ldp x5,lr,[sp],16      // restaur  2 registers
    ret                    // retur address lr x30
szMessErrDep:      .asciz "Number too large: overflow of 64 bits. :\n"
.align 4                   // instruction to realign the following routines


report z_sum_a_b.
data: lv_output type i.
selection-screen begin of block input.
  parameters:
    p_first type i,
    p_second type i.
selection-screen end of block input.

at selection-screen output.
  %_p_first_%_app_%-text  = 'First Number: '.
  %_p_second_%_app_%-text = 'Second Number: '.

start-of-selection.
  lv_output = p_first + p_second.
  write : / lv_output.


class Abbreviations {
    static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("days_of_week.txt"), "utf-8"))
        List<String> readAllLines = br.readLines()

        for (int i = 0; i < readAllLines.size(); i++) {
            String line = readAllLines.get(i)
            if (line.length() == 0) continue

            String[] days = line.split(" ")
            if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1))

            Map<String, Integer> temp = new HashMap<>()
            for (String day : days) {
                Integer count = temp.getOrDefault(day, 0)
                temp.put(day, count + 1)
            }
            if (temp.size() < 7) {
                System.out.print(" ∞  ")
                System.out.println(line)
                continue
            }

            int len = 1
            while (true) {
                temp.clear()
                for (String day : days) {
                    String sd
                    if (len >= day.length()) {
                        sd = day
                    } else {
                        sd = day.substring(0, len)
                    }
                    Integer count = temp.getOrDefault(sd, 0)
                    temp.put(sd, count + 1)
                }
                if (temp.size() == 7) {
                    System.out.printf("%2d  %s\n", len, line)
                    break
                }
                len++
            }
        }
    }
}


define cumu(n::integer) => {
	loop(-from=$cache->size,-to=#n+1) => {
		local(r = array(0), l = loop_count)
		loop(loop_count) => {
			protect => { #r->insert(#r->last + $cache->get(#l - loop_count)->get(math_min(loop_count+1, #l - loop_count))) }
		}
		#r->size > 1 ? $cache->insert(#r)
	}
	return $cache->get(#n)
}
define row(n::integer) => {
	// cache gets reset & rebuilt for each row, slower but more accurate
	var(cache = array(array(1)))
	local(r = cumu(#n+1))
	local(o = array)
	loop(#n) => {
		protect => { #o->insert(#r->get(loop_count+1) - #r->get(loop_count)) }
	}
	return #o
}
'rows:\r'
loop(25) => {^
	loop_count + ': '+ row(loop_count)->join(' ') + '\r'
^}

'sums:\r'
with x in array(23, 123, 1234) do => {^
	var(cache = array(array(1)))
	cumu(#x+1)->last
	'\r'
^}


function nog(n)
  local tri = {{1}}
  for r = 2, n do
    tri[r] = {}
    for c = 1, r do
      tri[r][c] = (tri[r-1][c-1] or 0) + (tri[r-c] and tri[r-c][c] or 0)
    end
  end
  return tri
end

function G(n)
  local tri, sum = nog(n), 0
  for _, v in ipairs(tri[n]) do sum = sum + v end
  return sum
end

tri = nog(25)
for i, row in ipairs(tri) do
  print(i .. ":  " .. table.concat(row, " "))
end
print("G(23) = " .. G(23))
print("G(123) = " .. G(123))


···
http://rosettacode.org/wiki/ABC_Problem
···
■ ABC
  § static
    blocks⦂ StringBuffer " BO XK DQ CP NA GT RE TG QD FS
                           JW HU VI AN OB ER FS LY PC ZM"
    ▶ main
    • args⦂ String[]
      for each word in ["A", "BARK", "BOOK", "TREAT",
                        "COMMON", "SQUAD", "CONFUSE"]⦂ String

          System.out.println "⸨word⸩: ⸨canMakeWord word⸩"

    ▶ canMakeWord⦂ boolean
    • word⦂ String
      solution⦂ boolean: word.isEmpty°
      if no solution
        i⦂ int: blocks.indexOf word.substring 0, 1
        🔁 until solution or i < 0
           i: i ÷ 3 × 3 · block index
           block⦂ String: blocks.substring i, i + 3
           blocks.delete i, i + 3 · remove block
           solution: canMakeWord word.substring 1
           blocks.insert i, block · restore block
           i: blocks.indexOf (word.substring 0, 1), i + 3
      return solution


Option Explicit

Sub Main_ABC()
Dim Arr, i As Long

    Arr = Array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE")
    For i = 0 To 6
        Debug.Print ">>> can_make_word " & Arr(i) & " => " & ABC(CStr(Arr(i)))
    Next i
End Sub

Function ABC(myWord As String) As Boolean
Dim myColl As New Collection
Dim NbLoop As Long, NbInit As Long
Dim b As Byte, i As Byte
Const BLOCKS As String = "B,O;X,K;D,Q;C,P;N,A;G,T;R,E;T,G;Q,D;F,S;J,W;H,U;V,I;A,N;O,B;E,R;F,S;L,Y;P,C;Z,M"

    For b = 0 To 19
        myColl.Add Split(BLOCKS, ";")(b), Split(BLOCKS, ";")(b) & b
    Next b
    NbInit = myColl.Count
    NbLoop = NbInit
    For b = 1 To Len(myWord)
        For i = 1 To NbLoop
            If i > NbLoop Then Exit For
            If InStr(myColl(i), Mid(myWord, b, 1)) <> 0 Then
                myColl.Remove (i)
                NbLoop = NbLoop - 1
                Exit For
            End If
        Next
    Next b
    ABC = (NbInit = (myColl.Count + Len(myWord)))
End Function


BYTE FUNC Find(CHAR ARRAY s CHAR c BYTE POINTER err)
  BYTE i
  FOR i=1 TO s(0)
  DO
    IF s(i)=c THEN
      err^=0 RETURN (i)
    FI
  OD
  err^=1
RETURN (0)

INT FUNC Decode(CHAR ARRAY s BYTE start,stop BYTE POINTER err)
  CHAR ARRAY tmp(20),tmp2(20)
  INT value

  IF s(start)='+ THEN
    start==+1
  FI
  SCopyS(tmp,s,start,stop)
  value=ValI(tmp)

  ;Check if conversion failed
  IF value=0 AND s(start)#'0 THEN
    err^=1 RETURN (0)
  FI

  ;Check if value is out of range
  IF value<-1000 OR value>1000 THEN
    err^=1 RETURN (0)
  FI

  err^=0
RETURN (value)

PROC Main()
  CHAR ARRAY s(20)
  BYTE pos,err,err2,value
  INT a,b,sum

  DO
    PrintE("Enter two integer numbers between -1000 and 1000, separated by a space or Q for quit")
    InputS(s)
    IF s(0)=1 AND (s(1)='Q OR s(1)='q) THEN
      EXIT
    FI

    pos=Find(s,' ,@err)
    IF err=0 THEN
      a=Decode(s,1,pos-1,@err)
      b=Decode(s,pos+1,s(0),@err2)
      err=err OR err2
    FI

    IF err=0 THEN
      sum=a+b
      PrintF("Their sum is %I%E",sum)
    ELSE
      PrintE("Invalid input!")
    FI
    PutE();
  OD
RETURN


-- Standard I/O Streams

with Ada.Integer_Text_Io;
procedure APlusB is
   A, B : Integer;
begin
   Ada.Integer_Text_Io.Get (Item => A);
   Ada.Integer_Text_Io.Get (Item => B);
   Ada.Integer_Text_Io.Put (A+B);
end APlusB;


import Data.List (inits, intercalate, transpose)
import qualified Data.Set as S

--------------- MINIMUM ABBREVIATION LENGTH --------------

minAbbrevnLength :: [String] -> Int
minAbbrevlnLength [] = 0
minAbbrevnLength xs =
  length . head . S.toList . head $
    dropWhile ((< n) . S.size) $
      S.fromList
        <$> transpose (inits <$> xs)
  where
    n = length xs

--------------------------- TEST -------------------------
main :: IO ()
main = do
  s <- readFile "./weekDayNames.txt"
  mapM_ putStrLn $
    take 10 $
      intercalate "\t"
        . (<*>)
          [ show . minAbbrevnLength . words,
            id
          ]
        . return
        <$> lines s


NB. y is words in boxes
abbreviation_length =: monad define
 N =. # y
 for_i. i. >: >./ #&> y do.
  NB. if the length of the set of length i prefixes matches the length of the row
  if. N -: # ~. i ({. &>) y do.
   i return.
  end.
 end.
)

NB. use: auto_abbreviate DAY_NAMES
auto_abbreviate =: 3 :0
 y =. y -. CR
 lines =. [;._2 y
 a =. <@([: <;._2 ,&' ');._2 y
 L =. abbreviation_length&> a
 ((' ',~":)&> L) ,"1 lines
)


TriangleLine(n) := map(rhs, Statistics :- Tally(map(x -> x[-1],  combinat:-partition(n)))):
Triangle := proc(m)
            local i;
            for i  from 1 to m do
                print(op(TriangleLine(i)));
            end do
            end proc:


Table[Last /@ [email protected][First /@ IntegerPartitions[n]], {n, 10}] // Grid


for n thru 25 do print(makelist(length(integer_partitions(n-k,k)),k,1,n))$


import "/fmt" for Fmt

var r // recursive
r = Fn.new { |word, bl|
    if (word == "") return true
    var c = word.bytes[0] | 32
    for (i in 0...bl.count) {
        var b = bl[i]
        if (c == b.bytes[0] | 32 || c == b.bytes[1] | 32) {
            bl[i] = bl[0]
            bl[0] = b
            if (r.call(word[1..-1], bl[1..-1])) return true
            var t = bl[i]
            bl[i] = bl[0]
            bl[0] = t
        }
    }
    return false
}

var newSpeller = Fn.new { |blocks|
    var bl = blocks.split(" ")
    return Fn.new { |word| r.call(word, bl) }
}

var sp = newSpeller.call("BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")
for (word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]) {
    System.print("%(Fmt.s(-7, word)) %(sp.call(word))")
}


scope
    local f := trim( io.read() ) split " "; # read a line and split into fields
    local a := tonumber( f[ 1 ] );
    local b := tonumber( f[ 2 ] );
    print( a + b )
epocs


file f;
list l;

f_affix(f, "/dev/stdin");
f_list(f, l, 0);
o_integer(atoi(l[0]) + atoi(l[1]));
o_newline();


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Abbreviations {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("days_of_week.txt");
        List<String> readAllLines = Files.readAllLines(path);
        for (int i = 0; i < readAllLines.size(); i++) {
            String line = readAllLines.get(i);
            if (line.length() == 0) continue;

            String[] days = line.split(" ");
            if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));

            Map<String, Integer> temp = new HashMap<>();
            for (String day : days) {
                Integer count = temp.getOrDefault(day, 0);
                temp.put(day, count + 1);
            }
            if (temp.size() < 7) {
                System.out.print(" ∞  ");
                System.out.println(line);
                continue;
            }

            int len = 1;
            while (true) {
                temp.clear();
                for (String day : days) {
                    String sd;
                    if (len >= day.length()) {
                        sd = day;
                    } else {
                        sd = day.substring(0, len);
                    }
                    Integer count = temp.getOrDefault(sd, 0);
                    temp.put(sd, count + 1);
                }
                if (temp.size() == 7) {
                    System.out.printf("%2d  %s\n", len, line);
                    break;
                }
                len++;
            }
        }
    }
}


import bigints

var cache = @[@[1.initBigInt]]

proc cumu(n: int): seq[BigInt] =
  for m in cache.len .. n:
    var r = @[0.initBigInt]
    for x in 1..m:
      r.add r[r.high] + cache[m-x][min(x, m-x)]
    cache.add r
  result = cache[n]

proc row(n: int): seq[BigInt] =
  let r = cumu n
  result = @[]
  for i in 0 .. <n:
    result.add r[i+1] - r[i]

echo "rows:"
for x in 1..10:
  echo row x

echo "sums:"
for x in [23, 123, 1234, 12345]:
  let c = cumu(x)
  echo x, " ", c[c.high]


let get, sum_unto =
  let cache = ref [||]
  let rec get i j =
    if Array.length !cache < i then
      cache :=
        Array.init i begin fun i ->
          try !cache.(i) with Invalid_argument _ ->
          Array.make (i+1) (Num.num_of_int 0)
        end;
    if Num.(!cache.(i-1).(j-1) =/ num_of_int 0)
    then !cache.(i-1).(j-1) <- sum_unto (i-j) j;
    !cache.(i-1).(j-1)
  and sum_unto i j =
    let rec sum_unto sum i j =
      match (i,j) with
      |(0,0) -> (Num.num_of_int 1)
      |(_,0) -> sum
      |(i,j) when j > i -> sum_unto sum i i
      |(i,j) -> sum_unto Num.(sum +/ (get i j)) i (j-1)
    in
    sum_unto (Num.num_of_int 0) i j
  in
  get, sum_unto

let sum_of_row n = sum_unto n n

let euler_recurrence =
  let cache = ref [||] in
  let rec recurrence = function
    |n when n < 0 -> Num.num_of_int 0
    |0 -> Num.num_of_int 1
    |n ->
        if n >= Array.length !cache then
          cache :=
            Array.init (n+1) (fun i ->
              try !cache.(i) with Invalid_argument _ -> Num.num_of_int 0);
        if Num.(!cache.(n) =/ num_of_int 0)
        then begin
          let rec summing sum = function
            |0 -> sum
            |k ->
                let op = if k mod 2 = 0 then Num.sub_num else Num.add_num in
                let sum = op sum (recurrence (n - k * (3*k - 1) / 2)) in
                let sum = op sum (recurrence (n - k * (3*k + 1) / 2)) in
                summing sum (k-1)
          in
          !cache.(n) <- summing (Num.num_of_int 0) n
        end;
        !cache.(n)
  in
  recurrence

let print i_max =
  for i=1 to i_max do
    print_int (i+1); print_string ": ";
    for j=1 to i do
      print_string (Num.string_of_num (get i j));
      print_char ' ';
    done;
    print_newline ();
  done

let () =
  print 30;
  print_newline ();
  List.iter begin fun i ->
      Printf.printf "%i: %s ?= %s\n" i
        (Num.string_of_num (sum_of_row i))
        (Num.string_of_num (euler_recurrence i));
      flush stdout;
    end
  [23;123;1234;];
  List.iter begin fun i ->
      Printf.printf "%i: %s\n" i
        (Num.string_of_num (euler_recurrence i));
      flush stdout;
    end
  [23;123;1234;12345;123456]


string 0;

char Side1, Side2;
def  Size = 20;
char Avail(Size);

func CanMakeWord(Word);         \returns 'true' if blocks can make Word
char Word;
int  I, Let;
[Let:= Word(0) & $5F;           \get letter and make sure it's uppercase
if Let = 0 then return true;    \if 0 then end of word; return successful
for I:= 0 to Size-1 do          \scan for block that contains letter
    if Avail(I) and (Side1(I) = Let or Side2(I) = Let) then
        [Avail(I):= false;
        if CanMakeWord(Word+1) then return true;
        ];
return false;
];

int  I, J, Words;
[Side1:= "BXDCNGRTQFJHVAOEFLPZ";
 Side2:= "OKQPATEGDSWUINBRSYCM";
Words:= ["A", "bark", "Book", "Treat", "Common", "Squad", "conFuse"];
for J:= 0 to 6 do
    [Text(0, "Can make ^"");  Text(0, Words(J));  Text(0, "^": ");
    for I:= 0 to Size-1 do Avail(I):= true;
    Text(0, if CanMakeWord(Words(J)) then "True" else "False");  CrLf(0);
    ];
]


letters$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"

sub canMake(letters$, word$)
	local i, j, p, n, pairs$(1)

	n = token(letters$, pairs$(), ",")
	word$ = upper$(word$)

	for i = 1 to len(word$)
		for j = 1 to n
			p = instr(pairs$(j), mid$(word$, i, 1))
			if p then
				pairs$(j) = ""
				break
			end if
		next j
		if not p return false
	next i
	return true
end sub

print "a = ", canMake(letters$, "a")	// 1 = true
print "bark = ", canMake(letters$, "Bark")	// 1
print "book = ", canMake(letters$, "BooK")	// 0 = false
print "treat = ", canMake(letters$, "TREAt")	// 1
print "common = ", canMake(letters$, "common")	// 0
print "squad = ", canMake(letters$, "squad")	// 1
print "confuse = ", canMake(letters$, "confuse")	// 1


begin
    comment A+B;
    integer a,b;
    ininteger(0,a); ininteger(0,b);
    outinteger(1,a+b)
end


Array.prototype.hasDoubles = function() {
  let arr = this.slice();
  while (arr.length > 1) {
    let cur = arr.shift();
    if (arr.includes(cur)) return true;
  }
  return false;
}

function getMinAbbrLen(arr) {
  if (arr.length <= 1) return '';
  let testArr = [],
      len = 0, i;
  do {
    len++;
    for (i = 0; i < arr.length; i++)
      testArr[i] = arr[i].substr(0, len);
  } while (testArr.hasDoubles());
  return len;
}

// testing
for (let x = 0; x < list.length; x++) {
  let days = list[x].split(' '),
      l    = getMinAbbrLen(days);
  for (let y = 0; y < days.length; y++)
    days[y] = days[y].substring(0, l);
  document.write(`<p>(${l}): ${days.join('. ')}.</p>`);
}


const text = """
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag
E_djelë E_hënë E_martë E_mërkurë E_enjte E_premte E_shtunë
Ehud Segno Maksegno Erob Hamus Arbe Kedame
Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit
Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat
domingu llunes martes miércoles xueves vienres sábadu
Bazar_gÜnÜ Birinci_gÜn Çkinci_gÜn ÜçÜncÜ_gÜn DÖrdÜncÜ_gÜn Bes,inci_gÜn Altòncò_gÜn
Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat
Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar
Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota
Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn
nedelia ponedelnik vtornik sriada chetvartak petak sabota
sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk
Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte
Dzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee
dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn
Dimanch Lendi Madi Mèkredi Jedi Vandredi Samdi
nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota
nede^le ponde^lí úterÿ str^eda c^tvrtek pátek sobota
Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee
s0ndag mandag tirsdag onsdag torsdag fredag l0rdag
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
Diman^co Lundo Mardo Merkredo ^Jaùdo Vendredo Sabato
pÜhapäev esmaspäev teisipäev kolmapäev neljapäev reede laupäev

Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata
sunnudagur mánadagur tÿsdaguy mikudagur hósdagur friggjadagur leygardagur
Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh
sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai
dimanche lundi mardi mercredi jeudi vendredi samedi
Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon
Domingo Segunda_feira Martes Mércores Joves Venres Sábado
k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag
Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato
ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar
pópule pó`akahi pó`alua pó`akolu pó`ahá pó`alima pó`aono
Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat
ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar
vasárnap hétfö kedd szerda csütörtök péntek szombat
Sunnudagur Mánudagur ╞riδjudagur Miδvikudagar Fimmtudagur FÖstudagur Laugardagur
sundio lundio mardio merkurdio jovdio venerdio saturdio
Minggu Senin Selasa Rabu Kamis Jumat Sabtu
Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato
Dé_Domhnaigh Dé_Luain Dé_Máirt Dé_Ceadaoin Dé_ardaoin Dé_hAoine Dé_Sathairn
domenica lunedí martedí mercoledí giovedí venerdí sabato
Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi
Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il
Dies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien
Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis
Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi
xing-_qi-_rì xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù
Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam
Jabot Manre Juje Wonje Taije Balaire Jarere
geminrongo minòmishi mártes mièrkoles misheushi bèrnashi mishábaro
Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu
sφndag mandag tirsdag onsdag torsdag fredag lφrdag
lo_dimenge lo_diluns lo_dimarç lo_dimèrcres lo_dijòus lo_divendres lo_dissabte
djadomingo djaluna djamars djarason djaweps djabièrna djasabra
Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota
Domingo segunda-feire terça-feire quarta-feire quinta-feire sexta-feira såbado
Domingo Lunes martes Miercoles Jueves Viernes Sabado
Duminicª Luni Mart'i Miercuri Joi Vineri Sâmbªtª
voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota
Sunday Di-luain Di-màirt Di-ciadain Di-ardaoin Di-haoine Di-sathurne
nedjelja ponedjeljak utorak sreda cxetvrtak petak subota
Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo
Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-
nedel^a pondelok utorok streda s^tvrtok piatok sobota
Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota
domingo lunes martes miércoles jueves viernes sábado
sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday
Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi
söndag måndag tisdag onsdag torsdag fredag lordag
Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado
Lé-pài-jít Pài-it Pài-jï Pài-sañ Pài-sì Pài-gÖ. Pài-lák
wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao
Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso
Pazar Pazartesi Sali Çar,samba Per,sembe Cuma Cumartesi
nedilya ponedilok vivtorok sereda chetver pyatnytsya subota
Chu?_Nhâ.t Thú*_Hai Thú*_Ba Thú*_Tu* Thú*_Na'm Thú*_Sáu Thú*_Ba?y
dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn
Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw
iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo
zuntik montik dinstik mitvokh donershtik fraytik shabes
iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo
Dies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
Bazar_gÜnÜ Bazar_ærtæsi Çærs,ænbæ_axs,amò Çærs,ænbæ_gÜnÜ CÜmæ_axs,amò CÜmæ_gÜnÜ CÜmæ_Senbæ
Sun Moon Mars Mercury Jove Venus Saturn
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend
Domingo Luns Terza_feira Corta_feira Xoves Venres Sábado
Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum
xing-_qi-_tiàn xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù
djadomingu djaluna djamars djarason djaweps djabièrnè djasabra
Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau"""

function processweek(txt)
    for lin in split(txt, "\n")
        print(lin)
        if length(lin) < 7
            println("A blank line returns \"\", a blank string.")
            continue
        end
        words = map(x->"$x", split(lin, r"\s+"))
        minlen = minimum(map(length, words))
        abbrev = fill("", length(words))
        for i in 1:minlen
            if length(unique(wrd -> split(wrd, "")[1:i], words)) == length(words)
                for (k, word) in enumerate(words)
                    abbrev[k] = join(split(word, "")[1:i], "")
                end
                println(" => ", abbrev, ", which are length ", i)
                break
            elseif i == minlen
                println(" => Could not find abbreviations for the week")
            end
        end
    end
end

processweek(text)


(define (nine-billion-names row column)
   (cond
      ((<= row 0) 0)
      ((<= column 0) 0)
      ((< row column) 0)
      ((= row 1) 1)
      (else
         (let ((addend (nine-billion-names (- row 1) (- column 1)))
               (augend (nine-billion-names (- row column) column)))
	         (+ addend augend)))))

(define (print-row row)
   (for-each (lambda (x)
         (display (nine-billion-names row x))
         (display " "))
      (iota row 1)))

(define (print-triangle rows)
   (for-each (lambda (x)
         (print-row x)
         (print))
      (iota rows 1)))

(print-triangle 25)


row(n)=my(v=vector(n)); forpart(i=n,v[i[#i]]++); v;
show(n)=for(k=1,n,print(row(k)));
show(25)
apply(numbpart, [23,123,1234,12345])
plot(x=1,999.9, numbpart(x\1))


var blocks=T("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
	     "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );

fcn can_make_word(word){
   fcn(blks,word){
      if (not word) return(True);  // bottom of recursion
      foreach b in (blks){ n:=__bWalker.idx;
	 if(not b.holds(word[0])) continue; // letter not on this block
	 blks.del(n);		// remove this block from pile
	 if (self.fcn(blks,word[1,*])) return(True);  // try remaining blocks
	 blks.insert(n,b);	// put block back in pile: backtracking
      }
      False;   // out of blocks but not out of word
   }(blocks.copy(),word.toUpper())
}

foreach word in (T("","A","BarK","BOOK","TREAT","COMMON","SQUAD","Confuse","abba")){
   can_make_word(word).println(": ",word);
}


module Main;
type
	Block = record
		l,r: char;
		used: boolean;
	end Block;

var
	blocks: array 20 of Block;

procedure Exists(c: char): boolean;
var
	i: integer;
	r: boolean;
begin
	r := false;i := 0;
	while ~r & (i < len(blocks)) do
		if ~(blocks[i].used) then
			r := (blocks[i].l = cap(c)) or (blocks[i].r = cap(c));
			blocks[i].used := r;
		end;
		inc(i)
	end;
	return r
end Exists;

procedure CanMakeWord(s: string);
var
	i: integer;
	made: boolean;
begin
	made := true;
	for i := 0 to len(s) - 1 do
		made := made & Exists(s[i])
	end;
	writeln(s:20,"?",made);
	Clean()
end CanMakeWord;

procedure Clean();
var
	i: integer;
begin
	for i := 0 to len(blocks) - 1 do
		blocks[i].used := false
	end
end Clean;

procedure InitBlock(i:integer;l,r:char);
begin
	blocks[i].l := l;blocks[i].r := r;
	blocks[i].used := false;
end InitBlock;

procedure Init;
begin
	InitBlock(0,'B','O');
	InitBlock(1,'X','K');
	InitBlock(2,'D','Q');
	InitBlock(3,'C','Q');
	InitBlock(4,'N','A');
	InitBlock(5,'G','T');
	InitBlock(6,'R','E');
	InitBlock(7,'T','G');
	InitBlock(8,'Q','D');
	InitBlock(9,'F','S');
	InitBlock(10,'J','W');
	InitBlock(11,'H','U');
	InitBlock(12,'V','I');
	InitBlock(13,'A','N');
	InitBlock(14,'O','B');
	InitBlock(15,'E','R');
	InitBlock(16,'F','S');
	InitBlock(17,'L','Y');
	InitBlock(18,'P','C');
	InitBlock(19,'Z','M')
end Init;

begin
	Init();
	CanMakeWord("A");
	CanMakeWord("BARK");
	CanMakeWord("BOOK");
	CanMakeWord("TREAT");
	CanMakeWord("COMMON");
	CanMakeWord("confuse");
end Main.


begin
    integer a, b;
    read( a, b );
    write( a + b )
end.


#include <hbasic.h>

#import lib/input.bas.lib
#include include/input.h

Begin
  Token Init
  Cls
  Locate(5,1),Print(Utf8$("Ingrese dos números, separados por espacio: "))
  msg=""
  LocCol(45),Let( msg := ReadString(msg))
  Token Sep(" ")
  Print("Suma : ", Token(1),Val(Token$(msg)) Plus (Token(2),Val(Token$(msg))), Newl)
End


// version 1.1.4-3

import java.io.File

val r = Regex("[ ]+")

fun main(args: Array<String>) {
    val lines = File("days_of_week.txt").readLines()
    for ((i, line) in lines.withIndex()) {
        if (line.trim().isEmpty()) {
            println()
            continue
        }
        val days = line.trim().split(r)
        if (days.size != 7) throw RuntimeException("There aren't 7 days in line ${i + 1}")
        if (days.distinct().size < 7) { // implies some days have the same name
            println(" ∞  $line")
            continue
        }
        var len = 1
        while (true) {
            if (days.map { it.take(len) }.distinct().size ==  7) {
                println("${"%2d".format(len)}  $line")
                break
            }
            len++
        }
    }
}


#!/bin/ksh

# Abbreviations, automatic

#	# Variables:
#
dow_file='../dow'

typeset -T Dow_T=(
	typeset -a -h	"Week day name array"			dow
	typeset -si -h	"minimum length abbreviation"	minabv

	function init_dow {
		_.minabv=$1
		_.dow=( $2 )
	}

	function print_wk {
		typeset i ; typeset -si i

		printf "(%d)  " ${_.minabv}
		for((i=0; i<${#_.dow[*]}; i++)); do
			printf "%${_.minabv}s " ${_.dow[i]:0:${_.minabv}}
		done
		printf "\n"
	}
)

#	# Functions:
#
#	# Function _file2arr(fn, arr) - read file fn into arr
#
function _file2arr {
	typeset _fn ; _fn="$1"
	typeset _arr ; nameref _arr="$2"
	typeset _i ; typeset -si _i=0

	while read; do
		_arr[_i++]="$REPLY"
	done < ${_fn}

}

#	# Function _minabbr(buff) - return the min length abbr for items in buff
#
function _minabbr {
	typeset _buf ; _buf="$1"
	typeset _i _flg ; typeset -si _i=0 _cnt
	typeset _item _list _abr

	until (( _cnt == 7 )); do
		unset _list
		_cnt=0
		(( _i++ ))
		for _item in ${_buf}; do
			_abr=${_item:0:${_i}}
			[[ ${_abr} == @(${_list}) ]] && break
			_list+="${_abr}|"
			(( _cnt++ ))
		done
	done

	echo ${_i}
}

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

typeset -a dow langs
_file2arr "${dow_file}" dow

for ((i=0; i<${#dow[*]}; i++)); do
	(( ! ${#dow[i]} )) && { print "Blank Input, line $((i+1))" ; continue ;}
	alen=$(_minabbr "${dow[i]}")
	Dow_T langs[i]
	langs[i].init_dow ${alen} "${dow[i]}"

	(( $((RANDOM%100+1))<=5 )) && { printf "%d. " $((i+1)) ; langs[i].print_wk ;}
done


use ntheory qw/:all/;

sub triangle_row {
  my($n,@row) = (shift);
  # Tally by first element of the unrestricted integer partitions.
  forpart { $row[ $_[0] - 1 ]++ } $n;
  @row;
}

printf "%2d: %s\n", $_, join(" ",triangle_row($_)) for 1..25;
print "\n";
say "P($_) = ", partitions($_) for (23, 123, 1234, 12345);


-- demo\rosetta\9billionnames.exw
with javascript_semantics
sequence cache = {{1}}
function cumu(integer n)
sequence r
    for l=length(cache) to n do
        r = {0}
        for x=1 to l do
            r = append(r,r[-1]+cache[l-x+1][min(x,l-x)+1])
        end for
        cache = append(cache,r)
    end for
    return cache[n]
end function

function row(integer n)
sequence r = cumu(n+1)
sequence res = repeat(0,n)
    for i=1 to n do
        res[i] = r[i+1]-r[i]
    end for
    return res
end function

for i=1 to 25 do
    puts(1,repeat(' ',50-2*i))
    sequence r = row(i)
    for j=1 to i do
        printf(1,"%4d",r[j])
    end for
    puts(1,"\n")
end for


10 LET b$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
20 READ p
30 FOR c=1 TO p
40 READ p$
50 GO SUB 100
60 NEXT c
70 STOP
80 DATA 7,"A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"
90 REM Can make?
100 LET u$=b$
110 PRINT "Can make word ";p$;"? ";
120 FOR i=1 TO LEN p$
130 FOR j=1 TO LEN u$
140 IF p$(i)=u$(j) THEN GO SUB 200: GO TO 160
150 NEXT j
160 IF j>LEN u$ THEN PRINT "No": RETURN
170 NEXT i
180 PRINT "Yes": RETURN
190 REM Erase pair
200 IF j/2=INT (j/2) THEN LET u$(j-1 TO j)="  ": RETURN
210 LET u$(j TO j+1)="  ": RETURN


static Integer sumOfTwoNums(Integer A, Integer B) {
    return A + B;
}

System.debug('A = 50 and B = 25: ' + sumOfTwoNums(50, 25));
System.debug('A = -50 and B = 25: ' +sumOfTwoNums(-50, 25));
System.debug('A = -50 and B = -25: ' +sumOfTwoNums(-50, -25));
System.debug('A = 50 and B = -25: ' +sumOfTwoNums(50, -25));

'''Output'''
A = 50 and B = 25: 75
A = -50 and B = 25: -25
A = -50 and B = -25: -75
A = 50 and B = -25: 25


function split(line)
    local wa = {}
    for i in string.gmatch(line, "%S+") do
        table.insert(wa, i)
    end
    return wa
end

-- main
local file = assert(io.open("days_of_week.txt", "r"))
io.input(file)

local line_num = 0
while true do
    local line = io.read()
    if line == nil then break end
    line_num = line_num + 1

    if string.len(line) > 0 then
        local days = split(line)
        if #days ~= 7 then
            error("There aren't 7 days in line "..line_num)
        end

        local temp = {}
        for i,day in pairs(days) do
            if temp[day] ~= nil then
                io.stderr:write(" ∞  "..line.."\n")
            else
                temp[day] = true
            end
        end

        local length = 1
        while length < 50 do
            temp = {}
            local count = 0
            for i,day in pairs(days) do
                local key = string.sub(day, 0, length)
                if temp[key] ~= nil then break end
                temp[key] = true
                count = count + 1
            end
            if count == 7 then
                print(string.format("%2d  %s", length, line))
                break
            end
            length = length + 1
        end
    end
end


(*This function gives all 'heads' of str of length 1 to maxLength. Since the input data was formatted to use underscores in place of spaces, there is an edge case where distinct abbreviations derived from the input data would actually not be distinct in the 'real' abbreviations. See further comments below regarding the difference between my output and the output of other solutions.*)
Abbreviations[maxLength_Integer][str_String]:=Array[StringTake[StringPadRight[str,maxLength,"_"],#]&,maxLength];

(*Given a list of words (weekday names), this function expands each to its abbreviations and then picks the first 'column' that contains no duplicates. The failure case isn't really needed for this specific data, but I included it for completeness.*)
ShortestUniqueAbbreviations[list:{__String}]:=
 With[
  {maxLength=Max[StringLength/@list]},
  SelectFirst[Transpose[Abbreviations[maxLength]/@list],DuplicateFreeQ,"no unique abbreviations possible"]
 ];

(*This function gives the minimum number of characters to distinguish the words (weekday names). It assumes data is a space separated list of weekday names (i.e. one line of the input data). I would prefer to ignore blank lines, but the spec says to return an empty string. Since all of the abbreviations should be the same length because of the padding done by Abbreviations, I could have just selected the first item rather than taking the Max of the StringLength. However, the implmenetation of Abbreviations was very specific to the format of the input data, and so using Max seemed a bit safer and more general.*)
RequiredAbbreviationLength[""]="";
RequiredAbbreviationLength[input_String]:=Max[StringLength/@ShortestUniqueAbbreviations[StringSplit[input]]];


/# Rosetta Code problem: http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
by Galileo, 05/2022 #/

include ..\Utilitys.pmt

cls

def nine_billion_names >ps
    0 ( tps dup ) dim

    1 ( 1 1 ) sset

    ( 2 tps ) for var i
        ( 1 i ) for var j
            ( i 1 - j 1 - ) sget >ps ( i j - j ) sget ps> + ( i j ) sset
        endfor
    endfor

    ( 1 tps ) for var i
        tps 2 * i 2 * 2 - - >ps
        ( 1 i ) for var j
            ( i j ) sget tostr len nip 1 swap - tps j 4 * + + i locate ( i j ) sget print
        endfor
        nl
        ps> drop
    endfor
    ps> drop drop
enddef

20 nine_billion_names


import cp.

main =>
  foreach(N in 1..25)
     P = integer_partition(N).reverse,
     G = P.map(sort_down).map(first).counts.to_list.sort.map(second),
     println(G=G.sum)
  end,
  println("Num partitions == sum of rows:"),
  println([partition1(N) : N in 1..25]).

% Get all partitions
integer_partition(N) = find_all(X,integer_partition(N,X)).
integer_partition(N,X) =>
  member(Len,1..N),
  X = new_list(Len),
  X :: 1..N,
  increasing(X),
  sum(X) #= N,
  solve($[split],X).

% Counts the occurrences of the elements in L
counts(L) = Map =>
  Map = new_map(),
  foreach(I in L)
    Map.put(I,Map.get(I,0)+1)
  end.


import sets
import unicode

type Runes = seq[Rune]

var linenum = 0
for line in lines("days.txt"):
  inc linenum
  if line.len > 0:

    # Extract the day names and store them in a sorted list of sequences of runes.
    var days: seq[Runes]
    for day in line.splitWhitespace():
      days.add(day.toLower.toRunes)
    if days.len != 7:
      echo "Wrong number of days at line ", linenum

    # Build the abbreviations and store them in a set.
    var index = 0
    while true:
      var abbrevs: HashSet[seq[Rune]]
      for day in days:
        abbrevs.incl(day[0..min(index, day.high)])
      if abbrevs.card == 7:
        # All abbreviations are different: fine!
        break
      inc index
    echo index + 1, " ", line

  else:
    echo line


use System.IO.File;
use Collection;

class Abbreviations  {
  function : Main(args : String[]) ~ Nil {
    if(args->Size() = 1) {
      Go(args[0]);
    };
  }

  function : Go(file : String) ~ Nil {
    reader := FileReader->New(file);
    leaving {
      reader->Close();
    };

    cache := StringMap->New();
    line := reader->ReadString();
    while(line <> Nil) {
      if(line->Size() > 0) {
        days := line->Split(" ");

        cache->Empty();
        each(i : days) {
          day := days[i];
          cache->Insert(day, IntHolder->New(1));
        };

        if(cache->Size() < 7) {
          " ∞ {$line}"->PrintLine();
        };

        len := 1;
        while(true) {
          cache->Empty();
          each(i : days) {
            day := days[i];
            sd : String;
            if(len >= day->Size()) {
              sd := day;
            }
            else {
              sd := day->SubString(len);
            };

            count := cache->Find(sd)->As(IntHolder);
            if(count = Nil) {
              cache->Insert(sd, IntHolder->New(1));
            }
            else {
              count->Inc();
            };
          };

          if(cache->Size() = 7) {
            "{$len} {$line}"->PrintLine();
            break;
          };
          len += 1;
        };
      };

      line := reader->ReadString();
    };
  }
}


(de row (N)
   (let C '((1))
      (do N
         (push 'C (grow C)) )
      (mapcon
         '((L)
            (when (cdr L)
               (cons (- (cadr L) (car L))) ) )
         (car C) ) ) )

(de grow (Lst)
   (let (L (length Lst)  S 0)
      (cons
         0
         (mapcar
            '((I X)
               (inc 'S
                  (get I (inc (min X (- L X)))) ) )
            Lst
            (range 1 L) ) ) ) )

(de sumr (N)
   (let
      (K 1
         S 1
         O (cons 1 (need N 0))
         D
         (make
            (while
               (<
                  (* K (dec (* 3 K)))
                  (* 2 N) )
               (link (list (dec (* 2 K)) S))
               (link (list K S))
               (inc 'K)
               (setq S (- S)) ) ) )
      (for (Y O (cdr Y) (cdr Y))
         (let Z Y
            (for L D
               (inc
                  (setq Z (cdr (nth Z (car L))))
                  (* (car Y) (cadr L)) ) ) ) )
      (last O) ) )

(for I 25
   (println (row I)) )

(bench
   (for I '(23 123 1234 12345)
      (println (sumr I)) ) )

(bye)


array cumu(int n) {
	array(array(int)) cache = ({({1})});

	for(int l = sizeof(cache); l < n + 1; l++) {
		array(int) r = ({0});
		for(int x = 1; x < l + 1; x++) {
			r = Array.push(r, r[-1] + cache[l - x][min(x, l-x)]);
		}
		cache = Array.push(cache, r);
	}
	return cache[n];
}

array row(int n) {
	array r = cumu(n);
	array res = ({});
	for (int i = 0; i < n; i++) {
		res = Array.push(res, r[i+1] - r[i]);
	}
	return res;
}

int main() {
	write("rows:\n");
	for(int x = 1; x < 11; x++) {
		write("%2d: ", x);
		for(int i = 0; i < sizeof(row(x)); i++) {
			write((string)row(x)[i] + " ");
		}
		write("\n");
	}

	array(int) sum_n = ({23, 123, 1234, 12345});
	write("\nsums:\n");
	for (int x = 0; x < sizeof(sum_n); x++) {
		write((string)sum_n[x] + " " + (string)cumu(sum_n[x])[-1] + "\n");
	}
	return 0;
}


on run argv
    try
        return ((first item of argv) as integer) + (second item of argv) as integer
    on error
        return "Usage with -1000 <= a,b <= 1000: " & tab & " A+B.scpt a b"
    end try
end run


use strict;
use utf8;
binmode STDOUT, ":utf8";

sub auto_abbreviate {
    my($string) = @_;
    my @words = split ' ', $string;
    my $max = 0;
    return '' unless @words;
    map { $max = length($_) if length($_) > $max } @words;
    for $i (1..$max) {
        my %seen;
        return $i if @words == grep {!$seen{substr($_,0,$i)}++} @words;
    }
    return '∞';
}

open $fh, '<:encoding(UTF-8)', 'DoWAKA.txt';
while ($_ = <$fh>) {
    print "$.) " . auto_abbreviate($_) . '  ' . $_;
}


constant lines = get_text("abbrev_auto.txt",GT_LF_STRIPPED)

for i=1 to length(lines) do
    string li = lines[i]
    if length(li) then
        sequence days = split(li,no_empty:=true)
        if length(days)!=7 then ?9/0 end if
        integer len = 1
        for j=1 to 7 do
            for k=j+1 to 7 do
                for m=1 to min(length(days[j]),length(days[k])) do
                    if days[j][m]!=days[k][m] then exit end if
                    len = max(len,m+1)
                end for
            end for
        end for
        printf(1,"%d: %s\n",{len,li})
    end if
end for


Define nMax.i=25, n.i, k.i
Dim pfx.s(1)

Procedure.s Sigma(sx.s, sums.s)
  Define i.i, v1.i, v2.i, r.i
  Define s.s, sa.s
  sums=ReverseString(sums) : s=ReverseString(sx)
  For i=1 To Len(s)*Bool(Len(s)>Len(sums))+Len(sums)*Bool(Len(sums)>=Len(s))
    v1=Val(Mid(s,i,1))
    v2=Val(Mid(sums,i,1))
    r+v1+v2
    sa+Str(r%10)
    r/10
  Next i
  If r : sa+Str(r%10) : EndIf
  ProcedureReturn ReverseString(sa)
EndProcedure

Procedure.i Adr(row.i,col.i)
  ProcedureReturn ((row-1)*row/2+col)*Bool(row>0 And col>0)
EndProcedure

Procedure Triangle(row.i,Array pfx.s(1))
  Define n.i,k.i
  Define zs.s
  nMax=row
  ReDim pfx(Adr(nMax,nMax))
  For n=1 To nMax
    For k=1 To n
      If k>n    : pfx(Adr(n,k))="0"    : Continue : EndIf
      If n=k    : pfx(Adr(n,k))="1"    : Continue : EndIf
      If k<=n/2
        zs=""
        zs=Sigma(pfx(Adr(n-k,k)),zs)
        zs=Sigma(pfx(Adr(n-1,k-1)),zs)
        pfx(Adr(n,k))=zs
      Else
        pfx(Adr(n,k))=pfx(Adr(n-1,k-1))
      EndIf
    Next k
  Next n
EndProcedure

Procedure.s sum(row.i, Array pfx.s(1))
  Define s.s
  Triangle(row, pfx())
  For n=1 To row
    s=Sigma(pfx(Adr(row,n)),s)
  Next n
  ProcedureReturn RSet(Str(row),5,Chr(32))+" : "+s
EndProcedure

OpenConsole()

Triangle(nMax, pfx())
For n=1 To nMax
  Print(Space(((nMax*4-1)-(n*4-1))/2))
  For k=1 To n
    Print(RSet(pfx(Adr(n,k)),3,Chr(32))+Space(1))
  Next k
  PrintN("")
Next n
PrintN("")
PrintN(sum(23,pfx()))
PrintN(sum(123,pfx()))
PrintN(sum(1234,pfx()))
PrintN(sum(12345,pfx()))
Input()


(: Standard input-output streams :)
use std, array
Cfunc scanf "%d%d" (&val int a) (&val int b)
printf "%d\n" (a + b)


arm-linux-gnueabi-as src.s -o src.o && arm-linux-gnueabi-gcc -static src.o -o run && qemu-arm run


while ø [
	x: map split.words input "give me 2 numbers:" 'x -> to :integer x
	print add x\0 x\1
]


import util.

max_length(Words) = Max =>
    Lengths = [len(W): W in Words],
    Max = max(Lengths).

min_abbr([]) = 0.

min_abbr(Line) = Min =>
    Words = split(Line),
    Max = max_length(Words),
    I = 0,
    Abbrevs = [],
    Uniqs = [],
    do
        I := I + 1,
        Abbrevs := [slice(W, 1, I): W in Words],
        Uniqs := sort_remove_dups(Abbrevs)
    while (I < Max, len(Abbrevs) > len(Uniqs)),
    Min = I.

main(Args) =>
    File = Args[1],
    Reader = open(File),
    while (not at_end_of_stream(Reader))
        Line := read_line(Reader),
        Min := min_abbr(Line),
        if (Min > 0) then
            printf("%d %s\n", Min, Line)
        else
            nl
        end
    end.


minimum_abbreviation_length(Day_names, Min_length):-
	sort(Day_names, Sorted_names),
	minimum_abbreviation_length(Sorted_names, Min_length, 1).

minimum_abbreviation_length([_], Min_length, Min_length):- !.
minimum_abbreviation_length([Name1, Name2|Rest], Min_length, M1):-
	common_prefix_length(Name1, Name2, Length),
	M2 is max(M1, Length + 1),
	minimum_abbreviation_length([Name2|Rest], Min_length, M2).

common_prefix_length(String1, String2, Length):-
	string_chars(String1, Chars1),
	string_chars(String2, Chars2),
	common_prefix_length1(Chars1, Chars2, Length, 0).

common_prefix_length1([], _, Length, Length):-!.
common_prefix_length1(_, [], Length, Length):-!.
common_prefix_length1([C1|_], [C2|_], Length, Length):-
	C1 \= C2,
	!.
common_prefix_length1([C|Chars1], [C|Chars2], Length, L1):-
	L2 is L1 + 1,
	common_prefix_length1(Chars1, Chars2, Length, L2).

to_upper_case([], []):-!.
to_upper_case([String|S], [Upper_case|U]):-
    string_upper(String, Upper_case),
    to_upper_case(S, U).

process_line(""):-
    nl,
    !.
process_line(Line):-
    split_string(Line, "\s\t", "\s\t", Day_names),
    to_upper_case(Day_names, Upper),
    minimum_abbreviation_length(Upper, Length),
    writef('%w %w\n', [Length, Line]).

process_stream(Stream):-
    read_line_to_string(Stream, String),
    String \= end_of_file,
    !,
    process_line(String),
    process_stream(Stream).
process_stream(_).

process_file(File):-
    open(File, read, Stream),
    process_stream(Stream),
    close(Stream).

main:-
    process_file("days_of_week.txt").


cache = [[1]]
def cumu(n):
    for l in range(len(cache), n+1):
        r = [0]
        for x in range(1, l+1):
            r.append(r[-1] + cache[l-x][min(x, l-x)])
        cache.append(r)
    return cache[n]

def row(n):
    r = cumu(n)
    return [r[i+1] - r[i] for i in range(n)]

print "rows:"
for x in range(1, 11): print "%2d:"%x, row(x)

print "\nsums:"
for x in [23, 123, 1234, 12345]: print x, cumu(x)[-1]


#lang racket

(define (cdr-empty ls) (if (empty? ls) empty (cdr ls)))

(define (names-of n)
  (define (names-of-tail ans raws-rest n)
    (if (zero? n)
        ans
        (names-of-tail (cons 1 (append (map +
                                            (take ans (length raws-rest))
                                            (map car raws-rest))
                                       (drop ans (length raws-rest))))
                       (filter (compose not empty?)
                               (map cdr-empty (cons ans raws-rest)))
                       (sub1 n))))
  (names-of-tail '() '() n))

(define (G n) (foldl + 0 (names-of n)))

(module+ main
  (build-list 25 (compose names-of add1))
  (newline)
  (map G '(23 123 1234)))


(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
staload UN = $UNSAFE
//
(* ****** ****** *)

staload "libc/SATS/stdio.sats"

(* ****** ****** *)

implement
main0() = let
  var A: int
  var B: int
  val () =
  $extfcall
    (void, "scanf", "%d%d", [email protected], [email protected])
  // end of [val]
in
   println! ($UN.cast2int(A) + $UN.cast2int(B))
end // end of [main0]

(* ****** ****** *)


Gui, Add, Edit, vEdit ;Enter your A+B, i.e. 5+3 or 5+3+1+4+6+2
Gui, Add, Button, gAdd, Add
Gui, Add, Edit, ReadOnly x+10 w80
Gui, Show
return

Add:
Gui, Submit, NoHide
Loop, Parse, Edit, + ;its taking each substring separated by "+" and its storing it in A_LoopField
	var += A_LoopField ;here its adding it to var
GuiControl, Text, Edit2, %var% ;here it displays var in the second edit control
var := 0 ;here it makes sure var is 0 so it won't contain the value from the previous addition
return


EnableExplicit
#TZ="|"
#FZ="@"
#WORD_SEPARATOR=Chr(32)
Declare.i abbreviations(txt.s)
Define dataset.s, line_number.i, line_cache.s, result.i, word_index.i, word.s

If OpenConsole("abbreviations-automatic") And ReadFile(0,"./Data/days_of_the_week.txt")
  dataset=ReadString(0,#PB_UTF8|#PB_File_IgnoreEOL) : CloseFile(0)
  line_number=1
  Repeat
    line_cache=StringField(dataset,line_number,#LF$)
    If Len(line_cache)=0
      PrintN("")
    Else
      result=abbreviations(line_cache) : PrintN(RSet(Str(result),3)+": "+line_cache)
      word_index=1
      word=StringField(line_cache,word_index,#WORD_SEPARATOR)
      If word : Print(Space(5)) : EndIf
      While word
        Print(LSet(Left(word,result),Len(word)+1))
        word_index+1 : word=StringField(line_cache,word_index,#WORD_SEPARATOR)
      Wend
      PrintN("")
    EndIf
    line_number+1
  Until line_number>CountString(dataset,#LF$)
  Input()
EndIf

Procedure.b CompareLetters(sfield.s,letters.i,separator.s=#WORD_SEPARATOR)
  Define word_index.i, buf.s
  For word_index=1 To CountString(sfield,separator)+1
    buf+LSet(Left(StringField(sfield,word_index,separator),letters),letters,#FZ)+#TZ
  Next
  For word_index=1 To CountString(buf,#TZ)
    If CountString(buf,StringField(buf,word_index,#TZ))>1 : ProcedureReturn #True : EndIf
  Next
  ProcedureReturn #False
EndProcedure

Procedure.i abbreviations(txt.s)
  Define letters.i=1
  While CompareLetters(txt,letters) : letters+1 : Wend
  ProcedureReturn letters
EndProcedure


def shortest_abbreviation_length(line, list_size):
    words = line.split()
    word_count = len(words)
    # Can't give true answer with unexpected number of entries
    if word_count != list_size:
        raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')

    # Find the small slice length that gives list_size unique values
    abbreviation_length = 1
    abbreviations = set()
    while(True):
        abbreviations = {word[:abbreviation_length] for word in words}
        if len(abbreviations) == list_size:
            return abbreviation_length
        abbreviation_length += 1
        abbreviations.clear()

def automatic_abbreviations(filename, words_per_line):
    with open(filename) as file:
        for line in file:
            line = line.rstrip()
            if len(line) > 0:
                length = shortest_abbreviation_length(line, words_per_line)
                print(f'{length:2} {line}')
            else:
                print()

automatic_abbreviations('daysOfWeek.txt', 7)


my @todo = $[1];
my @sums = 0;
sub nextrow($n) {
    for +@todo .. $n -> $l {
        my $r = [];
        for reverse ^$l -> $x {
            my @x := @todo[$x];
            if @x {
                $r.push: @sums[$x] += @x.shift;
            }
            else {
                $r.push: @sums[$x];
            }
        }
        @todo.push($r);
    }
    @todo[$n];
}

say "rows:";
say .fmt('%2d'), ": ", nextrow($_)[] for 1..25;

my @names-of-God = 1, { partition-sum ++$ } … *;
my @names-of-God-adder = lazy [\+] flat 1, ( (1 .. *) Z (1 .. *).map: * × 2 + 1 );
sub partition-sum ($n) {
    sum @names-of-God[$n X- @names-of-God-adder[^(@names-of-God-adder.first: * > $n, :k)]]
        Z× (flat (1, 1, -1, -1) xx *)
}

say "\nsums:";
for 23, 123, 1234, 12345 {
    put $_, "\t",  @names-of-God[$_];
}


;AutoIt Version: 3.2.10.0
$num = "45  54"
consolewrite ("Sum of " & $num & " is: " & sum($num))
Func sum($numbers)
   $numm = StringSplit($numbers," ")
   Return $numm[1]+$numm[$numm[0]]
EndFunc


#lang racket

(require racket/set)

(define (abbr-length ss)
  (for*/first ((l (in-range 1 (string-length (argmax string-length ss))))
               #:when (equal? (sequence-length
                               (for/set ((s ss))
                                 (substring s 0 (min l (string-length s)))))
                              (length ss)))
    l))

(module+ main
  (define report-line
    (match-lambda
      ["" ""]
      [(and s (app string-split ss)) (format "~a ~a" (abbr-length ss) s)]))
  (for-each (compose displayln report-line) (take (file->lines "data.txt") 5)))


sub auto-abbreviate ( Str $string ) {
    return Nil unless my @words = $string.words;
    return $_ if @words».substr(0, $_).Set == @words for 1 .. @words».chars.max;
    return '∞';
}

# Testing
 say ++$, ') ', .&auto-abbreviate, '  ', $_ for './DoWAKA.txt'.IO.lines;


Red []
;; read and convert data to a string - to char conversion is neccessary to avoid
;; illegal utf8 encoding error....

data: collect/into [foreach b read/binary %abbrev.txt [keep to-char b ]] ""
                                           ;; data: read %abbrev.txt - would work, if file was utf-8 encoded ...
foreach line split data newline [           ;; split data in lines at carriage return & line feed:

 if  empty?  trim line [ continue ]         ;; continues at head of loop

 arr: split line space                      ;; now split line in words ; accumulate in array / series

 min: 1                                     ;; preset min length
 until [
                                            ;; head is the first position of series
   if head? arr [m: make map! [] ]          ;; define an empty map (key -value store)

   abbr: copy/part first arr min            ;; copy/part ~  leftstr of first word with length min

   arr: either m/:abbr [                    ;; abbreviation already exists ?
        min: min + 1
        head arr                            ;; reset series position to head
      ][                                    ;; otherwise ....
        m/:abbr: true                       ;; mark abreviation in map as existent
        next arr                            ;; set series position to next word
      ]
  tail? arr                                 ;; this is the until condition , end /tail of  series reached ?
 ]
 print [min line]                           ;; print automatically reduces all words in block
]


Red []

context [
    sum-part: function [nums [block!] count [integer!]][
        out: 0.0
        loop count [
            out: out + nums/1
            if empty? nums: next nums [break]
        ]
        out
    ]
    nums: make map! [1 [1] 2 [1 1]]
    sums: make map! [1 1 2 2]
    set 'names function [row /show /all][
        if row < 1 [cause-error 'user 'message "Argument needs to be >= 1"]
        if show [
            unless nums/:row [names row]
            repeat i row [either all [probe reduce [i nums/:i sums/:i]][print nums/:i]]
        ]
        either sums/:row [sums/:row][
            out: clear []
            half: to integer! row / 2
            if row - 1 > last: length? nums [
                repeat i row - last - 1 [names last + i]
            ]
            repeat col row - 1 [
                either col = (half + 1) [
                    append out at nums/(row - 1) half
                    break
                ][
                    append out sum-part nums/(row - col) col
                ]
            ]
            also sums/:row: sum nums/:row: copy out  clear out
        ]
    ]
]

print "rows: ^/"
names/show 25
print "^/sums: ^/"
probe names 23
probe names 123
probe names 1234


DEFINT A-Z

tryagain:
backhere = CSRLIN
INPUT "", i$
i$ = LTRIM$(RTRIM$(i$))
where = INSTR(i$, " ")
IF where THEN
    a = VAL(LEFT$(i$, where - 1))
    b = VAL(MID$(i$, where + 1))
    c = a + b
    LOCATE backhere, LEN(i$) + 1
    PRINT c
ELSE
    GOTO tryagain
END IF


::aplusb.cmd
@echo off
setlocal
set /p a="A: "
set /p b="B: "
set /a c=a+b
echo %c%
endlocal


/*REXX program finds the minimum length abbreviation for a lists of words (from a file).*/
parse arg uw                                     /*obtain optional arguments from the CL*/
iFID= 'ABBREV_A.TAB'                             /*name of the file that has the table. */
say 'minimum'                                    /*display the first part of the title. */
say 'abbrev' center("days of the week", 80)      /*display the title for the output.    */
say '══════' center("",                 80, '═') /*display separator for the title line.*/
                                                 /* [↓]  process the file until done.   */
     do while lines(iFID)\==0; days=linein(iFID) /*read a line (should contain 7 words).*/
     minLen= abb(days)                           /*find the minimum abbreviation length.*/
     say right(minLen, 4)   '  '    days         /*display a somewhat formatted output. */
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
abb: procedure;  parse arg x;  #=words(x)        /*obtain list of words;  find how many.*/
     if #==0  then return ''                     /*check for a blank line or null line. */
     @.=                                         /*@.   is a stemmed array of the words.*/
     L=0                                         /*L    is the max length  of  "    "   */
        do j=1  for #;         @.j=word(x, j)    /*assign to array for faster processing*/
        L.j=length(@.j);       L= max(L, L.j)    /*find the maximum length of any item. */
        end   /*L*/
                                                 /* [↓]  determine minimum abbrev length*/
        do m=1  for L;         $=                /*for all lengths, find a unique abbrev*/
             do k=1  to #;     a=left(@.k, m)    /*get an abbreviation (with length  M).*/
             if wordpos(a,$)\==0  then iterate M /*test this abbreviation for uniquness.*/
             $=$  a                              /*so far, it's unique; add to the list.*/
             end   /*k*/
        leave m                                  /*a good abbreviation length was found.*/
        end        /*m*/
     return m


require "abbrev"

File.read("daynames.txt").each_line do |line|
  next if line.strip.empty?
  abbr = line.split.abbrev.invert
  puts "Minimum size: #{abbr.values.max_by(&:size).size}", abbr.inspect, "\n"
end


/*REXX program  generates and displays a  number triangle  for partitions of a number.  */
numeric digits 400                               /*be able to handle larger numbers.    */
parse arg N .                                    /*obtain optional argument from the CL.*/
if N==''  then N= 25                             /*N  specified?  Then use the default. */
@.= 0;          @.0= 1;       aN= abs(N)         /*initialize a partition number; AN abs*/
if N==N+0  then say  '         G('aN"):"   G(N)  /*just do this for well formed numbers.*/
                say  'partitions('aN"):"   partitions(aN)          /*do it the easy way.*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
G: procedure; parse arg nn;  !.= 0;    !.4.2= 2;     mx= 1;    aN= abs(nn);    build= nn>0
                do j=1  for aN%2;      !.j.j= 1      /*gen shortcuts for unity elements.*/
                end   /*j*/

                do     t=1  for 1+build;        #.=1 /*generate triangle once or twice. */
                  do   r=1  for aN;   #.2= r % 2     /*#.2  is a shortcut calculation.  */
                    do c=3  to  r-2;  #.c= gen#(r,c)
                    end   /*c*/
                  L= length(mx);      p= 0;     __=  /*__  will be a row of the triangle*/
                      do cc=1  for r; p= p + #.cc    /*only sum the last row of numbers.*/
                      if \build  then iterate        /*should we skip building triangle?*/
                      mx= max(mx, #.cc)              /*used to build the symmetric #s.  */
                      __= __  right(#.cc, L)         /*construct a row of the triangle. */
                      end   /*cc*/
                  if t==1  then iterate              /*Is this 1st time through? No show*/
                  say  center( strip(__),  2 + (aN-1) * (length(mx) + 1) )
                  end       /*r*/                    /* [↑]  center row of the triangle.*/
                end         /*t*/
              return p                               /*return with the generated number.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen#: procedure expose !.;   parse arg x,y             /*obtain the  X and Y  arguments.*/
      if !.x.y\==0  then  return !.x.y                 /*was number generated before ?  */
      if y>x%2  then do;  nx= x+1-(y-x%2)*2-(x//2==0)
                          ny= nx % 2;  !.x.y= !.nx.ny
                          return !.x.y                 /*return the calculated number.  */
                     end                               /* [↑]  right half of triangle.  */
      $= 1                                             /* [↓]   left   "   "     "      */
                          do q=2  for y-1;   xy= x-y;   if q>xy  then iterate
                          if q==2  then $= $  +  xy % 2
                                   else if q==xy-1  then $= $ + 1
                                                    else $= $ + gen#(xy,q)    /*recurse.*/
                          end   /*q*/
      !.x.y=$; return $                                /*use memoization; return with #.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
partitions: procedure expose @.; parse arg n;   if @.n\==0  then return @.n   /* ◄─────┐*/
            $= 0                                         /*Already known?  Return ►────┘*/
                     do k=1  for n                       /*process  N  partitions.      */
                     #= n - (k*3-1) * k % 2              /*calculate a partition number.*/
                     if #<0  then leave                  /*Is it negative?  Then leave. */
                     if @.#==0  then x= partitions(#)    /* [◄] this is a recursive call*/
                                else x= @.#              /*the value is already known.  */
                     #= # - k
                     if #<0  then  y= 0                  /*Is negative?   Then use zero.*/
                             else  if @.#==0  then y= partitions(p)    /*recursive call.*/
                                              else y= @.#
                     if k//2  then $= $ + x + y          /*use this method if K is odd. */
                              else $= $ - x - y          /* "    "     "    " "  " even.*/
                     end   /*k*/                         /* [↑]  Euler's recursive func.*/
            @.n= $;             return $                 /*use memoization;  return num.*/


use Console Math

define Main
    $a Console.Read
    $b Console.Read
    Console.Println Math.Add $a $b
end


/**
 * Abbreviations from tintenalarm.de
 */
use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader};

fn main() {
    let table = read_days("weekdays.txt").expect("Error in Function read_days:");
    for line in table {
        if line.len() == 0 {
            continue;
        };
        let mut max_same = 0;
        for i in 0..(line.len() - 1) {
            for j in i + 1..line.len() {
                max_same = max_same.max(begins_with_num_same_chars(&line[i], &line[j]));
            }
        }
        println!("{}\t{:?}", max_same + 1, line);
    }
}

fn read_days(filename: &str) -> io::Result<Vec<Vec<String>>> {
    let f = File::open(filename)?;
    let reader = BufReader::new(f);
    let mut table: Vec<Vec<String>> = Vec::new();
    for line in reader.lines() {
        let mut days: Vec<String> = Vec::with_capacity(7);
        for day in line?.split_whitespace() {
            days.push(day.to_string());
        }
        table.push(days);
    }
    Ok(table)
}

fn begins_with_num_same_chars(str_a: &str, str_b: &str) -> u32 {
    let mut num = 0;
    for (pos, char_a) in str_a.chars().enumerate() {
        match str_b.chars().nth(pos) {
            Some(char_b) => {
                if char_a == char_b {
                    num = num + 1;
                } else {
                    return num;
                }
            }
            None => return num,
        }
    }
    num
}


# Generate IPF triangle
# Nigel_Galloway: May 1st., 2013.
def g(n,g)
  return 1 unless 1 < g and g < n-1
  (2..g).inject(1){|res,q| res + (q > n-g ? 0 : g(n-g,q))}
end

(1..25).each {|n|
  puts (1..n).map {|g| "%4s" % g(n,g)}.join
}


extern crate num;

use std::cmp;
use num::bigint::BigUint;

fn cumu(n: usize, cache: &mut Vec<Vec<BigUint>>) {
    for l in cache.len()..n+1 {
        let mut r = vec![BigUint::from(0u32)];
        for x in 1..l+1 {
            let prev = r[r.len() - 1].clone();
            r.push(prev + cache[l-x][cmp::min(x, l-x)].clone());
        }
        cache.push(r);
    }
}

fn row(n: usize, cache: &mut Vec<Vec<BigUint>>) -> Vec<BigUint> {
    cumu(n, cache);
    let r = &cache[n];
    let mut v: Vec<BigUint> = Vec::new();

    for i in 0..n {
        v.push(&r[i+1] - &r[i]);
    }
    v
}

fn main() {
    let mut cache = vec![vec![BigUint::from(1u32)]];

    println!("rows:");
    for x in 1..26 {
        let v: Vec<String> = row(x, &mut cache).iter().map(|e| e.to_string()).collect();
        let s: String = v.join(" ");
        println!("{}: {}", x, s);
    }

    println!("sums:");
    for x in vec![23, 123, 1234, 12345] {
        cumu(x, &mut cache);
        let v = &cache[x];
        let s = v[v.len() - 1].to_string();
        println!("{}: {}", x, s);
    }
}


DEFINE PROCEDURE ''ADD'' [A, B]:
BLOCK 0: BEGIN
    OUTPUT <= A + B;
BLOCK 0: END.


10 print "Number 1";
20 input a
30 print "Number 2";
40 input b
50 print a+b


name         := "Abbreviations-automatic"
scalaVersion := "2.13.0"
version      := "0.1"

homepage     := Some(url("http://rosettacode.org/wiki/Abbreviations,_automatic#Scala"))

libraryDependencies += "com.lihaoyi" %% "os-lib" % "0.3.0"


function AbbreviationsAutomatic days
	put 1 into abbreviationLength
	put the number of items in days into len
	repeat forever
		put () into abbreviations
		repeat with each item day in days
			put the first abbreviationLength characters of day into abbreviation
			if abbreviations contains abbreviation
				exit repeat
			end if
			insert abbreviation after abbreviations
			if the number of items in abbreviations is len
				return abbreviationLength
			end if
		end repeat
		add 1 to abbreviationLength
	end repeat
end AbbreviationsAutomatic


set f [open abbreviations_automatic_weekdays.txt]
set lines [split [read -nonewline $f] \n]
close $f

foreach days $lines {
  if {[string length $days] == 0} continue
  if {[llength $days] != 7} {
    throw ERROR {not 7 days in a line}
  }
  if {[llength [lsort -unique $days]] != 7} {
    throw ERROR {not all 7 days in a line are distinct}
  }
  for {set i 0} {1} {incr i} {
    if {[llength [lsort -unique [lmap x $days {string range $x 0 $i}]]] == 7} break
  }
  incr i
  puts "$i $days"
}


object Main {

  // This is a special class for memoization
  case class Memo[A,B](f: A => B) extends (A => B) {
	  private val cache = Map.empty[A, B]
	  def apply(x: A) = cache getOrElseUpdate (x, f(x))
  }

  // Naive, but memoized solution
  lazy val namesStartingMemo : Memo[Tuple2[Int, Int], BigInt] = Memo {
    case (1, 1) => 1
    case (a, n) =>
	    if (a > n/2) namesStartingMemo(a - 1, n - 1)
	    else if (n < a) 0
	    else if (n == a) 1
	    else (1 to a).map(i => namesStartingMemo(i, n - a)).sum

  }

  def partitions(n: Int) = (1 to n).map(namesStartingMemo(_, n)).sum

  // main method
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 25) {
    	for (j <- 1 to i) {
	      print(namesStartingMemo(j, i));
	      print(' ');
	    }
    	println()
    }
    println(partitions(23))
    println(partitions(123))
    println(partitions(1234))
    println(partitions(12345))
  }
}


#!/usr/bin/env bqn

# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments
# (BQNcrate phrase).
Split ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢

# Natural number from base-10 digits (BQNcrate phrase).
Base10 ← 10⊸×⊸+˜´∘⌽

# Parse any number of space-separated numbers from string 𝕩.
ParseNums ← {Base10¨ -⟜'0' ' ' Split 𝕩}

# •GetLine and •_while_ are nonstandard CBQN extensions.
{•Show +´ ParseNums 𝕩 ⋄ •[email protected]} •_while_ (@⊸≢) •[email protected]


( out
$ (   put$"Enter two integer numbers between -1000 and 1000:"
    & (filter=~/#%:~<-1000:~>1000)
    & get':(!filter:?a) (!filter:?b)
    & !a+!b
  | "Invalid input. Try again"
  )
);


INPUT AND SUMMATION
TODO if first symbol is a minus sign print Qgo awayQ
+>                                                  initialize sum to one
++[                                                 loop for each input ie twice
    [>>,----------[----------------------[-<+>]]<]      eat digits until space or newline
    <[<]>>>
    >[<                                                 until no next digit
        ----------------                                    subtract ascii zero minus what we subtracted above
        [->++++++++++<]                                     add ten timess that to the next digit
        <[->+<]<[->+<]>>                                    shift sum and loop counter
        >>
    ]
    <----------------                                   subtract as above from last digit as well
    [-<<+>>]                                            add to sum
    <-
]
<-                                                  subtract original one from sum

OUTPUT
[                                                                                while a number divided by ten is bigger than zero
    [->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->--------->+<<[->>>+<<<]]]]]]]]]]>>>[-<<<+>>>]<<<]   divide by ten
    >++++++++++++++++++++++++++++++++++++++++++++++++>                                                  convert remainder to ascii digit
]
<[.<<]                                                                                print ascii digits


#lang transd

MainModule : {
    _start: (λ
        (with fs FileStream() words String()
            (open-r fs "D:\\Temp\\wordlist.txt")
            (for line in (read-lines fs) do
               (with days (split line " ") len 0
                  (for w in days do (for y in days do
                    (if (neq w y) (= len (max len (coincide w y))))))
                  (lout (+ len 1) " " days))
   )   )   )
}


STRING PROC FNStringGetExpressionRegularCharacterMetaEscapeS( STRING inS )
 STRING s[255] = inS
 s = StrReplace( "\", s, "\\", "gn" )
 s = StrReplace( "{", s, "\{", "gn" )
 s = StrReplace( "[", s, "\[", "gn" )
 s = StrReplace( "}", s, "\}", "gn" )
 s = StrReplace( "]", s, "\]", "gn" )
 s = StrReplace( "*", s, "\*", "gn" )
 s = StrReplace( "+", s, "\+", "gn" )
 s = StrReplace( "@", s, "\@", "gn" )
 s = StrReplace( ".", s, "\.", "gn" )
 s = StrReplace( "^", s, "\^", "gn" )
 s = StrReplace( "$", s, "\$", "gn" )
 s = StrReplace( "|", s, "\|", "gn" )
 s = StrReplace( "?", s, "\?", "gn" )
 s = StrReplace( "#", s, "\#", "gn" )
 RETURN( s )
END
//
INTEGER PROC FNBlockGetAbbreviationLengthMinimumToBufferB( INTEGER buffer1I )
 INTEGER B = FALSE
 INTEGER downB = TRUE
 STRING s[255] = ""
 INTEGER foundB = FALSE
 INTEGER minI = 1
 INTEGER I = 0
 INTEGER buffer2I = 0
 STRING s1[255] = ""
 INTEGER lineColumnStartI = 4 // change this
 Set( BREAK, ON )
 PushPosition()
 PushBlock()
 GotoBlockBegin()
 WHILE ( ( IsCursorInBlock() ) AND ( downB ) )
  IF NOT LFind( "^$", "cgx" )
   I = minI - 1
   REPEAT
    I = I + 1
    PushPosition()
    buffer2I = CreateTempBuffer()
    PopPosition()
    BegLine()
    REPEAT
     IF ( LFind( "{.*}{{[ ]#}|$}\c", "cx" ) )
      s = GetFoundText( 1 )
      s = Trim( s )
      s1 = LeftStr( s, I )
      PushPosition()
      PushBlock()
      GotoBufferId( buffer2I )
      foundB = LFind( Format( "^", FNStringGetExpressionRegularCharacterMetaEscapeS( s1 ), "$" ), "gx" )
      IF NOT foundB
       EndFile()
       AddLine( s1 )
      ENDIF
      PopBlock()
      PopPosition()
     ENDIF
    UNTIL ( ( ( CurrChar() == _AT_EOL_ ) OR ( CurrChar() == _BEYOND_EOL_ ) ) OR ( foundB ) )
    AbandonFile( buffer2I )
   UNTIL ( NOT ( foundB ) )
  ENDIF
  IF NOT foundB
   PushPosition()
   PushBlock()
   BegLine()
   UnMarkBlock()
   MarkStream()
   EndLine()
   Left()
   MarkStream()
   Copy()
   GotoBufferId( buffer1I )
   EndFile()
   AddLine( Str( I ) )
   GotoColumn( lineColumnStartI )
   Paste()
   PopBlock()
   PopPosition()
  ENDIF
  downB = Down()
 ENDWHILE
 B = TRUE
 PopPosition()
 PopBlock()
 RETURN( B )
END
//
PROC Main()
 INTEGER bufferI = 0
 PushPosition()
 bufferI = CreateTempBuffer()
 PopPosition()
 Message( FNBlockGetAbbreviationLengthMinimumToBufferB( bufferI ) )
 GotoBufferId( bufferI )
END


Function MinimalLenght(strLine As String) As Integer
Dim myVar As Variant, I As Integer, Flag As Boolean, myColl As Collection, Count As Integer
   myVar = Split(strLine, " ")
   Count = 0
   Do
      Set myColl = New Collection
      Count = Count + 1
      On Error Resume Next
      Do
         myColl.Add Left$(myVar(I), Count), Left$(myVar(I), Count)
         I = I + 1
      Loop While Err.Number = 0 And I <= UBound(myVar)
      Flag = Err.Number = 0
      On Error GoTo 0
      I = 0
      Set myColl = Nothing
   Loop While Not Flag
   MinimalLenght = Count
End Function


(define (f m n)
  (define (sigma g x y)
    (define (sum i)
      (if (< i 0) 0 (+ (f x (- y i) ) (sum (- i 1)))))
    (sum y))
  (cond ((eq? m n) 1)
        ((eq? n 1) 1)
        ((eq? n 0) 0)
        ((< m n) (f m m))
        ((< (/ m 2) n) (sigma f (- m n) (- m n)))
        (else (sigma f (- m n) n))))
(define (line m)
  (define (connect i)
    (if (> i m) '() (cons (f m i) (connect (+ i 1)))))
  (connect 1))
(define (print x)
  (define (print-loop i)
    (cond ((< i x) (begin (display (line i)) (display "\n") (print-loop (+ i 1)) ))))
  (print-loop 1))
(print 25)


numbers = g.split[0,1].map(:to_i)
p numbers[0] + numbers[1]  #Prints the sum of the input


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

set d=createobject("Scripting.Dictionary")
set fso=createobject("Scripting.Filesystemobject")

const fn="weekdays_ansi.txt"
sfn=WScript.ScriptFullName
sfn= Left(sfn, InStrRev(sfn, "\"))
set f=fso.opentextfile(sfn & fn,1)

while not f.atendofstream
  s=f.readline
  if s=vbNullString then
	   print " "
	else
    a=split(trim(s)," ")
    for abrlen=1 to 14
      d.removeall
      for wd=0 to 6
        k=left(a(wd),abrlen)
        if d.exists(k) then
          exit for
        else
          d.add k,""
        end if
      next  'wd
      if wd>6 then exit for
    next 'abrlen
	  b=right("  " & abrlen,2)
	  for wd=0 to 6
       b=b &" "& left(a(wd),abrlen)
    next
    print b
  end if
wend  'line
f.close