import "random" for Random
import "/ioutil" for Input

var r = Random.new()
var b = List.filled(3, null)
for (i in 0..2) b[i] = List.filled(3, 0) // board -> 0: blank; -1: computer; 1: human

var bestI = 0
var bestJ = 0

var checkWinner = Fn.new {
    for (i in 0..2) {
        if (b[i][0] != 0 && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]
        if (b[0][i] != 0 && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]
    }
    if (b[1][1] == 0) return 0
    if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0]
    if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1]
    return 0
}

var showBoard = Fn.new {
    var t = "X O"
    for (i in 0..2) {
        for (j in 0..2) System.write("%(t[b[i][j] + 1]) ")
        System.print()
    }
    System.print("-----")
}

var testMove // recursive
testMove = Fn.new { |value, depth|
    var best = -1
    var changed = 0
    var score = checkWinner.call()
    if (score != 0) return (score == value) ? 1 : -1
    for (i in 0..2) {
        for (j in 0..2) {
            if (b[i][j] == 0) {
                b[i][j] = value
                changed = value
                score = -testMove.call(-value, depth + 1)
                b[i][j] = 0
                if (score > best) {
                    if (depth == 0) {
                        bestI = i
                        bestJ = j
                    }
                    best = score
                }
            }
        }
    }
    return (changed != 0) ? best : 0
}

var game = Fn.new { |u|
    for (i in 0..2) {
        for (j in 0..2) b[i][j] = 0
    }
    System.print("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9")
    System.print("You have O, I have X.\n")

    for (k in 0..8) {
        while (u) {
            var move = Input.integer("Your move: ", 1, 9) - 1
            var i = (move/3).floor
            var j = move % 3
            if (b[i][j] == 0) {
                b[i][j] = 1
                break
            }
        }
        if (!u) {
            if (k == 0) { // randomize if computer opens, less boring
                bestI = r.int(1e6) % 3
                bestJ = r.int(1e6) % 3
            } else {
                testMove.call(-1, 0)
            }
            b[bestI][bestJ] = -1
            var myMove = bestI * 3 + bestJ + 1
            System.print("My move: %(myMove)")
        }
        showBoard.call()
        var win = checkWinner.call()
        if (win != 0) return ((win == 1) ? "You win" : "I win") + ".\n\n"
        u = !u
    }
    return "A draw.\n\n"
}

var user = false
while (true) {
    user = !user
    System.write(game.call(user))
    var yn = Input.option("Play again y/n: ", "yYnN")
    if (yn == "n" || yn == "N") return
    System.print()
}


MODULE TauNumbers;
FROM InOut IMPORT WriteCard, WriteLn;

CONST
    MaxNum = 1100; (* enough to generate 100 Tau numbers *)
    NumTau = 100;  (* how many Tau numbers to generate *)

VAR DivCount: ARRAY [1..MaxNum] OF CARDINAL;
    seen, n: CARDINAL;

(* Find the amount of divisors for each number beforehand *)
PROCEDURE CountDivisors;
VAR i, j: CARDINAL;
BEGIN
    FOR i := 1 TO MaxNum DO
        DivCount[i] := 1; (* every number is divisible by 1 *)
    END;

    FOR i := 2 TO MaxNum DO
        j := i;
        WHILE j <= MaxNum DO (* J is divisible by I *)
            DivCount[j] := DivCount[j] + 1;
            j := j + i; (* next multiple of i *)
        END;
    END;
END CountDivisors;

BEGIN
    CountDivisors();
    n := 1;
    seen := 0;
    WHILE seen < NumTau DO
        IF n MOD DivCount[n] = 0 THEN
            WriteCard(n, 5);
            INC(seen);
            IF seen MOD 10 = 0 THEN
                WriteLn();
            END;
        END;
        INC(n);
    END;
END TauNumbers.


import math, strutils

func divcount(n: Natural): Natural =
  for i in 1..sqrt(n.toFloat).int:
    if n mod i == 0:
      inc result
      if n div i != i: inc result

var count = 0
var n = 1
var tauNumbers: seq[Natural]
while true:
  if n mod divcount(n) == 0:
    tauNumbers.add n
    inc count
    if count == 100: break
  inc n

echo "First 100 tau numbers:"
for i, n in tauNumbers:
  stdout.write ($n).align(5)
  if i mod 20 == 19: echo()


program Tau_number;
{$IFDEF Windows}  {$APPTYPE CONSOLE} {$ENDIF}
  function CountDivisors(n: NativeUint): integer;
  //tau function
  var
    q, p, cnt, divcnt: NativeUint;
  begin
    divCnt := 1;
    if n > 1 then
    begin
      cnt := 1;
      while not (Odd(n)) do
      begin
        n := n shr 1;
        divCnt+= cnt;
      end;
      p := 3;
      while p * p <= n do
      begin
        cnt := divCnt;
        q := n div p;
        while q * p = n do
        begin
          n := q;
          q := n div p;
          divCnt+= cnt;
        end;
        Inc(p, 2);
      end;
      if n <> 1 then
        divCnt += divCnt;
    end;
    CountDivisors := divCnt;
  end;

const
  UPPERLIMIT = 100;
var
  cnt,n: NativeUint;
begin
  cnt := 0;
  n := 1;
  repeat
    if n MOD CountDivisors(n) = 0 then
    Begin
      write(n:5);
      inc(cnt);
      if cnt Mod 10 = 0 then
        writeln;
    end;
    inc(n);
  until cnt >= UPPERLIMIT;
  writeln;
  {$Ifdef Windows}readln;{$ENDIF}
end.


program Temperature;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TTemp = class
  private
    fCelsius, fFahrenheit, fRankine: double;
  public
    constructor Create(aKelvin: double);
    property AsCelsius: double read fCelsius;
    property AsFahrenheit: double read fFahrenheit;
    property AsRankine: double read fRankine;
  end;

  { TTemp }

constructor TTemp.Create(aKelvin: double);
begin
  fCelsius := aKelvin - 273.15;
  fRankine := aKelvin * 9 / 5;
  fFahrenheit := fRankine - 459.67;
end;

var
  kelvin: double;
  temp: TTemp;

begin
  write('Kelvin: ');
  readln(kelvin);
  temp := TTemp.Create(kelvin);
  writeln(Format('Celsius: %.2f', [temp.AsCelsius]));
  writeln(Format('Fahrenheit: %.2f', [temp.AsFahrenheit]));
  writeln(Format('Rankine: %.2f', [temp.AsRankine]));
  temp.Free;
  readln;
end.


\The computer marks its moves with an "O" and the player uses an "X". The
\ numeric keypad is used to make the player's move.
\
\                         7 | 8 | 9
\                        ---+---+---
\                         4 | 5 | 6
\                        ---+---+---
\                         1 | 2 | 3
\
\The player always goes first, but the 0 key is used to skip a move. Thus
\ it can be used to let the computer play first. Esc terminates program.

inc     c:\cxpl\codes;  \intrinsic routine declarations
def     X0=16, Y0=10;   \coordinates of character in upper-left square
int     I0,
        PMove,          \player's move (^0..^9)
        Key;            \keystroke
int     X, O;           \bit arrays for player and computer
                        \ bit 0 corresponds to playing square 1, etc.

proc    HLine(X, Y);    \Draw a horizontal line
int     X, Y;
int     I;
[Cursor(X, Y);
for I:= 0 to 10 do ChOut(0, ^Ä);
];      \HLine

proc    VLine(X, Y);    \Draw a vertical line over the above horizontal line
int     X, Y;
int     I;
[for I:= 0 to 4 do
        [Cursor(X, Y+I);
        ChOut(0, if I&1 then ^Å else ^³);
        ];
];      \VLine

func    Won(p);         \Return 'true' if player P has won
int     P;
int     T, I;
[T:= [$007, $038, $1C0, $049, $092, $124, $111, $054];
for I:= 0 to 7 do       \check if player matches a bit pattern for 3 in a row
    if (P & T(I)) = T(I) then return true;
return false;
];      \Won

func    Cats;           \Return 'true' if no more moves available (Cat's game)
[if (X ! O) = $1FF then \all bit positions played
        [Cursor(17, 20);
        Text(0, "A draw!");
        return true;
        ];
return false;
];      \Cats

proc    DoMove(P, M, Ch); \Make move in player's bit array and display it
int     P,              \address of player's bit array
        M,              \index 0..8 where bit is placed
        Ch;
int     I, X, Y;
[P(0):= P(0) ! 1<<M;    \make move

I:= M / 3;              \display move
X:= Rem(0) * 4;
Y:= (2-I) * 2;
Cursor(X+X0, Y+Y0);
ChOut(0, Ch);
];      \DoMove

func    Try(P);         \Return the value of the best node for player P
int     P;              \address of player's bit array
int     P1, I, I0, V, V0;
[P1:= if P = addr X then addr O else addr X;

if Won(P1(0)) then return -1;
if (X ! O) = $1FF then return 0;

V0:= -1;                                \assume the worst
for I:= 0 to 8 do                       \for all of the squares...
    if ((O!X) & 1<<I) = 0 then          \if square is unused
        [P(0):= P(0) ! 1<<I;            \make tenative move
        V:= -(extend(Try(P1)));         \get value
        if V > V0 then                  \save best value
                [V0:= V;  I0:= I];
        P(0):= P(0) & ~(1<<I);          \undo tenative move
        ];
return V0 & $FF ! I0<<8;
];      \Try

proc    PlayGame;       \Play one game
[ChOut(0, $0C\FF\);     \clear screen with a form feed
HLine(X0-1, Y0+1);      \draw grid (#)
HLine(X0-1, Y0+3);
VLine(X0+2, Y0);
VLine(X0+6, Y0);

X:= 0;  O:= 0;          \initialize player's bit arrays to empty
loop    [loop   [PMove:= ChIn(1);               \GET PLAYER'S MOVE (X)
                if PMove = $1B\Esc\ then
                        [SetVid(3);  exit];     \restore display and end program
                if PMove = ^0 then quit;
                if PMove>=^1 & PMove<=^9 &      \check for legal move
                   ((X!O) & 1<<(PMove-^1)) = 0 then quit;
                ChOut(0, 7\Bel\);               \beep the dude
                ];
        if PMove # ^0 then
                [DoMove(addr X, PMove-^1, ^X);
                if Won(X) then
                        [Cursor(17, 20);
                        Text(0, "X wins!");
                        quit;
                        ];
                ];
        if Cats then quit;

        I0:= Try(addr O) >>8;                   \GET COMPUTER'S MOVE (O)
        DoMove(addr O, I0, ^O);                 \do best move
        if Won(O) then
                [Cursor(17, 20);
                Text(0, "O wins!");
                quit;
                ];
        if Cats then quit;
        ];
];      \PlayGame

int     CpuReg;
[SetVid(1);                             \set 40x25 text mode
CpuReg:= GetReg;                        \turn off annoying flashing cursor
CpuReg(0):= $0100;                      \ with BIOS interrupt 10h, function 01h
CpuReg(2):= $2000;                      \set cursor type to disappear
SoftInt($10);
loop    [PlayGame;
        Key:= ChIn(1);                  \keep playing games until Esc key is hit
        if Key = $1B\Esc\ then
                [SetVid(3);  exit];     \clear screen & restore normal text mode
        ];
]


use strict;
use warnings;
use feature 'say';
use ntheory 'divisors';

my(@x,$n);

do { push(@x,$n) unless $n % scalar(divisors(++$n)) } until 100 == @x;

say "Tau numbers - first 100:\n" .
    ((sprintf "@{['%5d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);


integer n = 1, found = 0
while found<100 do
    if remainder(n,length(factors(n,1)))=0 then
        found += 1
        printf(1,"%,6d",n)
        if remainder(found,10)=0 then puts(1,"\n") end if
    end if
    n += 1
end while


T :1
C :n=2
C :seen=1
C :max=100
*number
C :c=1
C :i=1
*divisor
C (n=i*(n/i)):c=c+1
C :i=i+1
J (i<=n/2):*divisor
T (n=c*(n/c)):#n
C (n=c*(n/c)):seen=seen+1
C :n=n+1
J (seen<max):*number
E :


100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;

/* PRINT NUMBER RIGHT-ALIGNED IN 7 POSITIONS */
PRINT$NUMBER: PROCEDURE (N);
    DECLARE S (7) BYTE INITIAL (' .....$');
    DECLARE N ADDRESS, I BYTE;
    I = 6;
DIGIT:
    I = I - 1;
    S(I) = N MOD 10 + '0';
    N = N / 10;
    IF N > 0 THEN GO TO DIGIT;
    DO WHILE I <> 0;
        I = I - 1;
        S(I) = ' ';
    END;
    CALL PRINT(.S);
END PRINT$NUMBER;

/* COUNT AND STORE AMOUNT OF DIVISORS FOR 1..N AT VEC */
COUNT$DIVS: PROCEDURE (VEC, N);
    DECLARE (VEC, N, V BASED VEC) ADDRESS;
    DECLARE (I, J) ADDRESS;

    DO I=1 TO N;
        V(I) = 1;
    END;

    DO I=2 TO N;
        J = I;
        DO WHILE J <= N;
            V(J) = V(J) + 1;
            J = J + I;
        END;
    END;
END COUNT$DIVS;

/* GIVEN VECTOR OF COUNT OF DIVISORS, SEE IF N IS A TAU NUMBER */
TAU: PROCEDURE (VEC, N) BYTE;
    DECLARE (VEC, N, V BASED VEC) ADDRESS;
    RETURN N MOD V(N) = 0;
END TAU;

DECLARE AMOUNT LITERALLY '100';
DECLARE LIMIT LITERALLY '1100';

DECLARE SEEN BYTE INITIAL (0);
DECLARE N ADDRESS INITIAL (1);

CALL COUNT$DIVS(.MEMORY, LIMIT);
DO WHILE SEEN < AMOUNT;
    IF TAU(.MEMORY, N) THEN DO;
        CALL PRINT$NUMBER(N);
        SEEN = SEEN + 1;
        IF SEEN MOD 10 = 0 THEN CALL PRINT(.(13,10,'$'));
    END;
    N = N + 1;
END;

CALL EXIT;
EOF


OpenConsole()

Procedure.i numdiv(n)
  c=2
  For i=2 To (n+1)/2 : If n%i=0 : c+1 : EndIf : Next
  ProcedureReturn c
EndProcedure

Procedure.b istau(n)
  If n=1 : ProcedureReturn #True : EndIf
  If n%numdiv(n)=0 : ProcedureReturn #True : Else : ProcedureReturn #False : EndIf
EndProcedure

c=0 : i=1
While c<100
  If istau(i) : Print(RSet(Str(i),4)+#TAB$) : c+1 : If c%10=0 : PrintN("") : EndIf: EndIf
  i+1
Wend

Input()


k = number input
print k & " °K"
print k - 273.15 & " °C"
print k * 1.8 - 459.67 & " °F"
print k * 1.8 & " °R"


import extensions;

convertKelvinToFahrenheit(x)
    = x * 1.8r - 459.6r;

convertKelvinToRankine(x)
    = x * 1.8r;

convertKelvinToCelsius(x)
    = x - 273.15r;

public program()
{
    console.print("Enter a Kelvin Temperature: ");
    var inputVal := console.readLine();
    real kelvinTemp := 0.0r;
    try
    {
        kelvinTemp := realConvertor.convert(inputVal)
    }
    catch(Exception e)
    {
        console.printLine("Invalid input value: ", inputVal);

        AbortException.raise()
    };

    console.printLine("Kelvin: ", kelvinTemp);
    console.printLine("Fahrenheit: ", convertKelvinToFahrenheit(kelvinTemp));
    console.printLine("Rankine: ", convertKelvinToRankine(kelvinTemp));
    console.printLine("Celsius: ", convertKelvinToCelsius(kelvinTemp));
    console.readChar()
}


defmodule Temperature do
  def conversion(t) do
    IO.puts "K : #{f(t)}"
    IO.puts "\nC : #{f(t - 273.15)}"
    IO.puts "\nF : #{f(t * 1.8 - 459.67)}"
    IO.puts "\nR : #{f(t * 1.8)}"
  end

  defp f(a) do
    Float.round(a, 2)
  end

  def task, do: conversion(21.0)
end

Temperature.task


5 REM Adaptation to Yabasic of the program published in Tim Hartnell's book "Artificial Intelligence: Concepts and Programs", with some minor modifications. 6/2018.
10 REM TICTAC
15 INPUT "English (0), Spanish (other key): " IDIOMA : IF NOT IDIOMA THEN RESTORE 2020 ELSE RESTORE 2010 END IF
20 GOSUB 1180: REM INICIALIZACION
30 REM *** REQUISITOS PREVIOS AL JUEGO ***
40 FOR J = 1 TO 9
50 A(J) = 32
60 NEXT J
70 FOR J = 1 TO 5
80 D(J) = 0
90 NEXT J
100 CCONTADOR = 0
110 R$ = ""
120 GOSUB 1070: REM IMPRESION DEL TABLERO
130 REM ** CICLO PRINCIPAL **
140 GOSUB 540: REM MOVIMIENTO DEL ORDENADOR
150 GOSUB 1070: REM IMPRESION DEL TABLERO
160 GOSUB 870: REM COMPRUEBA LA VICTORIA
170 IF R$ <> ""  GOTO 240
180 GOSUB 980: REM SE ACEPTA EL MOVIMIENTO DE LA PERSONA
190 GOSUB 1070: REM IMPRESION DEL TABLERO
200 GOSUB 870: REM COMPRUEBA LA VICTORIA
210 IF R$ = ""  GOTO 140
220 REM ** FIN DEL CICLO PRINCIPAL **
230 REM *****************************
240 REM FIN DEL JUEGO
250 GOSUB 1070: REM IMPRESION DEL TABLERO
260 PRINT: PRINT
270 IF R$ = "G"  PRINT MENSAJE$(1): BANDERA = -1
280 IF R$ = "P"  PRINT MENSAJE$(2): BANDERA = 1
290 IF R$ = "D"  PRINT MENSAJE$(3): GOTO 430
300 REM ACTUALIZACION DE LA BASE DE DATOS
310 FOR B = 1 TO 5
320 FOR J = 2 TO 9
330 IF M(J) = D(B) GOSUB 370
340 NEXT J
350 NEXT B
360 GOTO 430
370 REM ** REORDENACION DE LOS ELEMENTOS DE LA MATRIZ M **
380 TEMP = M(J + BANDERA)
390 M(J + BANDERA) = M(J)
400 M(J) = TEMP
410 J = 9
420 RETURN
430 PRINT: PRINT
440 PRINT MENSAJE$(4)
450 PRINT: PRINT
460 FOR J = 1 TO 9
470 PRINT M(J), " ";
480 NEXT J
490 PRINT: PRINT
500 PRINT MENSAJE$(5)
510 INPUT A$
520 GOTO 30
530 REM ************************
540 REM MOVIMIENTO DEL ORDENADOR
550 P = ASC("O")
560 X = 0
570 J = 1
580 IF A(W(J)) = A(W(J + 1)) AND A(W(J + 2)) = 32 AND A(W(J)) = P  X = W(J + 2): GOTO 750
590 IF A(W(J)) = A(W(J + 2)) AND A(W(J + 1)) = 32 AND A(W(J)) = P  X = W(J + 1): GOTO 750
600 IF A(W(J + 1)) = A(W(J + 2)) AND A(W(J)) = 32 AND A(W(J + 1)) = P  X = W(J): GOTO 750
610 IF J < 21  J = J + 3: GOTO 580
620 IF P = ASC("O")  P = ASC("X"): GOTO 570
630 REM ** SI NO SE GANA SE BUSCA UN MOVIMIENTO DE BLOQUEO **
640 REM * ENTONCES SE USA LA SIGUIENTE SECCION *
650 J = 1
660 IF A(M(J)) = 32  X = M(J): GOTO 750
670 IF J < 10  J = J + 1: GOTO 660
680 H = 0
690 H = H + 1
700 X = INT(RAN(1) * 9): IF A(X) = 32  GOTO 750
710 IF H < 100  GOTO 690
720 R$ = "D": REM ES SIMPLEMENTE UN DIBUJO
730 RETURN
740 REM *********************
750 REM REALIZA EL MOVIMIENTO
760 A(X) = ASC("O")
770 CCONTADOR = CCONTADOR + 1
780 D(CCONTADOR) = X
790 BANDERA = 0
800 FOR J = 1 TO 9
810 IF A(J) = 32  BANDERA = 1
820 NEXT J
830 IF BANDERA = 0 AND R$ = ""  R$ = "D"
840 REM SI TODAS LAS CASILLAS ESTAN LLENAS Y R$ ESTA VACIO, ENTONCES ES SIMPLEMENTE UN DIBUJO
850 RETURN
860 REM *********************
870 REM COMPRUEBA LA VICTORIA
880 J = 1
890 IF A(W(J)) = 32  J = J + 3
900 IF J > 23  RETURN
910 IF A(W(J)) = A(W(J + 1)) AND A(W(J)) = A(W(J + 2))  GOTO 940
920 IF J < 22  J = J + 3: GOTO 890
930 RETURN
940 IF A(W(J)) = ASC("O")  R$ = "G": REM EL ORDENADOR GANA
950 IF A(W(J)) = ASC("X")  R$ = "P": REM EL ORDENADOR PIERDE
960 RETURN
970 REM ************************
980 REM MOVIMIENTO DE LA PERSONA
990 PRINT: PRINT
1000 PRINT MENSAJE$(6)
1010 PRINT MENSAJE$(7); : INPUT MOVIMIENTO
1020 IF MOVIMIENTO < 1 OR MOVIMIENTO > 9  GOTO 1010
1030 IF A(MOVIMIENTO) <> 32  GOTO 1010
1040 A(MOVIMIENTO) = ASC("X")
1050 RETURN
1060 REM *********************
1070 REM IMPRESION DEL TABLERO
1080 CLEAR SCREEN
1090 PRINT: PRINT: PRINT
1100 PRINT " 1 : 2 : 3        ", CHR$(A(1)), " : ", CHR$(A(2)), " : ", CHR$(A(3))
1110 PRINT "-----------      ------------"
1120 PRINT " 4 : 5 : 6        ", CHR$(A(4)), " : ", CHR$(A(5)), " : ", CHR$(A(6))
1130 PRINT "-----------      ------------"
1140 PRINT " 7 : 8 : 9        ", CHR$(A(7)), " : ", CHR$(A(8)), " : ", CHR$(A(9))
1150 PRINT
1160 RETURN
1170 REM **************
1180 REM INICIALIZACION
1190 CLEAR SCREEN
1200 DIM A(9) : REM TABLERO
1210 DIM M(10) : REM ACCESO A LA BASE DE DATOS
1220 DIM W(24) : REM DATOS DE VICTORIA O BLOQUEO
1230 DIM D(5) : REM ACCESO AL MOVIMIENTO EN EL JUEGO ACTUAL
1235 DIM MENSAJE$(1) : READ M$ : N = TOKEN(M$,MENSAJE$(),",") : RESTORE
1240 REM DATOS DE VICTORIA O BLOQUEO
1250 FOR J = 1 TO 24
1260 READ W(J)
1270 NEXT J
1280 DATA 1, 2, 3, 4, 5, 6, 7, 8, 9
1290 DATA 1, 4, 7, 2, 5, 8, 3, 6, 9
1300 DATA 1, 5, 9, 3, 5, 7
1310 REM BASE INICIAL DE DATOS
1320 FOR J = 1 TO 10
1330 READ M(J)
1340 NEXT J
1350 DATA 2, 6, 8, 4, 7, 3, 1, 9, 5, 2
1360 RETURN
2000 REM MENSAJES EN ESPAÑOL
2010 DATA "YO GANO,TU GANAS,ES SIMPLEMENTE UN DIBUJO,ESTA ES MI PRIORIDAD ACTUALIZADA,PULSE LA TECLA <RETURN> PARA CONTINUAR,REALICE SU MOVIMIENTO,MOVIMIENTO: "
2020 DATA "I WIN,YOU WIN,IT'S JUST A DRAWING,THIS IS MY PRIORITY UPDATE,PRESS <RETURN> TO CONTINUE,TO MAKE YOUR MOVE,MOVEMENT: "


def tau(n):
    assert(isinstance(n, int) and 0 < n)
    ans, i, j = 0, 1, 1
    while i*i <= n:
        if 0 == n%i:
            ans += 1
            j = n//i
            if j != i:
                ans += 1
        i += 1
    return ans

def is_tau_number(n):
    assert(isinstance(n, int))
    if n <= 0:
        return False
    return 0 == n%tau(n)

if __name__ == "__main__":
    n = 1
    ans = []
    while len(ans) < 100:
        if is_tau_number(n):
            ans.append(n)
        n += 1
    print(ans)


  [ dup factors size mod 0 = ] is taunumber ( n --> b )

  [] 0
  [ 1+ dup taunumber if
      [ tuck join swap ]
    over size 100 = until ]
  drop
  [] swap
  witheach [ number$ nested join ]
  80 wrap$


tau <- function(t)
{
  results <- integer(0)
  resultsCount <- 0
  n <- 1
  while(resultsCount != t)
  {
    condition <- function(n) (n %% length(c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n))) == 0
    if(condition(n))
    {
      resultsCount <- resultsCount + 1
      results[resultsCount] <- n
    }
    n <- n + 1
  }
  results
}
tau(100)


use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;

say "\nTau function - first 100:\n",        # ID
(1..*).map({ +.&divisors })[^100]\          # the task
.batch(20)».fmt("%3d").join("\n");          # display formatting

say "\nTau numbers - first 100:\n",         # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\   # the task
.batch(10)».&comma».fmt("%5s").join("\n");  # display formatting

say "\nDivisor sums - first 100:\n",        # ID
(1..*).map({ [+] .&divisors })[^100]\       # the task
.batch(20)».fmt("%4d").join("\n");          # display formatting

say "\nDivisor products - first 100:\n",    # ID
(1..*).map({ [×] .&divisors })[^100]\       # the task
.batch(5)».&comma».fmt("%16s").join("\n");  # display formatting


% Implemented by Arjun Sunel
-module(temp_conv).
-export([main/0]).

main() ->
    conversion(21).

conversion(T) ->
    io:format("\nK : ~p\n\n",[f(T)]),
    io:format("C : ~p \n\n",[f(T - 273.15)]),
    io:format("F : ~p\n\n",[f(T * 1.8 - 459.67)]),
    io:format("R : ~p\n\n",[f(T * 1.8)]).

f(A) ->
    (round(A*100))/100 .


include std/console.e

atom K
while 1 do
    K = prompt_number("Enter temperature in Kelvin >=0: ",{0,4294967296})
    printf(1,"K = %5.2f\nC = %5.2f\nF = %5.2f\nR = %5.2f\n\n",{K,K-273.15,K*1.8-459.67,K*1.8})
end while


/*REXX pgm displays   N   tau numbers,  an integer divisible by the # of its divisors). */
parse arg n cols .                               /*obtain optional argument from the CL.*/
if    n=='' |    n==","  then    n= 100          /*Not specified?  Then use the default.*/
if cols=='' | cols==","  then cols=  10          /*Not specified?  Then use the default.*/
w= max(8, length(n) )                            /*W:  used to align 1st output column. */
@tau= ' the first '  commas(n)   " tau numbers " /*the title of the tau numbers table.  */
say ' index │'center(@tau,  1 + cols*(w+1)     ) /*display the title of the output table*/
say '───────┼'center(""  ,  1 + cols*(w+1), '─') /*   "     " header  "  "     "     "  */
idx= 1;                  #= 0;           $=      /*idx: line;   #:  tau numbers;  $: #s */
           do j=1  until #==n                    /*search for   N   tau numbers         */
           if j//tau(j) \==0  then iterate       /*Is this a tau number?  No, then skip.*/
           #= # + 1                              /*bump the count of tau numbers found. */
           $= $  right( commas(j), w)            /*add a tau number to the output list. */
           if #//cols\==0     then iterate       /*Not a multiple of cols?  Don't show. */
           say center(idx, 7)'│'   substr($, 2)  /*display partial list to the terminal.*/
           idx= idx + cols;               $=     /*bump idx by number of cols; nullify $*/
           end   /*j*/

if $\==''  then say center(idx, 7)"│"  substr($, 2)  /*possible display residual output.*/
say '───────┴'center(""  ,  1 + cols*(w+1), '─')
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
tau: procedure; parse arg x 1 y                  /*X  and  $  are both set from the arg.*/
     if x<6  then return 2 + (x==4) - (x==1)     /*some low #s should be handled special*/
     odd= x // 2                                 /*check if  X  is odd (remainder of 1).*/
     if odd  then do;   #= 2;               end  /*Odd?    Assume divisor count of  2.  */
             else do;   #= 4;   y= x % 2;   end  /*Even?      "      "      "    "  4.  */
                                                 /* [↑]  start with known number of divs*/
        do j=3  for x%2-3  by 1+odd  while j<y   /*for odd number,  skip even numbers.  */
        if x//j==0  then do                      /*if no remainder, then found a divisor*/
                         #= # + 2;   y= x % j    /*bump # of divisors;  calculate limit.*/
                         if j>=y  then do;   #= # - 1;   leave;   end   /*reached limit?*/
                         end                     /*                     ___             */
                    else if j*j>x  then leave    /*only divide up to   √ x              */
        end   /*j*/                              /* [↑]  this form of DO loop is faster.*/
     return #


see "The first 100 tau numbers are:" + nl + nl

n = 1
num = 0
limit = 100
while num < limit
      n = n + 1
      tau = 0
      for m = 1 to n
          if n%m = 0
             tau = tau + 1
          ok
      next
      if n%tau = 0
         num = num + 1
         if num%10 = 1
            see nl
         ok
         see "" + n + " "
      ok
end


A1 : Kelvin
B1 : Celsius
C1 : Fahrenheit
D1 : Rankine
Name A2 : K
B2 : =K-273.15
C2 : =K*1.8-459.67
D2 : =K*1.8
Input in A1


# convert from Kelvin
நிரல்பாகம் கெல்வின்_இருந்து_மாற்று( k )
 பதிப்பி "Kelvin: ",k,"Celsius: ",round(k-273.15)," Fahrenheit: ",(round(k*1.8 - 459.67))," Rankine: ",(round(k*1.8))
முடி

கெல்வின்_இருந்து_மாற்று( 0 ) #absolute zero
கெல்வின்_இருந்து_மாற்று( 273 ) #freezing pt of water
கெல்வின்_இருந்து_மாற்று( 30 + 273 ) #room temperature in Summer


// Define units of measure
[<Measure>] type k
[<Measure>] type f
[<Measure>] type c
[<Measure>] type r

// Define conversion functions
let kelvinToCelsius (t : float<k>) = ((float t) - 273.15) * 1.0<c>
let kelvinToFahrenheit (t : float<k>) = (((float t) * 1.8) - 459.67) * 1.0<f>
let kelvinToRankine (t : float<k>) = ((float t) * 1.8) * 1.0<r>

// Example code
let K = 21.0<k>
printfn "%A Kelvin is %A Celsius" K (kelvinToCelsius K)
printfn "%A Kelvin is %A Fahrenheit" K (kelvinToFahrenheit K)
printfn "%A Kelvin is %A Rankine" K (kelvinToRankine K)


require 'prime'

taus = Enumerator.new do |y|
  (1..).each do |n|
    num_divisors = n.prime_division.inject(1){|prod, n| prod *= n[1] + 1 }
    y << n if n % num_divisors == 0
  end
end

p taus.take(100)


/// Gets all divisors of a number, including itself
fn get_divisors(n: u32) -> Vec<u32> {
    let mut results = Vec::new();

    for i in 1..(n / 2 + 1) {
        if n % i == 0 {
            results.push(i);
        }
    }
    results.push(n);
    results
}

fn is_tau_number(i: u32) -> bool {
    0 == i % get_divisors(i).len() as u32
}

fn main() {
    println!("\nFirst 100 Tau numbers:");
    let mut counter: u32 = 0;
    let mut i: u32 = 1;
    while counter < 100 {
        if is_tau_number(i) {
            print!("{:>4}", i);
            counter += 1;
            print!("{}", if counter % 20 == 0 { "\n" } else { "," });
        }
        i += 1;
    }
}


func is_tau_number(n) {
    n % n.sigma0 == 0
}

say is_tau_number.first(100).join(' ')


import Foundation

// See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
    var n = number
    var total = 1
    // Deal with powers of 2 first
    while (n & 1) == 0 {
        total += 1
        n >>= 1
    }
    // Odd prime factors up to the square root
    var p = 3
    while p * p <= n {
        var count = 1
        while n % p == 0 {
            count += 1
            n /= p
        }
        total *= count
        p += 2
    }
    // If n > 1 then it's prime
    if n > 1 {
        total *= 2
    }
    return total
}

let limit = 100
print("The first \(limit) tau numbers are:")
var count = 0
var n = 1
while count < limit {
    if n % divisorCount(number: n) == 0 {
        print(String(format: "%5d", n), terminator: "")
        count += 1
        if count % 10 == 0 {
            print()
        }
    }
    n += 1
}


module main;
  integer n, m, num, limit, tau;

  initial begin
    $display("The first 100 tau numbers are:\n");
    n = 0;
    num = 0;
    limit = 100;

    while (num < limit) begin
      n = n + 1;
      tau = 0;
      for (m = 1; m <= n; m=m+1) if (n % m == 0) tau = tau + 1;

      if (n % tau == 0) begin
        num = num + 1;
        if (num % 5 == 1) $display("");
        $write(n);
      end
    end
    $finish ;
  end
endmodule


T Graph
   String name
   [Char = [Char]] graph
   Int _order
   [Char = Int] disc
   [Char = Int] low
   [Char] stack
   [[Char]] scc

   F (name, connections)
      .name = name

      DefaultDict[Char, [Char]] g
      L(n) connections
         V (n1, n2) = (n[0], n[1])
         I n1 != n2
            g[n1].append(n2)
         E
            g[n1]
         g[n2]

      .graph = Dict(move(g))
      .tarjan_algo()

   F _visitor(this) -> N
      ‘
        Recursive function that finds SCC's
        using DFS traversal of vertices.

        Arguments:
            this        --> Vertex to be visited in this call.
            disc{}      --> Discovery order of visited vertices.
            low{}       --> Connected vertex of earliest discovery order
            stack       --> Ancestor node stack during DFS.
      ’
      .disc[this] = .low[this] = ._order
      ._order++
      .stack.append(this)

      L(neighbr) .graph[this]
         I neighbr !C .disc
            ._visitor(neighbr)
            .low[this] = min(.low[this], .low[neighbr])

         E I neighbr C .stack
            .low[this] = min(.low[this], .disc[neighbr])

      I .low[this] == .disc[this]
         [Char] new
         L
            V top = .stack.pop()
            new.append(top)
            I top == this
               L.break
         .scc.append(new)

   F tarjan_algo()
      ‘
        Recursive function that finds strongly connected components
        using the Tarjan Algorithm and function _visitor() to visit nodes.
      ’
      ._order = 0

      L(vertex) sorted(.graph.keys())
         I vertex !C .disc
            ._visitor(vertex)

L(n, m) [(‘Tx1’, ‘10 02 21 03 34’.split(‘ ’)),
         (‘Tx2’, ‘01 12 23’.split(‘ ’)),
         (‘Tx3’, ‘01 12 20 13 14 16 35 45’.split(‘ ’)),
         (‘Tx4’, ‘01 03 12 14 20 26 32 45 46 56 57 58 59 64 79 89 98 AA’.split(‘ ’)),
         (‘Tx5’, ‘01 12 23 24 30 42’.split(‘ ’))
         ]
   print("\n\nGraph('#.', #.):\n".format(n, m))
   V g = Graph(n, m)
   print(‘               :  ’sorted(g.disc.keys()).map(v -> String(v)).join(‘  ’))
   print(‘    DISC of ’(g.name‘:’)‘ ’sorted(g.disc.items()).map((_, v) -> v))
   print(‘     LOW of ’(g.name‘:’)‘ ’sorted(g.low.items()).map((_, v) -> v))
   V scc = (I !g.scc.empty {String(g.scc).replace(‘'’, ‘’).replace(‘,’, ‘’)[1 .< (len)-1]} E ‘’)
   print("\n   SCC's of "(g.name‘:’)‘ ’scc)


USING: combinators formatting kernel math ;
IN: rosetta-code.temperature

: k>c ( kelvin -- celsius )    273.15 - ;
: k>r ( kelvin -- rankine )    9/5 * ;
: k>f ( kelvin -- fahrenheit ) k>r 459.67 - ;

: convert ( kelvin -- )
    { [ ] [ k>c ] [ k>f ] [ k>r ] } cleave
    "K  %.2f\nC  %.2f\nF  %.2f\nR  %.2f\n" printf ;

21 convert


: k>°C  ( F: kelvin  -- celsius )     273.15e0 f- ;
: k>°R  ( F: kelvin  -- rankine )     1.8e0 f* ;
: °R>°F ( F: rankine -- fahrenheit )  459.67e0 f- ;
: k>°F  ( F: kelvin  -- fahrenheit )  k>°R °R>°F ;
: main
   argc 1 > if  1 arg >float
      fdup      f. ." K"  cr
      fdup k>°C f. ." °C" cr
      fdup k>°F f. ." °F" cr
      fdup k>°R f. ." °R" cr
   then ;

main bye


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

System.print("The first 100 tau numbers are:")
var count = 0
var i = 1
while (count < 100) {
    var tf = Int.divisors(i).count
    if (i % tf == 0) {
        Fmt.write("$,5d  ", i)
        count = count + 1
        if (count % 10 == 0) System.print()
    }
    i = i + 1
}


func Divs(N);   \Return number of divisors of N
int  N, D, C;
[C:= 0;
for D:= 1 to N do
    if rem(N/D) = 0 then C:= C+1;
return C;
];

int C, N;
[Format(5, 0);
C:= 0;  N:= 1;
loop    [if rem(N/Divs(N)) = 0 then
            [RlOut(0, float(N));
            C:= C+1;
            if rem(C/10) = 0 then CrLf(0);
            if C >= 100 then quit;
            ];
        N:= N+1;
        ];
]


#include <stddef.h>
#include <stdlib.h>
#include <stdbool.h>

#ifndef min
#define min(x, y) ((x)<(y) ? (x) : (y))
#endif

struct edge {
	void *from;
	void *to;
};

struct components {
	int nnodes;
	void **nodes;
	struct components *next;
};

struct node {
	int index;
	int lowlink;
	bool onStack;
	void *data;
};

struct tjstate {
	int index;
	int sp;
	int nedges;
	struct edge *edges;
	struct node **stack;
	struct components *head;
	struct components *tail;
};

static int nodecmp(const void *l, const void *r)
{
	return (ptrdiff_t)l -(ptrdiff_t)((struct node *)r)->data;
}

static int strongconnect(struct node *v, struct tjstate *tj)
{
	struct node *w;

	/* Set the depth index for v to the smallest unused index */
	v->index = tj->index;
	v->lowlink = tj->index;
	tj->index++;
	tj->stack[tj->sp] = v;
	tj->sp++;
	v->onStack = true;

	for (int i = 0; i<tj->nedges; i++) {
		/* Only consider nodes reachable from v */
		if (tj->edges[i].from != v) {
			continue;
		}
		w = tj->edges[i].to;
		/* Successor w has not yet been visited; recurse on it */
		if (w->index == -1) {
			int r = strongconnect(w, tj);
			if (r != 0)
				return r;
			v->lowlink = min(v->lowlink, w->lowlink);
		/* Successor w is in stack S and hence in the current SCC */
		} else if (w->onStack) {
			v->lowlink = min(v->lowlink, w->index);
		}
	}

	/* If v is a root node, pop the stack and generate an SCC */
	if (v->lowlink == v->index) {
		struct components *ng = malloc(sizeof(struct components));
		if (ng == NULL) {
			return 2;
		}
		if (tj->tail == NULL) {
			tj->head = ng;
		} else {
			tj->tail->next = ng;
		}
		tj->tail = ng;
		ng->next = NULL;
		ng->nnodes = 0;
		do {
			tj->sp--;
			w = tj->stack[tj->sp];
			w->onStack = false;
			ng->nnodes++;
		} while (w != v);
		ng->nodes = malloc(ng->nnodes*sizeof(void *));
		if (ng == NULL) {
			return 2;
		}
		for (int i = 0; i<ng->nnodes; i++) {
			ng->nodes[i] = tj->stack[tj->sp+i]->data;
		}
	}
	return 0;
}

static int ptrcmp(const void *l, const void *r)
{
	return (ptrdiff_t)((struct node *)l)->data
		- (ptrdiff_t)((struct node *)r)->data;
}

/**
 * Calculate the strongly connected components using Tarjan's algorithm:
 * en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
 *
 * Returns NULL when there are invalid edges and sets the error to:
 * 1 if there was a malformed edge
 * 2 if malloc failed
 *
 * @param number of nodes
 * @param data of the nodes (assumed to be unique)
 * @param number of edges
 * @param data of edges
 * @param pointer to error code
 */
struct components *tarjans(
		int nnodes, void *nodedata[],
		int nedges, struct edge *edgedata[],
		int *error)
{
	struct node nodes[nnodes];
	struct edge edges[nedges];
	struct node *stack[nnodes];
	struct node *from, *to;
	struct tjstate tj = {0, 0, nedges, edges, stack, NULL, .tail=NULL};

	// Populate the nodes
	for (int i = 0; i<nnodes; i++) {
		nodes[i] = (struct node){-1, -1, false, nodedata[i]};
	}
	qsort(nodes, nnodes, sizeof(struct node), ptrcmp);

	// Populate the edges
	for (int i = 0; i<nedges; i++) {
		from = bsearch(edgedata[i]->from, nodes, nnodes,
			sizeof(struct node), nodecmp);
		if (from == NULL) {
			*error = 1;
			return NULL;
		}
		to = bsearch(edgedata[i]->to, nodes, nnodes,
			sizeof(struct node), nodecmp);
		if (to == NULL) {
			*error = 1;
			return NULL;
		}
		edges[i] = (struct edge){.from=from, .to=to};
	}

	//Tarjan's
	for (int i = 0; i < nnodes; i++) {
		if (nodes[i].index == -1) {
			*error = strongconnect(&nodes[i], &tj);
			if (*error != 0)
				return NULL;
		}
	}
	return tj.head;
}


Program Temperature
  implicit none

  real :: kel, cel, fah, ran

  write(*,*) "Input Kelvin temperature to convert"
  read(*,*) kel

  call temp_convert(kel, cel, fah, ran)
  write(*, "((a10), f10.3)") "Kelvin", kel
  write(*, "((a10), f10.3)") "Celsius", cel
  write(*, "((a10), f10.3)") "Fahrenheit", fah
  write(*, "((a10), f10.3)") "Rankine", ran

contains

subroutine temp_convert(kelvin, celsius, fahrenheit, rankine)
  real, intent(in)  :: kelvin
  real, intent(out) :: celsius, fahrenheit, rankine

  celsius = kelvin - 273.15
  fahrenheit = kelvin * 1.8 - 459.67
  rankine = kelvin * 1.8

end subroutine
end program


' FB 1.05.0 Win64

Sub convKelvin(temp As Double)
  Dim f As String = "####.##"
  Print Using f; temp;
  Print " degrees Kelvin"
  Print Using f; temp - 273.15;
  Print " degrees Celsius"
  Print Using f; (temp - 273.15) * 1.8 + 32.0;
  Print " degrees Fahreneit"
  Print Using f; (temp - 273.15) * 1.8 + 32.0 + 459.67;
  Print " degrees Rankine"
End Sub

convKelvin(0.0)
Print
convKelvin(21.0)
Print
Print "Press any key to quit"
Sleep


using System;
using System.Collections.Generic;

class Node
{
    public int LowLink { get; set; }
    public int Index { get; set; }
    public int N { get; }

    public Node(int n)
    {
        N = n;
        Index = -1;
        LowLink = 0;
    }
}

class Graph
{
    public HashSet<Node> V { get; }
    public Dictionary<Node, HashSet<Node>> Adj { get; }

    /// <summary>
    /// Tarjan's strongly connected components algorithm
    /// </summary>
    public void Tarjan()
    {
        var index = 0; // number of nodes
        var S = new Stack<Node>();

        Action<Node> StrongConnect = null;
        StrongConnect = (v) =>
        {
            // Set the depth index for v to the smallest unused index
            v.Index = index;
            v.LowLink = index;

            index++;
            S.Push(v);

            // Consider successors of v
            foreach (var w in Adj[v])
                if (w.Index < 0)
                {
                    // Successor w has not yet been visited; recurse on it
                    StrongConnect(w);
                    v.LowLink = Math.Min(v.LowLink, w.LowLink);
                }
                else if (S.Contains(w))
                    // Successor w is in stack S and hence in the current SCC
                    v.LowLink = Math.Min(v.LowLink, w.Index);

            // If v is a root node, pop the stack and generate an SCC
            if (v.LowLink == v.Index)
            {
                Console.Write("SCC: ");

                Node w;
                do
                {
                    w = S.Pop();
                    Console.Write(w.N + " ");
                } while (w != v);

                Console.WriteLine();
            }
        };

        foreach (var v in V)
            if (v.Index < 0)
                StrongConnect(v);
    }
}


//
// C++ implementation of Tarjan's strongly connected components algorithm
// See https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
//
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
#include <vector>

struct noncopyable {
    noncopyable() {}
    noncopyable(const noncopyable&) = delete;
    noncopyable& operator=(const noncopyable&) = delete;
};

template <typename T>
class tarjan;

template <typename T>
class vertex : private noncopyable {
public:
    explicit vertex(const T& t) : data_(t) {}
    void add_neighbour(vertex* v) {
        neighbours_.push_back(v);
    }
    void add_neighbours(const std::initializer_list<vertex*>& vs) {
        neighbours_.insert(neighbours_.end(), vs);
    }
    const T& get_data() {
        return data_;
    }
private:
    friend tarjan<T>;
    T data_;
    int index_ = -1;
    int lowlink_ = -1;
    bool on_stack_ = false;
    std::vector<vertex*> neighbours_;
};

template <typename T>
class graph : private noncopyable {
public:
    vertex<T>* add_vertex(const T& t) {
        vertexes_.emplace_back(t);
        return &vertexes_.back();
    }
private:
    friend tarjan<T>;
    std::list<vertex<T>> vertexes_;
};

template <typename T>
class tarjan  : private noncopyable {
public:
    using component = std::vector<vertex<T>*>;
    std::list<component> run(graph<T>& graph) {
        index_ = 0;
        stack_.clear();
        strongly_connected_.clear();
        for (auto& v : graph.vertexes_) {
            if (v.index_ == -1)
                strongconnect(&v);
        }
        return strongly_connected_;
    }
private:
    void strongconnect(vertex<T>* v) {
        v->index_ = index_;
        v->lowlink_ = index_;
        ++index_;
        stack_.push_back(v);
        v->on_stack_ = true;
        for (auto w : v->neighbours_) {
            if (w->index_ == -1) {
                strongconnect(w);
                v->lowlink_ = std::min(v->lowlink_, w->lowlink_);
            }
            else if (w->on_stack_) {
                v->lowlink_ = std::min(v->lowlink_, w->index_);
            }
        }
        if (v->lowlink_ == v->index_) {
            strongly_connected_.push_back(component());
            component& c = strongly_connected_.back();
            for (;;) {
                auto w = stack_.back();
                stack_.pop_back();
                w->on_stack_ = false;
                c.push_back(w);
                if (w == v)
                    break;
            }
        }
    }
    int index_ = 0;
    std::list<vertex<T>*> stack_;
    std::list<component> strongly_connected_;
};

template <typename T>
void print_vector(const std::vector<vertex<T>*>& vec) {
    if (!vec.empty()) {
        auto i = vec.begin();
        std::cout << (*i)->get_data();
        for (++i; i != vec.end(); ++i)
            std::cout << ' ' << (*i)->get_data();
    }
    std::cout << '\n';
}

int main() {
    graph<std::string> g;
    auto andy = g.add_vertex("Andy");
    auto bart = g.add_vertex("Bart");
    auto carl = g.add_vertex("Carl");
    auto dave = g.add_vertex("Dave");
    auto earl = g.add_vertex("Earl");
    auto fred = g.add_vertex("Fred");
    auto gary = g.add_vertex("Gary");
    auto hank = g.add_vertex("Hank");

    andy->add_neighbour(bart);
    bart->add_neighbour(carl);
    carl->add_neighbour(andy);
    dave->add_neighbours({bart, carl, earl});
    earl->add_neighbours({dave, fred});
    fred->add_neighbours({carl, gary});
    gary->add_neighbour(fred);
    hank->add_neighbours({earl, gary, hank});

    tarjan<std::string> t;
    for (auto&& s : t.run(g))
        print_vector(s);
    return 0;
}


Public Sub Form_Open()
Dim fKelvin As Float

fKelvin = InputBox("Enter a Kelvin value", "Kelvin converter")

Print "Kelvin =\t" & Format(Str(fKelvin), "#.00")
Print "Celsius =\t" & Format(Str(fKelvin - 273.15), "#.00")
Print "Fahrenheit =\t" & Format(Str(fKelvin * 1.8 - 459.67), "#.00")
Print "Rankine =\t" & Format(Str(fKelvin * 1.8), "#.00")

End


package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    if len(os.Args) != 2 {
        fmt.Println("Usage: k <Kelvin>")
        return
    }
    k, err := strconv.ParseFloat(os.Args[1], 64)
    if err != nil {
        fmt.Println(err)
        return
    }
    if k < 0 {
        fmt.Println("Kelvin must be >= 0.")
        return
    }
    fmt.Printf("K  %.2f\n", k)
    fmt.Printf("C  %.2f\n", k-273.15)
    fmt.Printf("F  %.2f\n", k*9/5-459.67)
    fmt.Printf("R  %.2f\n", k*9/5)
}


package main

import (
    "fmt"
    "math/big"
)

// (same data as zkl example)
var g = [][]int{
    0: {1},
    2: {0},
    5: {2, 6},
    6: {5},
    1: {2},
    3: {1, 2, 4},
    4: {5, 3},
    7: {4, 7, 6},
}

func main() {
    tarjan(g, func(c []int) { fmt.Println(c) })
}

// the function calls the emit argument for each component identified.
// each component is a list of nodes.
func tarjan(g [][]int, emit func([]int)) {
    var indexed, stacked big.Int
    index := make([]int, len(g))
    lowlink := make([]int, len(g))
    x := 0
    var S []int
    var sc func(int) bool
    sc = func(n int) bool {
        index[n] = x
        indexed.SetBit(&indexed, n, 1)
        lowlink[n] = x
        x++
        S = append(S, n)
        stacked.SetBit(&stacked, n, 1)
        for _, nb := range g[n] {
            if indexed.Bit(nb) == 0 {
                if !sc(nb) {
                    return false
                }
                if lowlink[nb] < lowlink[n] {
                    lowlink[n] = lowlink[nb]
                }
            } else if stacked.Bit(nb) == 1 {
                if index[nb] < lowlink[n] {
                    lowlink[n] = index[nb]
                }
            }
        }
        if lowlink[n] == index[n] {
            var c []int
            for {
                last := len(S) - 1
                w := S[last]
                S = S[:last]
                stacked.SetBit(&stacked, w, 0)
                c = append(c, w)
                if w == n {
                    emit(c)
                    break
                }
            }
        }
        return true
    }
    for n := range g {
        if indexed.Bit(n) == 0 && !sc(n) {
            return
        }
    }
}


class Convert{
static void main(String[] args){
def c=21.0;
println("K "+c)
println("C "+k_to_c(c));
println("F "+k_to_f(k_to_c(c)));
println("R "+k_to_r(c));
}
static def k_to_c(def k=21.0){return k-273.15;}
static def k_to_f(def k=21.0){return ((k*9)/5)+32;}
static def k_to_r(def k=21.0){return k*1.8;}
}


import System.Exit (die)
import Control.Monad (mapM_)

main = do
  putStrLn "Please enter temperature in kelvin: "
  input <- getLine
  let kelvin = read input
  if kelvin < 0.0
      then die "Temp cannot be negative"
      else mapM_ putStrLn $ convert kelvin

convert :: Double -> [String]
convert n = zipWith (++) labels nums
    where labels      = ["kelvin: ", "celcius: ", "farenheit: ", "rankine: "]
          conversions = [id, subtract 273, subtract 459.67 . (1.8 *), (*1.8)]
          nums        = (show . ($n)) <$> conversions


# Input: an integer
def Node:
  { n: .,
    index: -1,    # -1 signifies undefined
    lowLink: -1,
    onStack: false
  } ;

# Input: a DirectedGraph
# Output: a stream of Node ids
def successors($vn): .es[$vn][];

# Input: a DirectedGraph
# Output: an array of integer arrays
def tarjan:
  . + { sccs: [],    # strongly connected components
        index: 0,
        s: []        # Stack
      }
  # input: {es, vs, sccs, index, s}
  | def strongConnect($vn):
      # Set the depth index for v to the smallest unused index
        .vs[$vn].index = .index
      | .vs[$vn].lowLink = .index
      | .index += 1
      | .s += [ $vn ]
      | .vs[$vn].onStack = true

      # consider successors of v
      | reduce successors($vn) as $wn (.;
            if .vs[$wn].index < 0
	    then
                # Successor w has not yet been visited; recurse on it
                strongConnect($wn)
                | .vs[$vn].lowLink = ([.vs[$vn].lowLink, .vs[$wn].lowLink] | min )
            elif .vs[$wn].onStack
	    then
                # Successor w is in stack s and hence in the current SCC
                .vs[$vn].lowLink = ([.vs[$vn].lowLink, .vs[$wn].index] | min )
	    else .
            end
        )
      # If v is a root node, pop the stack and generate an SCC
      | if .vs[$vn] | (.lowLink == .index)
        then .scc = []
	    | .stop = false
            | until(.stop;
                .s[-1] as $wn
		| .s |= .[:-1]    # pop
                | .vs[$wn].onStack = false
                | .scc += [$wn]
                | if $wn == $vn then .stop = true else . end )
        | .sccs += [.scc]
        else .
	end
    ;

    reduce .vs[].n as $vn (.;
      if .vs[$vn].index < 0
      then strongConnect($vn)
      else . end
    )
    | .sccs
;

# Vertices
def vs: [range(0;8) | Node ];

# Edges
def es:
  [ [1],
    [2],
    [0],
    [1, 2, 4],
    [5, 3],
    [2, 6],
    [5],
    [4, 7, 6]
  ]
;

{ vs: vs, es: es }
| tarjan


using LightGraphs

edge_list=[(1,2),(3,1),(6,3),(6,7),(7,6),(2,3),(4,2),(4,3),(4,5),(5,6),(5,4),(8,5),(8,8),(8,7)]

grph = SimpleDiGraph(Edge.(edge_list))

tarj = strongly_connected_components(grph)

inzerobase(arrarr) = map(x -> sort(x .- 1, rev=true), arrarr)

println("Results in the zero-base scheme: $(inzerobase(tarj))")


// version 1.1.3

import java.util.Stack

typealias Nodes = List<Node>

class Node(val n: Int) {
    var index   = -1  // -1 signifies undefined
    var lowLink = -1
    var onStack = false

    override fun toString()  = n.toString()
}

class DirectedGraph(val vs: Nodes, val es: Map<Node, Nodes>)

fun tarjan(g: DirectedGraph): List<Nodes> {
    val sccs = mutableListOf<Nodes>()
    var index = 0
    val s = Stack<Node>()

    fun strongConnect(v: Node) {
        // Set the depth index for v to the smallest unused index
        v.index = index
        v.lowLink = index
        index++
        s.push(v)
        v.onStack = true

        // consider successors of v
        for (w in g.es[v]!!) {
            if (w.index < 0) {
                // Successor w has not yet been visited; recurse on it
                strongConnect(w)
                v.lowLink = minOf(v.lowLink, w.lowLink)
            }
            else if (w.onStack) {
                // Successor w is in stack s and hence in the current SCC
                v.lowLink = minOf(v.lowLink, w.index)
            }
        }

        // If v is a root node, pop the stack and generate an SCC
        if (v.lowLink == v.index) {
            val scc = mutableListOf<Node>()
            do {
                val w = s.pop()
                w.onStack = false
                scc.add(w)
            }
            while (w != v)
            sccs.add(scc)
        }
    }

    for (v in g.vs) if (v.index < 0) strongConnect(v)
    return sccs
}

fun main(args: Array<String>) {
    val vs = (0..7).map { Node(it) }
    val es = mapOf(
        vs[0] to listOf(vs[1]),
        vs[2] to listOf(vs[0]),
        vs[5] to listOf(vs[2], vs[6]),
        vs[6] to listOf(vs[5]),
        vs[1] to listOf(vs[2]),
        vs[3] to listOf(vs[1], vs[2], vs[4]),
        vs[4] to listOf(vs[5], vs[3]),
        vs[7] to listOf(vs[4], vs[7], vs[6])
    )
    val g = DirectedGraph(vs, es)
    val sccs = tarjan(g)
    println(sccs.joinToString("\n"))
}


   NB.  Temp conversions are all linear polynomials
   K2K    =:     0    1    NB. K = (1  *k) +   0
   K2C    =:  _273    1    NB. C = (1  *k) - 273
   K2F    =:  _459.67 1.8  NB. F = (1.8*k) - 459.67
   K2R    =:     0    1.8  NB. R = (1.8*k) +   0

   NB.  Do all conversions at once (eval
   NB.  polynomials in parallel). This is the
   NB.  numeric matrix J programs would manipulate
   NB.  directly.
   k2KCFR =:  (K2K , K2C , K2F ,: K2R) p./ ]


import sequtils, strutils, tables

type

  Node = ref object
    val: int
    index: int
    lowLink: int
    onStack: bool

  Nodes = seq[Node]

  DirectedGraph = object
    nodes: seq[Node]
    edges: Table[int, Nodes]

func initNode(n: int): Node =
  Node(val: n, index: -1, lowLink: -1, onStack: false)

func `$`(node: Node): string = $node.val

func tarjan(g: DirectedGraph): seq[Nodes] =
  var index = 0
  var s: seq[Node]
  var sccs: seq[Nodes]

  func strongConnect(v: Node) =

    # Set the depth index for "v" to the smallest unused index.
    v.index = index
    v.lowLink = index
    inc index
    s.add v
    v.onStack = true

    # Consider successors of "v".
    for w in g.edges[v.val]:
      if w.index < 0:
        # Successor "w" has not yet been visited; recurse on it.
        w.strongConnect()
        v.lowLink = min(v.lowLink, w.lowLink)
      elif w.onStack:
        # Successor "w" is in stack "s" and hence in the current SCC.
        v.lowLink = min(v.lowLink, w.index)

    # If "v" is a root node, pop the stack and generate an SCC.
    if v.lowLink == v.index:
      var scc: Nodes
      while true:
        let w = s.pop()
        w.onStack = false
        scc.add w
        if w == v: break
      sccs.add scc

  for v in g.nodes:
    if v.index < 0:
      v.strongConnect()
  result = move(sccs)

when isMainModule:

  let vs = toSeq(0..7).map(initNode)
  let es = {0: @[vs[1]],
            1: @[vs[2]],
            2: @[vs[0]],
            3: @[vs[1], vs[2], vs[4]],
            4: @[vs[5], vs[3]],
            5: @[vs[2], vs[6]],
            6: @[vs[5]],
            7: @[vs[4], vs[7], vs[6]]}.toTable
  var g = DirectedGraph(nodes: vs, edges: es)
  let sccs = g.tarjan()
  echo sccs.join("\n")


use strict;
use warnings;
use feature <say state current_sub>;
use List::Util qw(min);

sub tarjan {
    my (%k) = @_;
    my (%onstack, %index, %lowlink, @stack, @connected);

    my sub strong_connect {
        my ($vertex, $i) = @_;
        $index{$vertex}   = $i;
        $lowlink{$vertex} = $i + 1;
        $onstack{$vertex} = 1;
        push @stack, $vertex;
        for my $connection (@{$k{$vertex}}) {
            if (not defined $index{$connection}) {
                __SUB__->($connection, $i + 1);
                $lowlink{$vertex} = min($lowlink{$connection}, $lowlink{$vertex});
            }
            elsif ($onstack{$connection}) {
                $lowlink{$vertex} = min($index{$connection}, $lowlink{$vertex});
            }
        }
        if ($lowlink{$vertex} eq $index{$vertex}) {
            my @node;
            do {
                push @node, pop @stack;
                $onstack{$node[-1]} = 0;
            } while $node[-1] ne $vertex;
            push @connected, [@node];
        }
    }

    for (sort keys %k) {
        strong_connect($_, 0) unless $index{$_};
    }
    @connected;
}

my %test1 = (
             0 => [1],
             1 => [2],
             2 => [0],
             3 => [1, 2, 4],
             4 => [3, 5],
             5 => [2, 6],
             6 => [5],
             7 => [4, 6, 7]
            );

my %test2 = (
             'Andy' => ['Bart'],
             'Bart' => ['Carl'],
             'Carl' => ['Andy'],
             'Dave' => [qw<Bart Carl Earl>],
             'Earl' => [qw<Dave Fred>],
             'Fred' => [qw<Carl Gary>],
             'Gary' => ['Fred'],
             'Hank' => [qw<Earl Gary Hank>]
            );

print "Strongly connected components:\n";
print join(', ', sort @$_) . "\n" for tarjan(%test1);
print "\nStrongly connected components:\n";
print join(', ', sort @$_) . "\n" for tarjan(%test2);


F rotated(String s)
   R s[1..]‘’s[0]

V s = Set(File(‘unixdict.txt’).read().rtrim("\n").split("\n"))
L !s.empty
   L(=word) s // `=` is needed here because otherwise after `s.remove(word)` `word` becomes invalid
      s.remove(word)
      I word.len < 3
         L.break

      V w = word
      L 0 .< word.len - 1
         w = rotated(w)
         I w C s
            s.remove(w)
         E
            L.break
      L.was_no_break
         print(word, end' ‘’)
         w = word
         L 0 .< word.len - 1
            w = rotated(w)
            print(‘ -> ’w, end' ‘’)
         print()

      L.break


public class TemperatureConversion {
    public static void main(String args[]) {
        if (args.length == 1) {
            try {
                double kelvin = Double.parseDouble(args[0]);
                if (kelvin >= 0) {
                    System.out.printf("K  %2.2f\n", kelvin);
                    System.out.printf("C  %2.2f\n", kelvinToCelsius(kelvin));
                    System.out.printf("F  %2.2f\n", kelvinToFahrenheit(kelvin));
                    System.out.printf("R  %2.2f\n", kelvinToRankine(kelvin));
                } else {
                    System.out.printf("%2.2f K is below absolute zero", kelvin);
                }
            } catch (NumberFormatException e) {
                System.out.println(e);
            }
        }
    }

    public static double kelvinToCelsius(double k) {
        return k - 273.15;
    }

    public static double kelvinToFahrenheit(double k) {
        return k * 1.8 - 459.67;
    }

    public static double kelvinToRankine(double k) {
        return k * 1.8;
    }
}


with javascript_semantics
constant g = {{2}, {3}, {1}, {2,3,5}, {6,4}, {3,7}, {6}, {5,8,7}}

sequence index, lowlink, stacked, stack
integer x

function strong_connect(integer n, emit)
    index[n] = x
    lowlink[n] = x
    stacked[n] = 1
    stack &= n
    x += 1
    for b=1 to length(g[n]) do
        integer nb = g[n][b]
        if index[nb] == 0 then
            if not strong_connect(nb,emit) then
                return false
            end if
            if lowlink[nb] < lowlink[n] then
                lowlink[n] = lowlink[nb]
            end if
        elsif stacked[nb] == 1 then
            if index[nb] < lowlink[n] then
                lowlink[n] = index[nb]
            end if
        end if
    end for
    if lowlink[n] == index[n] then
        sequence c = {}
        while true do
            integer w := stack[$]
            stack = stack[1..$-1]
            stacked[w] = 0
            c = prepend(c, w)
            if w == n then
                emit(c)
                exit
            end if
        end while
    end if
    return true
end function

procedure tarjan(sequence g, integer emit)
    index   = repeat(0,length(g))
    lowlink = repeat(0,length(g))
    stacked = repeat(0,length(g))
    stack = {}
    x = 1
    for n=1 to length(g) do
        if index[n] == 0
        and not strong_connect(n,emit) then
            return
        end if
    end for
end procedure

procedure emit(object c)
-- called for each component identified.
-- each component is a list of nodes.
    ?c
end procedure

tarjan(g,emit)


wordset: map read.lines relative "unixdict.txt" => strip

rotateable?: function [w][
    loop 1..dec size w 'i [
        rotated: rotate w i
        if or? [rotated = w][not? contains? wordset rotated] ->
            return false
    ]
    return true
]

results: new []
loop select wordset 'word [3 =< size word] 'word [
    if rotateable? word ->
        'results ++ @[ sort map 1..size word 'i [ rotate word i ]]
]

loop sort unique results 'result [
    root: first result
    print join.with: " -> " map 1..size root 'i [ rotate.left root i]
]


Teacup_rim_text(wList){
    oWord := [], oRes := [], n := 0
    for i, w in StrSplit(wList, "`n", "`r")
        if StrLen(w) >= 3
            oWord[StrLen(w), w] := true

    for l, obj in oWord
    {
        for w, bool in obj
        {
            loop % l
                if oWord[l, rotate(w)]
                {
                    oWord[l, w] := 0
                    if (A_Index = 1)
                        n++, oRes[n] := w
                    if (A_Index < l)
                        oRes[n] := oRes[n] "," (w := rotate(w))
                }
            if (StrSplit(oRes[n], ",").Count() <> l)
                oRes.RemoveAt(n)
        }
    }
    return oRes
}

rotate(w){
    return SubStr(w, 2) . SubStr(w, 1, 1)
}


var k2c = k => k - 273.15
var k2r = k => k * 1.8
var k2f = k => k2r(k) - 459.67

Number.prototype.toMaxDecimal = function (d) {
    return +this.toFixed(d) + ''
}

function kCnv(k) {
    document.write( k,'K° = ', k2c(k).toMaxDecimal(2),'C° = ', k2r(k).toMaxDecimal(2),'R° = ', k2f(k).toMaxDecimal(2),'F°<br>' )
}

kCnv(21)
kCnv(295)


# round(keep) takes as input any jq (i.e. JSON) number and emits a string.
# "keep" is the desired maximum number of numerals after the decimal point,
# e.g. 9.999|round(2) => 10.00
def round(keep):
  tostring
  | (index("e") | if . then . else index("E") end) as $e
  | if $e then (.[0:$e] | round(keep)) + .[$e+1:]
    else index(".") as $ix
      | if $ix == null then .
        else .[0:$ix + 1] as $head
          | .[$ix+1:$ix+keep+2] as $tail
          | if ($tail|length) <= keep then $head + $tail
            else ($tail | .[length-1:] | tonumber) as $last
              | if $last < 5 then  $head + $tail[0:$tail|length - 1]
                else (($head + $tail) | length) as $length
                  | ($head[0:-1] + $tail)
                  | (tonumber +  (if $head[0:1]=="-" then -5 else 5 end))
                  | tostring
                  | .[0: ($ix+1+length-$length)] + "." + .[length-keep-1:-1]
                end
            end
        end
    end;

def k2c: . - 273.15;
def k2f: . * 1.8 - 459.67;
def k2r: . * 1.8;

# produce a stream
def cfr:
  if . >= 0
  then "Kelvin: \(.)", "Celsius: \(k2c|round(2))",
       "Fahrenheit: \(k2f|round(2))", "Rankine: \(k2r|round(2))"
  else error("cfr: \(.) is an invalid temperature in degrees Kelvin")
  end;

cfr


from collections import defaultdict

def from_edges(edges):
    '''translate list of edges to list of nodes'''

    class Node:
        def __init__(self):
            # root is one of:
            #   None: not yet visited
            #   -1: already processed
            #   non-negative integer: what Wikipedia pseudo code calls 'lowlink'
            self.root = None
            self.succ = []

    nodes = defaultdict(Node)
    for v,w in edges:
        nodes[v].succ.append(nodes[w])

    for i,v in nodes.items(): # name the nodes for final output
        v.id = i

    return nodes.values()

def trajan(V):
    def strongconnect(v, S):
        v.root = pos = len(S)
        S.append(v)

        for w in v.succ:
            if w.root is None:  # not yet visited
                yield from strongconnect(w, S)

            if w.root >= 0:  # still on stack
                v.root = min(v.root, w.root)

        if v.root == pos:  # v is the root, return everything above
            res, S[pos:] = S[pos:], []
            for w in res:
                w.root = -1
            yield [r.id for r in res]

    for v in V:
        if v.root is None:
            yield from strongconnect(v, [])

tables = [  # table 1
            [(1,2), (3,1), (3,6), (6,7), (7,6), (2,3), (4,2),
             (4,3), (4,5), (5,6), (5,4), (8,5), (8,7), (8,6)],

            # table 2
            [('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'Other')]]

for table in (tables):
    for g in trajan(from_edges(table)):
        print(g)
    print()


#lang racket

(require syntax/parse/define
         fancy-app
         (for-syntax racket/syntax))

(struct node (name index low-link on?) #:transparent #:mutable
  #:methods gen:custom-write
  [(define (write-proc v port mode) (fprintf port "~a" (node-name v)))])

(define-syntax-parser change!
  [(_ x:id f) #'(set! x (f x))]
  [(_ accessor:id v f)
   #:with mutator! (format-id this-syntax "set-~a!" #'accessor)
   #'(mutator! v (f (accessor v)))])

(define (tarjan g)
  (define sccs '())
  (define index 0)
  (define s '())

  (define (dfs v)
    (set-node-index! v index)
    (set-node-low-link! v index)
    (set-node-on?! v #t)
    (change! s (cons v _))
    (change! index add1)

    (for ([w (in-list (hash-ref g v '()))])
      (match-define (node _ index low-link on?) w)
      (cond
        [(not index) (dfs w)
                     (change! node-low-link v (min (node-low-link w) _))]
        [on? (change! node-low-link v (min index _))]))

    (when (= (node-low-link v) (node-index v))
      (define-values (scc* s*) (splitf-at s (λ (w) (not (eq? w v)))))
      (set! s (rest s*))
      (define scc (cons (first s*) scc*))
      (for ([w (in-list scc)]) (set-node-on?! w #f))
      (change! sccs (cons scc _))))

  (for* ([(u _) (in-hash g)] #:when (not (node-index u))) (dfs u))
  sccs)

(define (make-graph xs)
  (define store (make-hash))
  (define (make-node v) (hash-ref! store v (thunk (node v #f #f #f))))

  ;; it's important that we use hasheq instead of hash so that we compare
  ;; reference instead of actual value. Had we use the actual value,
  ;; the key would be a mutable value, which causes undefined behavior
  (for/hasheq ([vs (in-list xs)]) (values (make-node (first vs)) (map make-node (rest vs)))))

(tarjan (make-graph '([0 1]
                      [2 0]
                      [5 2 6]
                      [6 5]
                      [1 2]
                      [3 1 2 4]
                      [4 5 3]
                      [7 4 7 6])))


# syntax: GAWK -f TEACUP_RIM_TEXT.AWK UNIXDICT.TXT
#
# sorting:
#   PROCINFO["sorted_in"] is used by GAWK
#   SORTTYPE is used by Thompson Automation's TAWK
#
{   for (i=1; i<=NF; i++) {
      arr[tolower($i)] = 0
    }
}
END {
    PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
    for (i in arr) {
      leng = length(i)
      if (leng > 2) {
        delete tmp_arr
        words = str = i
        tmp_arr[i] = ""
        for (j=2; j<=leng; j++) {
          str = substr(str,2) substr(str,1,1)
          if (str in arr) {
            words = words " " str
            tmp_arr[str] = ""
          }
        }
        if (length(tmp_arr) == leng) {
          count = 0
          for (j in tmp_arr) {
            (arr[j] == 0) ? arr[j]++ : count++
          }
          if (count == 0) {
            printf("%s\n",words)
            circular++
          }
        }
      }
    }
    printf("%d words, %d circular\n",length(arr),circular)
    exit(0)
}


OPTION COLLAPSE TRUE

dict$ = LOAD$(DIRNAME$(ME$) & "/unixdict.txt")

FOR word$ IN dict$ STEP NL$
    IF LEN(word$) = 3 AND AMOUNT(UNIQ$(EXPLODE$(word$, 1))) = 3 THEN domain$ = APPEND$(domain$, 0, word$)
NEXT

FOR w1$ IN domain$
    w2$ = RIGHT$(w1$, 2) & LEFT$(w1$, 1)
    w3$ = RIGHT$(w2$, 2) & LEFT$(w2$, 1)
    IF TALLY(domain$, w2$) AND TALLY(domain$, w3$) AND NOT(TALLY(result$, w1$)) THEN
        result$ = APPEND$(result$, 0, w1$ & " " & w2$ & " " & w3$, NL$)
    ENDIF
NEXT

PRINT result$
PRINT "Total words: ", AMOUNT(dict$, NL$), ", and ", AMOUNT(result$, NL$), " are circular."


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

int string_compare(gconstpointer p1, gconstpointer p2) {
    const char* const* s1 = p1;
    const char* const* s2 = p2;
    return strcmp(*s1, *s2);
}

GPtrArray* load_dictionary(const char* file, GError** error_ptr) {
    GError* error = NULL;
    GIOChannel* channel = g_io_channel_new_file(file, "r", &error);
    if (channel == NULL) {
        g_propagate_error(error_ptr, error);
        return NULL;
    }
    GPtrArray* dict = g_ptr_array_new_full(1024, g_free);
    GString* line = g_string_sized_new(64);
    gsize term_pos;
    while (g_io_channel_read_line_string(channel, line, &term_pos,
                                         &error) == G_IO_STATUS_NORMAL) {
        char* word = g_strdup(line->str);
        word[term_pos] = '\0';
        g_ptr_array_add(dict, word);
    }
    g_string_free(line, TRUE);
    g_io_channel_unref(channel);
    if (error != NULL) {
        g_propagate_error(error_ptr, error);
        g_ptr_array_free(dict, TRUE);
        return NULL;
    }
    g_ptr_array_sort(dict, string_compare);
    return dict;
}

void rotate(char* str, size_t len) {
    char c = str[0];
    memmove(str, str + 1, len - 1);
    str[len - 1] = c;
}

char* dictionary_search(const GPtrArray* dictionary, const char* word) {
    char** result = bsearch(&word, dictionary->pdata, dictionary->len,
                            sizeof(char*), string_compare);
    return result != NULL ? *result : NULL;
}

void find_teacup_words(GPtrArray* dictionary) {
    GHashTable* found = g_hash_table_new(g_str_hash, g_str_equal);
    GPtrArray* teacup_words = g_ptr_array_new();
    GString* temp = g_string_sized_new(8);
    for (size_t i = 0, n = dictionary->len; i < n; ++i) {
        char* word = g_ptr_array_index(dictionary, i);
        size_t len = strlen(word);
        if (len < 3 || g_hash_table_contains(found, word))
            continue;
        g_ptr_array_set_size(teacup_words, 0);
        g_string_assign(temp, word);
        bool is_teacup_word = true;
        for (size_t i = 0; i < len - 1; ++i) {
            rotate(temp->str, len);
            char* w = dictionary_search(dictionary, temp->str);
            if (w == NULL) {
                is_teacup_word = false;
                break;
            }
            if (strcmp(word, w) != 0 && !g_ptr_array_find(teacup_words, w, NULL))
                g_ptr_array_add(teacup_words, w);
        }
        if (is_teacup_word && teacup_words->len > 0) {
            printf("%s", word);
            g_hash_table_add(found, word);
            for (size_t i = 0; i < teacup_words->len; ++i) {
                char* teacup_word = g_ptr_array_index(teacup_words, i);
                printf(" %s", teacup_word);
                g_hash_table_add(found, teacup_word);
            }
            printf("\n");
        }
    }
    g_string_free(temp, TRUE);
    g_ptr_array_free(teacup_words, TRUE);
    g_hash_table_destroy(found);
}

int main(int argc, char** argv) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s dictionary\n", argv[0]);
        return EXIT_FAILURE;
    }
    GError* error = NULL;
    GPtrArray* dictionary = load_dictionary(argv[1], &error);
    if (dictionary == NULL) {
        if (error != NULL) {
            fprintf(stderr, "Cannot load dictionary file '%s': %s\n",
                    argv[1], error->message);
            g_error_free(error);
        }
        return EXIT_FAILURE;
    }
    find_teacup_words(dictionary);
    g_ptr_array_free(dictionary, TRUE);
    return EXIT_SUCCESS;
}


// version 1.1.2

class Kelvin(val degrees: Double) {
    fun toCelsius() = degrees - 273.15

    fun toFahreneit() = (degrees - 273.15) * 1.8 + 32.0

    fun toRankine() = (degrees - 273.15) * 1.8 + 32.0 + 459.67
}

fun main(args: Array<String>) {
    print("Enter the temperature in degrees Kelvin : ")
    val degrees = readLine()!!.toDouble()
    val k = Kelvin(degrees)
    val f = "% 1.2f"
    println()
    println("K  ${f.format(k.degrees)}\n")
    println("C  ${f.format(k.toCelsius())}\n")
    println("F  ${f.format(k.toFahreneit())}\n")
    println("R  ${f.format(k.toRankine())}")
}


sub tarjan (%k) {
    my %onstack;
    my %index;
    my %lowlink;
    my @stack;
    my @connected;

    sub strong-connect ($vertex) {
         state $index      = 0;
         %index{$vertex}   = $index;
         %lowlink{$vertex} = $index++;
         %onstack{$vertex} = True;
         @stack.push: $vertex;
         for |%k{$vertex} -> $connection {
             if not %index{$connection}.defined {
                 strong-connect($connection);
                 %lowlink{$vertex} min= %lowlink{$connection};
             }
             elsif %onstack{$connection} {
                 %lowlink{$vertex} min= %index{$connection};
             }
        }
        if %lowlink{$vertex} eq %index{$vertex} {
            my @node;
            repeat {
                @node.push: @stack.pop;
                %onstack{@node.tail} = False;
            } while @node.tail ne $vertex;
            @connected.push: @node;
        }
    }

    .&strong-connect unless %index{$_} for %k.keys;

    @connected
}

# TESTING

-> $test { say "\nStrongly connected components: ", |tarjan($test).sort».sort } for

# hash of vertex, edge list pairs
(((1),(2),(0),(1,2,4),(3,5),(2,6),(5),(4,6,7)).pairs.hash),

# Same layout test data with named vertices instead of numbered.
%(:Andy<Bart>,
  :Bart<Carl>,
  :Carl<Andy>,
  :Dave<Bart Carl Earl>,
  :Earl<Dave Fred>,
  :Fred<Carl Gary>,
  :Gary<Fred>,
  :Hank<Earl Gary Hank>
)


/* REXX - Tarjan's Algorithm                        */
/* Vertices are numbered 1 to 8 (instead of 0 to 7) */
g='[2] [3] [1] [2 3 5] [4 6] [3 7] [6] [5 7 8]'
gg=g
Do i=1 By 1 While gg>''
  Parse Var gg '[' g.i ']' gg
  name.i=i-1
  End
g.0=i-1
index.=0
lowlink.=0
stacked.=0
stack.=0
x=1
Do n=1 To g.0
  If index.n=0 Then
    If strong_connect(n)=0 Then
      Return
  End
Exit

strong_connect: Procedure Expose x g. index. lowlink. stacked. stack. name.
Parse Arg n
index.n = x
lowlink.n = x
stacked.n = 1
Call stack n
x=x+1
Do b=1 To words(g.n)
  Call show_all
  nb=word(g.n,b)
  If index.nb=0 Then Do
    If strong_connect(nb)=0 Then
      Return 0
    If lowlink.nb < lowlink.n Then
      lowlink.n = lowlink.nb
    End
  Else Do
    If stacked.nb = 1 Then
      If index.nb < lowlink.n Then
        lowlink.n = index.nb
    end
  end
if lowlink.n=index.n then Do
  c=''
  Do z=stack.0 By -1
    w=stack.z
    stacked.w=0
    stack.0=stack.0-1
    c=name.w c
    If w=n Then Do
      Say '['space(c)']'
      Return 1
      End
    End
  End
Return 1

stack: Procedure Expose stack.
Parse Arg m
z=stack.0+1
stack.z=m
stack.0=z
Return

/* The following were used for debugging (and understanding) */

show_all: Return
ind='Index  '
low='Lowlink'
sta='Stacked'
Do z=1 To g.0
  ind=ind index.z
  low=low lowlink.z
  sta=sta stacked.z
  End
Say ind
Say low
Say sta
Return

show_stack:
ol='Stack'
Do z=1 To stack.0
  ol=ol stack.z
  End
Say ol
Return


#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <vector>

// filename is expected to contain one lowercase word per line
std::set<std::string> load_dictionary(const std::string& filename) {
    std::ifstream in(filename);
    if (!in)
        throw std::runtime_error("Cannot open file " + filename);
    std::set<std::string> words;
    std::string word;
    while (getline(in, word))
        words.insert(word);
    return words;
}

void find_teacup_words(const std::set<std::string>& words) {
    std::vector<std::string> teacup_words;
    std::set<std::string> found;
    for (auto w = words.begin(); w != words.end(); ++w) {
        std::string word = *w;
        size_t len = word.size();
        if (len < 3 || found.find(word) != found.end())
            continue;
        teacup_words.clear();
        teacup_words.push_back(word);
        for (size_t i = 0; i + 1 < len; ++i) {
            std::rotate(word.begin(), word.begin() + 1, word.end());
            if (word == *w || words.find(word) == words.end())
                break;
            teacup_words.push_back(word);
        }
        if (teacup_words.size() == len) {
            found.insert(teacup_words.begin(), teacup_words.end());
            std::cout << teacup_words[0];
            for (size_t i = 1; i < len; ++i)
                std::cout << ' ' << teacup_words[i];
            std::cout << '\n';
        }
    }
}

int main(int argc, char** argv) {
    if (argc != 2) {
        std::cerr << "usage: " << argv[0] << " dictionary\n";
        return EXIT_FAILURE;
    }
    try {
        find_teacup_words(load_dictionary(argv[1]));
    } catch (const std::exception& ex) {
        std::cerr << ex.what() << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}


{def to-celsius {lambda {:k} {- :k 273.15}}}
-> to-celsius

{def to-farenheit {lambda {:k} {- {* :k 1.8} 459.67}}}
-> to-farenheit

{def to-rankine {lambda {:k} {* :k 1.8}}}
-> to-rankine

{def format {lambda {:n} {/ {round {* :n 100}} 100}}}
-> format

{def kelvinConversion
 {lambda {:k}
  kelvin is equivalent to:{br}
  {format {to-celsius :k}} celsius{br}
  {format {to-farenheit :k}} farenheit{br}
  {format {to-rankine :k}} rankine}}
-> kelvinConversion

{kelvinConversion 21}
->
kelvin is equivalent to:
 -252.15 celsius
 -421.87 farenheit
 37.8 rankine


define tempconverter(temp, kind) => {

    local(
        _temp       = decimal(#temp),
        convertratio    = 1.8,
        k_c     = 273.15,
        r_f     = 459.67,
        k,c,r,f
    )

    match(#kind) => {
        case('k')
            #k = #_temp
            #c = -#k_c + #k
            #r = #k * #convertratio
            #f = -#r_f + #r
        case('c')
            #c = #_temp
            #k = #k_c + #c
            #r = #k * #convertratio
            #f = -#r_f + #r
        case('r')
            #r = #_temp
            #f = -#r_f + #r
            #k = #r / #convertratio
            #c = -#k_c + #k
        case('f')
            #f = #_temp
            #r = #r_f + #f
            #k = #r / #convertratio
            #c = -#k_c + #k
        case
            return 'Something wrong'
    }

    return ('K = ' + #k -> asstring(-precision = 2) +
        ' C = ' + #c -> asstring(-precision = 2) +
        ' R = ' + #r -> asstring(-precision = 2) +
        ' F = ' + #f -> asstring(-precision = 2)
        )
}

tempconverter(21, 'k')
'
'
tempconverter(21, 'c')
'
'
tempconverter(-41, 'c')
'
'
tempconverter(37.80, 'r')
'
'
tempconverter(69.80, 'f')


use std::collections::{BTreeMap, BTreeSet};

// Using a naked BTreeMap would not be very nice, so let's make a simple graph representation
#[derive(Clone, Debug)]
pub struct Graph {
    neighbors: BTreeMap<usize, BTreeSet<usize>>,
}

impl Graph {
    pub fn new(size: usize) -> Self {
        Self {
            neighbors: (0..size).fold(BTreeMap::new(), |mut acc, x| {
                acc.insert(x, BTreeSet::new());
                acc
            }),
        }
    }

    pub fn edges<'a>(&'a self, vertex: usize) -> impl Iterator<Item = usize> + 'a {
        self.neighbors[&vertex].iter().cloned()
    }

    pub fn add_edge(&mut self, from: usize, to: usize) {
        assert!(to < self.len());
        self.neighbors.get_mut(&from).unwrap().insert(to);
    }

    pub fn add_edges(&mut self, from: usize, to: impl IntoIterator<Item = usize>) {
        let limit = self.len();

        self.neighbors
            .get_mut(&from)
            .unwrap()
            .extend(to.into_iter().filter(|x| {
                assert!(*x < limit);
                true
            }));
    }

    pub fn is_empty(&self) -> bool {
        self.neighbors.is_empty()
    }

    pub fn len(&self) -> usize {
        self.neighbors.len()
    }
}

#[derive(Clone)]
struct VertexState {
    index: usize,
    low_link: usize,
    on_stack: bool,
}

// The easy way not to fight with Rust's borrow checker is moving the state in
// a structure and simply invoke methods on that structure.

pub struct Tarjan<'a> {
    graph: &'a Graph,
    index: usize,
    stack: Vec<usize>,
    state: Vec<VertexState>,
    components: Vec<BTreeSet<usize>>,
}

impl<'a> Tarjan<'a> {
    // Having index: Option<usize> would look nicer, but requires just
    // some unwraps and Vec has actual len limit isize::MAX anyway, so
    // we can reserve this large value as the invalid one.
    const INVALID_INDEX: usize = usize::MAX;

    pub fn walk(graph: &'a Graph) -> Vec<BTreeSet<usize>> {
        Self {
            graph,
            index: 0,
            stack: Vec::new(),
            state: vec![
                VertexState {
                    index: Self::INVALID_INDEX,
                    low_link: Self::INVALID_INDEX,
                    on_stack: false
                };
                graph.len()
            ],
            components: Vec::new(),
        }
        .visit_all()
    }

    fn visit_all(mut self) -> Vec<BTreeSet<usize>> {
        for vertex in 0..self.graph.len() {
            if self.state[vertex].index == Self::INVALID_INDEX {
                self.visit(vertex);
            }
        }

        self.components
    }

    fn visit(&mut self, v: usize) {
        let v_ref = &mut self.state[v];
        v_ref.index = self.index;
        v_ref.low_link = self.index;
        self.index += 1;
        self.stack.push(v);
        v_ref.on_stack = true;

        for w in self.graph.edges(v) {
            let w_ref = &self.state[w];
            if w_ref.index == Self::INVALID_INDEX {
                self.visit(w);
                let w_low_link = self.state[w].low_link;
                let v_ref = &mut self.state[v];
                v_ref.low_link = v_ref.low_link.min(w_low_link);
            } else if w_ref.on_stack {
                let w_index = self.state[w].index;
                let v_ref = &mut self.state[v];
                v_ref.low_link = v_ref.low_link.min(w_index);
            }
        }

        let v_ref = &self.state[v];
        if v_ref.low_link == v_ref.index {
            let mut component = BTreeSet::new();

            loop {
                let w = self.stack.pop().unwrap();
                self.state[w].on_stack = false;
                component.insert(w);
                if w == v {
                    break;
                }
            }

            self.components.push(component);
        }
    }
}

fn main() {
    let graph = {
        let mut g = Graph::new(8);
        g.add_edge(0, 1);
        g.add_edge(2, 0);
        g.add_edges(5, vec![2, 6]);
        g.add_edge(6, 5);
        g.add_edge(1, 2);
        g.add_edges(3, vec![1, 2, 4]);
        g.add_edges(4, vec![5, 3]);
        g.add_edges(7, vec![4, 7, 6]);
        g
    };

    for component in Tarjan::walk(&graph) {
        println!("{:?}", component);
    }
}


func tarjan (k) {

    var(:onstack, :index, :lowlink, *stack, *connected)

    func strong_connect (vertex, i=0) {

         index{vertex}   = i
         lowlink{vertex} = i+1
         onstack{vertex} = true
         stack << vertex

         for connection in (k{vertex}) {
             if (index{connection} == nil) {
                 strong_connect(connection, i+1)
                 lowlink{vertex} `min!` lowlink{connection}
             }
             elsif (onstack{connection}) {
                 lowlink{vertex} `min!` index{connection}
             }
        }

        if (lowlink{vertex} == index{vertex}) {
            var *node
            do {
                node << stack.pop
                onstack{node.tail} = false
            } while (node.tail != vertex)
            connected << node
        }
    }

    { strong_connect(_) if !index{_} } << k.keys

    return connected
}

var tests = [
    Hash(
         0 => <1>,
         1 => <2>,
         2 => <0>,
         3 => <1 2 4>,
         4 => <3 5>,
         5 => <2 6>,
         6 => <5>,
         7 => <4 6 7>,
    ),
    Hash(
        :Andy => <Bart>,
        :Bart => <Carl>,
        :Carl => <Andy>,
        :Dave => <Bart Carl Earl>,
        :Earl => <Dave Fred>,
        :Fred => <Carl Gary>,
        :Gary => <Fred>,
        :Hank => <Earl Gary Hank>,
    )
]

tests.each {|t|
    say ("Strongly connected components: ", tarjan(t).map{.sort}.sort)
}


import "/seq" for Stack
import "/dynamic" for Tuple

class Node {
    construct new(n) {
        _n = n
        _index = -1   // -1 signifies undefined
        _lowLink = -1
        _onStack = false
    }

    n           { _n }
    index       { _index }
    index=(v)   { _index = v }
    lowLink     { _lowLink }
    lowLink=(v) { _lowLink = v }
    onStack     { _onStack }
    onStack=(v) { _onStack = v }

    toString    { _n.toString }
}

var DirectedGraph = Tuple.create("DirectedGraph", ["vs", "es"])

var tarjan = Fn.new { |g|
    var sccs = []
    var index = 0
    var s = Stack.new()

    var strongConnect // recursive closure
    strongConnect = Fn.new { |v|
        // Set the depth index for v to the smallest unused index
        v.index = index
        v.lowLink = index
        index = index + 1
        s.push(v)
        v.onStack = true

        // consider successors of v
        for (w in g.es[v.n]) {
            if (w.index < 0) {
                // Successor w has not yet been visited; recurse on it
                strongConnect.call(w)
                v.lowLink = v.lowLink.min(w.lowLink)
            } else if (w.onStack) {
                // Successor w is in stack s and hence in the current SCC
                v.lowLink = v.lowLink.min(w.index)
            }
        }

        // If v is a root node, pop the stack and generate an SCC
        if (v.lowLink == v.index) {
            var scc = []
            while (true) {
                var w = s.pop()
                w.onStack = false
                scc.add(w)
                if (w == v) break
            }
            sccs.add(scc)
        }
    }

    for (v in g.vs) if (v.index < 0) strongConnect.call(v)
    return sccs
}

var vs = (0..7).map { |i| Node.new(i) }.toList
var es = {
    0: [vs[1]],
    2: [vs[0]],
    5: [vs[2], vs[6]],
    6: [vs[5]],
    1: [vs[2]],
    3: [vs[1], vs[2], vs[4]],
    4: [vs[5], vs[3]],
    7: [vs[4], vs[7], vs[6]]
}
var g = DirectedGraph.new(vs, es)
var sccs = tarjan.call(g)
System.print(sccs.join("\n"))


// Teacup rim text. Nigel Galloway: August 7th., 2019
let  N=System.IO.File.ReadAllLines("dict.txt")|>Array.filter(fun n->String.length n=3 && Seq.length(Seq.distinct n)>1)|>Set.ofArray
let fG z=Set.map(fun n->System.String(Array.ofSeq (Seq.permute(fun g->(g+z)%3)n))) N
Set.intersectMany [N;fG 1;fG 2]|>Seq.distinctBy(Seq.sort>>Array.ofSeq>>System.String)|>Seq.iter(printfn "%s")


USING: combinators.short-circuit fry grouping hash-sets
http.client kernel math prettyprint sequences sequences.extras
sets sorting splitting ;

"https://www.mit.edu/~ecprice/wordlist.10000" http-get nip
"\n" split [ { [ length 3 < ] [ all-equal? ] } 1|| ] reject
[ [ all-rotations ] map ] [ >hash-set ] bi
'[ [ _ in? ] all? ] filter [ natural-sort ] map members .


package main

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

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func readWords(fileName string) []string {
    file, err := os.Open(fileName)
    check(err)
    defer file.Close()
    var words []string
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        word := strings.ToLower(strings.TrimSpace(scanner.Text()))
        if len(word) >= 3 {
            words = append(words, word)
        }
    }
    check(scanner.Err())
    return words
}

func rotate(runes []rune) {
    first := runes[0]
    copy(runes, runes[1:])
    runes[len(runes)-1] = first
}

func main() {
    dicts := []string{"mit_10000.txt", "unixdict.txt"} // local copies
    for _, dict := range dicts {
        fmt.Printf("Using %s:\n\n", dict)
        words := readWords(dict)
        n := len(words)
        used := make(map[string]bool)
    outer:
        for _, word := range words {
            runes := []rune(word)
            variants := []string{word}
            for i := 0; i < len(runes)-1; i++ {
                rotate(runes)
                word2 := string(runes)
                if word == word2 || used[word2] {
                    continue outer
                }
                ix := sort.SearchStrings(words, word2)
                if ix == n || words[ix] != word2 {
                    continue outer
                }
                variants = append(variants, word2)
            }
            for _, variant := range variants {
                used[variant] = true
            }
            fmt.Println(variants)
        }
        fmt.Println()
    }
}


# Temperature conversion, in LIL
func kToc k {expr $k - 273.15}
func kTor k {expr $k / 5.0 * 9.0}
func kTof k {expr [kTor $k] - 469.67}

write "Enter kelvin temperatures or just enter to quit: "
for {set k [readline]} {![streq $k {}]} {set k [readline]} {
    print "Kelvin:     $k"
    print "Celsius:    [kToc $k]"
    print "Fahrenheit: [kTof $k]"
    print "Rankine:    [kTor $k]"
}


function convertDegrees k
    put k/5 * 9 into r
    put k - 273.15 into c
    put r - 459.67 into f
    return k,r,c,f
end convertDegrees


class Tarjan{
   // input: graph G = (V, Es)
   // output: set of strongly connected components (sets of vertices)
   // Ick: class holds global state for strongConnect(), otherwise inert
   const INDEX=0, LOW_LINK=1, ON_STACK=2;
   fcn init(graph){
      var index=0, stack=List(), components=List(),
          G=List.createLong(graph.len(),0);

      // convert graph to ( (index,lowlink,onStack),(id,links)), ...)
      // sorted by id
      foreach v in (graph){ G[v[0]]=T( L(Void,Void,False),v) }

      foreach v in (G){ if(v[0][INDEX]==Void) strongConnect(v) }

      println("List of strongly connected components:");
      foreach c in (components){ println(c.reverse().concat(",")) }

      returnClass(components);  // over-ride return of class instance
   }
   fcn strongConnect(v){  // v is ( (index,lowlink,onStack), (id,links) )
      // Set the depth index for v to the smallest unused index
      v0:=v[0]; v0[INDEX]=v0[LOW_LINK]=index;
      index+=1;
      v0[ON_STACK]=True;
      stack.push(v);

       // Consider successors of v
      foreach idx in (v[1][1,*]){  // links of v to other vs
         w,w0 := G[idx],w[0];   // well, that is pretty vile
     if(w[0][INDEX]==Void){
        strongConnect(w); // Successor w not yet visited; recurse on it
        v0[LOW_LINK]=v0[LOW_LINK].min(w0[LOW_LINK]);
     }
     else if(w0[ON_STACK])
        // Successor w is in stack S and hence in the current SCC
        v0[LOW_LINK]=v0[LOW_LINK].min(w0[INDEX]);
      }
      // If v is a root node, pop the stack and generate an SCC
      if(v0[LOW_LINK]==v0[INDEX]){
         strong:=List();  // start a new strongly connected component
     do{
        w,w0 := stack.pop(), w[0];
        w0[ON_STACK]=False;
        strong.append(w[1][0]); // add w to strongly connected component
     }while(w.id!=v.id);
     components.append(strong); // output strongly connected component
      }
   }
}


import Data.List (groupBy, intercalate, sort, sortBy)
import qualified Data.Set as S
import Data.Ord (comparing)
import Data.Function (on)

main :: IO ()
main =
  readFile "mitWords.txt" >>= (putStrLn . showGroups . circularWords . lines)

circularWords :: [String] -> [String]
circularWords ws =
  let lexicon = S.fromList ws
  in filter (isCircular lexicon) ws

isCircular :: S.Set String -> String -> Bool
isCircular lex w = 2 < length w && all (`S.member` lex) (rotations w)

rotations :: [a] -> [[a]]
rotations = fmap <$> rotated <*> (enumFromTo 0 . pred . length)

rotated :: [a] -> Int -> [a]
rotated [] _ = []
rotated xs n = zipWith const (drop n (cycle xs)) xs

showGroups :: [String] -> String
showGroups xs =
  unlines $
  intercalate " -> " . fmap snd <$>
  filter
    ((1 <) . length)
    (groupBy (on (==) fst) (sortBy (comparing fst) (((,) =<< sort) <$> xs)))


read=: CR -.~ 1!:1@boxopen  NB. dang that line end!
Filter=:(#~`)(`:6)

prep=: (;~ /:~);._2

gba=: <@:([: ,/ (>@}."1))/.~ 0&{"1
ew=: (>:&# {.)S:_1 Filter
le=: (2 < #@{.)S:_1 Filter
ra=: a: -.~ rotations&>

NB. prep was separated for fun, not necessity
teacup=: [email protected]:[email protected]:[email protected]:gba

rotations=: 3 :0
 subset=: 0 = #@:-.
 assert. 0 1 -: 'ab'(subset~ , subset)'cabag'
 N=. # {. y
 for_word. y do.
  a=. N ]\ (, (<: N)&{.) word
  if. a subset y do. word return. end.
 end.
 ''
)


function convert_temp(k)
    local c = k - 273.15
    local r = k * 1.8
    local f = r - 459.67
    return k, c, r, f
end

print(string.format([[
Kelvin: %.2f K
Celcius: %.2f °C
Rankine: %.2f °R
Fahrenheit: %.2f °F
]],convert_temp(21.0)))


Do
   Input "Kelvin degrees (>=0): ";K
Loop Until (K >= 0)

Print "K = ";K
Print "C = ";(K - 273.15)
Print "F = ";(K * 1.8 - 459.67)
Print "R = ";(K * 1.8)
End


F tau(n)
   V ans = 0
   V i = 1
   V j = 1
   L i * i <= n
      I 0 == n % i
         ans++
         j = n I/ i
         I j != i
            ans++
      i++
   R ans

print((1..100).map(n -> tau(n)))


import java.io.*;
import java.util.*;

public class Teacup {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("usage: java Teacup dictionary");
            System.exit(1);
        }
        try {
            findTeacupWords(loadDictionary(args[0]));
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
    }

    // The file is expected to contain one lowercase word per line
    private static Set<String> loadDictionary(String fileName) throws IOException {
        Set<String> words = new TreeSet<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String word;
            while ((word = reader.readLine()) != null)
                words.add(word);
            return words;
        }
    }

    private static void findTeacupWords(Set<String> words) {
        List<String> teacupWords = new ArrayList<>();
        Set<String> found = new HashSet<>();
        for (String word : words) {
            int len = word.length();
            if (len < 3 || found.contains(word))
                continue;
            teacupWords.clear();
            teacupWords.add(word);
            char[] chars = word.toCharArray();
            for (int i = 0; i < len - 1; ++i) {
                String rotated = new String(rotate(chars));
                if (rotated.equals(word) || !words.contains(rotated))
                    break;
                teacupWords.add(rotated);
            }
            if (teacupWords.size() == len) {
                found.addAll(teacupWords);
                System.out.print(word);
                for (int i = 1; i < len; ++i)
                    System.out.print(" " + teacupWords.get(i));
                System.out.println();
            }
        }
    }

    private static char[] rotate(char[] ch) {
        char c = ch[0];
        System.arraycopy(ch, 1, ch, 0, ch.length - 1);
        ch[ch.length - 1] = c;
        return ch;
    }
}


tempConvert := proc(k)
    seq(printf("%c: %.2f\n", StringTools[UpperCase](substring(i, 1)), convert(k, temperature, kelvin, i)), i in [kelvin, Celsius, Fahrenheit, Rankine]);
    return NULL;
end proc:

tempConvert(21);


tempConvert[t_] := # -> [email protected][#,{"DegreesFahrenheit", "DegreesCelsius", "DegreesRankine"}]&@Quantity[[email protected], "Kelvins"]
tempConvert[21]


/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/*  program taufunction64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ MAXI,      100

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:        .asciz " @ "
szCarriageReturn:   .asciz "\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:                  .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                             // entry of program
    mov x0,#1                     // factor number one
    bl displayResult
    mov x0,#2                     // factor number two
    bl displayResult
    mov x2,#3                     // begin number three
1:                                // begin loop
    mov x5,#2                     // divisor counter
    mov x4,#2                     // first divisor 1
2:
    udiv x0,x2,x4                 // compute divisor 2
    msub x3,x0,x4,x2              // remainder
    cmp x3,#0
    bne 3f                        // remainder = 0 ?
    cmp x0,x4                     // same divisor ?
    add x3,x5,1
    add x6,x5,2
    csel x5,x3,x6,eq
3:
    add x4,x4,#1                  // increment divisor
    cmp x4,x0                     // divisor 1  < divisor 2
    blt 2b                        // yes -> loop

    mov x0,x5                     // equal -> display
    bl displayResult

    add x2,x2,1
    cmp x2,MAXI                   // end ?
    bls 1b                        // no -> loop

    ldr x0,qAdrszCarriageReturn
    bl affichageMess

100:                              // standard end of the program
    mov x0, #0                    // return code
    mov x8, #EXIT                 // request to exit program
    svc #0                        // perform the system call
qAdrszCarriageReturn:        .quad szCarriageReturn
/***************************************************/
/*   display message number                        */
/***************************************************/
/* x0 contains the number            */
displayResult:
    stp x1,lr,[sp,-16]!      // save  registres
    ldr x1,qAdrsZoneConv
    bl conversion10          // call décimal conversion
    strb wzr,[x1,x0]
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv     // insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess         // display message
    ldp x1,lr,[sp],16        // restaur des  2 registres
    ret
qAdrsMessResult:     .quad sMessResult
qAdrsZoneConv:       .quad sZoneConv
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


CARD FUNC DivisorCount(CARD n)
  CARD result,p,count

  result=1
  WHILE (n&1)=0
  DO
    result==+1
    n=n RSH 1
  OD

  p=3
  WHILE p*p<=n
  DO
    count=1
    WHILE n MOD p=0
    DO
      count==+1
      n==/p
    OD
    result==*count
    p==+2
  OD

  IF n>1 THEN
    result==*2
  FI
RETURN (result)

PROC Main()
  CARD max=[100],n,divCount

  PrintF("Tau function for the first %U numbers%E",max)
  FOR n=1 TO max
  DO
    divCount=DivisorCount(n)
    PrintC(divCount) Put(32)
  OD
RETURN


BEGIN # find the count of the divisors of the first 100 positive integers   #
    # calculates the number of divisors of v                                #
    PROC divisor count = ( INT v )INT:
         BEGIN
            INT total := 1, n := v;
            # Deal with powers of 2 first #
            WHILE NOT ODD n DO
                total +:= 1;
                n OVERAB 2
            OD;
            # Odd prime factors up to the square root #
            FOR p FROM 3 BY 2 WHILE ( p * p ) <= n DO
                INT count := 1;
                WHILE n MOD p = 0 DO
                    count +:= 1;
                    n OVERAB p
                OD;
                total *:= count
            OD;
            # If n > 1 then it's prime #
            IF n > 1 THEN total *:= 2 FI;
            total
         END # divisor_count # ;
    BEGIN
        INT limit = 100;
        print( ( "Count of divisors for the first ", whole( limit, 0 ), " positive integers:" ) );
        FOR n TO limit DO
            IF n MOD 20 = 1 THEN print( ( newline ) ) FI;
            print( ( whole( divisor count( n ), -4 ) ) )
        OD
    END
END


begin % find the count of the divisors of the first 100 positive integers   %
    % calculates the number of divisors of v                                %
    integer procedure divisor_count( integer value v ) ; begin
        integer total, n, p;
        total := 1; n := v;
        % Deal with powers of 2 first %
        while not odd( n ) do begin
            total := total + 1;
            n     := n div 2
        end while_not_odd_n ;
        % Odd prime factors up to the square root %
        p := 3;
        while ( p * p ) <= n do begin
            integer count;
            count := 1;
            while n rem p = 0 do begin
                count := count + 1;
                n     := n div p
            end while_n_rem_p_eq_0 ;
            p     := p + 2;
            total := total * count
        end while_p_x_p_le_n ;
        % If n > 1 then it is prime %
        if n > 1 then total := total * 2;
        total
    end divisor_count ;
    begin
        integer limit;
        limit := 100;
        write( i_w := 1, s_w := 0, "Count of divisors for the first ", limit, " positive integers:" );
        for n := 1 until limit do begin
            if n rem 20 = 1 then write();
            writeon( i_w := 3, s_w := 1, divisor_count( n ) )
        end for_n
    end
end.