my @board = 1..9;
my @winning-positions = [0..2], [3..5], [6..8], [0,3,6], [1,4,7], [2,5,8],
	[0,4,8], [6,4,2];

sub get-winner() {
	for @winning-positions {
        return (@board[|$_][0], $_) if [eq] @board[|$_];
	}
}

sub free-indexes() {
	@board.keys.grep: { @board[$_] eq any(1..9) }
}

sub ai-move() {
	given free-indexes.pick {
		@board[$_] = 'o';
		say "I go at: { $_ + 1 }\n";
	}
}

sub print-board() {
    print "\e[2J";
    say @board.map({ "$^a | $^b | $^c" }).join("\n--+---+--\n"), "\n";
}

sub human-move() {
	my $pos = prompt "Choose one of { (free-indexes() »+» 1).join(",") }: ";
	if $pos eq any(free-indexes() »+» 1) {
		@board[$pos - 1] = 'x';
	} else {
		say "Sorry, you want to put your 'x' where?";
		human-move();
	}
}

for flat (&ai-move, &human-move) xx * {
	print-board;
    last if get-winner() or not free-indexes;
    .();
}

if get-winner() -> ($player, $across) {
	say "$player wins across [", ($across »+» 1).join(", "), "].";
} else {
	say "How boring, a draw!";
}


/*REXX program plays  (with a human)  the     tic─tac─toe     game  on an   NxN   grid. */
$= copies('─', 9)                                /*eyecatcher for error messages, prompt*/
oops   = $  '***error*** '                       /*literal for when an error happens.   */
single = '│─┼';    jam= "║";    bar= '═';     junc= "╬";         dbl=jam || bar || junc
sw     = linesize() - 1                          /*obtain width of the terminal (less 1)*/
parse arg N hm cm .,@.                           /*obtain optional arguments from the CL*/
if N=='' | N==","  then N=3;   oN=N              /*N  not specified?   Then use default.*/
     N = abs(N)                                  /*if N < 0.  then computer goes first. */
    NN = N*N                                     /*calculate the   square of  N.        */
middle = NN % 2   +   N % 2                      /*    "      "    middle  "  the grid. */
if N<2  then do;  say oops  'tic─tac─toe grid is too small: '    N;     exit 13;    end
pad= left('', sw % NN)                           /*display padding:  6x6  in 80 columns.*/
if hm==''  then hm= "X";                         /*define the marker for  a   human.    */
if cm==''  then cm= "O"                          /*   "    "     "    "  the  computer. */
                hm= aChar(hm, 'human')           /*determine if the marker is legitimate*/
                cm= aChar(cm, 'computer')        /*    "      "  "     "    "      "    */
parse upper value  hm  cm     with     uh  uc    /*use uppercase values is markers:  X x*/
if uh==uc  then cm= word('O X', 1 + (uh=="O") )  /*The human wants Hal's marker?  Swap. */
if oN<0  then call Hmove middle                  /*Hal moves first? Then choose middling*/
         else call showGrid                      /*showGrid also checks for wins & draws*/

/*tic─tac─toe game───►*/     do  forever         /*'til the cows come home  (or  QUIT). */
/*tic─tac─toe game───►*/     call CBLF           /*process carbon─based lifeform's move.*/
/*tic─tac─toe game───►*/     call Hal            /*determine Hal's  (the computer) move.*/
/*tic─tac─toe game───►*/     end   /*forever*/   /*showGrid subroutine does wins & draws*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
aChar: parse arg x,whoseX;  L=length(x)                               /*process markers.*/
       if L==1                        then return testB(     x  )     /*1 char,  as is. */
       if L==2 & datatype(x, 'X')     then return testB( x2c(x) )     /*2 chars, hex.   */
       if L==3 & datatype(x, 'W') & ,                                 /*3 chars, decimal*/
          x>=0 & x<256                then return testB( d2c(x) )     /*···and in range.*/
       say oops  'illegal character or character code for'    whoseX    "marker: "    x
       exit 13                                   /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
CBLF:  prompt='Please enter a cell number to place your next marker ['hm"]     (or Quit):"

         do forever;                 say $ prompt
         parse pull  x 1 ux 1 ox;    upper ux    /*get versions of answer;  uppercase ux*/
         if datatype(ox, 'W')  then ox=ox / 1    /*normalize cell number:  +0007 ───► 7 */
                                                 /*(division by unity normalizes a num.)*/
           select                                /*perform some validations of X (cell#)*/
           when abbrev('QUIT',ux,1)  then call tell 'quitting.'
           when x=''                 then iterate                    /*Nada?  Try again.*/
           when words(x)\==1         then say oops "too many" cell#  'specified:'   x
           when \datatype(x, 'N')    then say oops "cell number isn't numeric: "        x
           when \datatype(x, 'W')    then say oops "cell number isn't an integer: "     x
           when x=0                  then say oops "cell number can't be zero: "        x
           when x<0                  then say oops "cell number can't be negative: "    x
           when x>NN                 then say oops "cell number can't exceed "          NN
           when @.ox\==''            then say oops "cell number is already occupied: "  x
           otherwise                 leave  /*forever*/
           end   /*select*/

         end     /*forever*/
                                                 /* [↓]  OX is a normalized version of X*/
       @.ox= hm                                  /*place a marker for the human (CLBF). */
       call showGrid                             /*and display the  tic─tac─toe  grid.  */
       return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Hal:           select                                        /*Hal tries various moves. */
               when win(cm, N-1)   then call Hmove , ec      /*is this the winning move?*/
               when win(hm, N-1)   then call Hmove , ec      /* "   "   a blocking   "  */
               when @.middle== ''  then call Hmove middle    /*pick the  center  cell.  */
               when @.N.N  ==  ''  then call Hmove , N N     /*bottom right corner cell.*/
               when @.N.1  ==  ''  then call Hmove , N 1     /*   "    left    "     "  */
               when @.1.N  ==  ''  then call Hmove , 1 N     /*  top  right    "     "  */
               when @.1.1  ==  ''  then call Hmove , 1 1     /*   "    left    "     "  */
               otherwise                call Hmove , ac      /*pick a blank cell in grid*/
               end   /*select*/
       return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Hmove: parse arg Hplace,dr dc;     if Hplace==''  then Hplace = (dr - 1)*N    +  dc
       @.Hplace= cm                                          /*place computer's marker. */
       say;  say  $   'computer places a marker  ['cm"]  at cell number  "    Hplace
       call showGrid
       return
/*──────────────────────────────────────────────────────────────────────────────────────*/
showGrid: _= 0;              cW= 5;     cH= 3;       open= 0 /*cell width,  cell height.*/
           do   r=1  for N                                   /*construct array of cells.*/
             do c=1  for N;  _= _ + 1;  @.r.c= @._;  open= open  |  @._==''
             end   /*c*/
           end     /*r*/                                     /* [↑]  OPEN≡a cell is open*/
       say                                                   /* [↑]  create grid coörds.*/
       z= 0;         do     j=1  for  N                      /* [↓]  show grids&markers.*/
                       do   t=1  for cH;    _=;  __=         /*MK is a marker in a cell.*/
                         do k=1  for  N;    if t==2  then z= z + 1;        mk=;     c#=
                         if t==2  then do;  mk= @.z;      c#= z      /*c# is cell number*/
                                       end
                          _= _   ||  jam  ||  center(mk, cW)
                         __= __  ||  jam  ||  center(c#, cW)
                         end   /*k*/
                       say pad  substr(_, 2)  pad  translate( substr(__, 2),  single, dbl)
                       end     /*t*/                                 /* [↑]  show a line*/
                     if j==N  then leave
                     _=
                        do b=1  for  N;       _= _  ||  junc  ||  copies(bar, cW)
                        end   /*b*/                                  /* [↑]  a grid part*/
                     say   pad  substr(_, 2)  pad  translate( substr(_,  2),  single, dbl)
                     end        /*j*/
       say
       if win(hm)  then  call tell  'You  ('hm")  won"copies('!',random(1, 5) )
       if win(cm)  then  call tell  'The computer  ('cm")  won."
       if \open    then  call tell  'This tic─tac─toe game is a draw   (a cat scratch).'
       return
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell:  do 4; say; end;     say center(' 'arg(1)" ", sw, '─');      do 5; say; end;    exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
testB: parse arg bx; if bx\==' '  then return bx /*test if the  marker  isn't  a  blank.*/
       say oops   'character code for'      whoseX      "marker can't be a blank."
       exit 13                                   /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
win:   parse arg wm,w;        if w==''  then w= N        /* [↓]  see if there is a win. */
       ac=                                               /* [↓]  EC ≡ means Empty Cell. */
            do   r=1  for N;  _= 0;  ec=                 /*see if any  rows are a winner*/
              do c=1  for N;  _= _ + (@.r.c==wm)         /*count the # of markers in col*/
              if @.r.c==''              then ec= r c     /*Cell empty?  Then remember it*/
              end   /*c*/                                /* [↓]  AC≡means available cell*/
            if ec\==''                  then ac=ec       /*Found an empty?  Then use it.*/
            if _==N | (_>=w & ec\=='')  then return 1==1 /*a winner has been determined.*/
            end     /*r*/                                /*w=N-1?  Checking for near win*/

            do   c=1  for N;  _= 0;  ec=                 /*see if any  cols are a winner*/
              do r=1  for N;  _= _ + (@.r.c==wm)         /*count the # of markers in row*/
              if @.r.c==''              then ec= r c     /*Cell empty?  Then remember it*/
              end   /*r*/
            if ec\==''                  then ac= ec      /*Found an empty? Then remember*/
            if _==N | (_>=w & ec\=='')  then return 1==1 /*a winner has been determined.*/
            end     /*c*/
                              _= 0;  ec=                 /*EC≡location of an empty cell.*/
            do d=1  for N;    _= _ + (@.d.d==wm)         /*A winning descending diag. ? */
            if @.d.d==''                then ec= d d     /*Empty cell?  Then note cell #*/
            end     /*d*/

       if _==N  |  (_>=w  &  ec\=='')   then return 1==1 /*a winner has been determined.*/
                              _= 0;  r= 1
            do c=N  for N  by -1;   _=_ + (@.r.c==wm)    /*A winning ascending diagonal?*/
            if @.r.c==''                then ec= r c     /*Empty cell?  Then note cell #*/
            r= r + 1                                     /*bump the counter for the rows*/
            end     /*c*/

       if _==N  |  (_>=w  &  ec\=='')   then return 1==1 /*a winner has been determined.*/
       return 0==1                                       /*no winner "    "       "     */


Load "guilib.ring"

#Provide a list to save each button status in numeric readable format
#0=nothing 1=X 2=O
lst=[]

#Provide onScreen button status and style
btns=[]

#Define who has the turn
isXTurn=true

    app=new qApp
    {

        frmMain=new qMainWindow()
		{
			setWindowTitle("TicTacToe!")
			resize(300,320)
			move(200,200)
			//buttons
			pos=0
			for y=0 to 2
				for x=0 to 2
				//Creating Buttons on the screen
					pos++
					Add(lst,0)
					Add(btns,new qPushButton(frmMain)
						{
							setGeometry(x*100,y*100,100,100)
							setText("-")
							setclickevent("Disp(" + pos +")")
							setstylesheet("font-size:24pt ; font: bold ; color:yellow ; background-color: green")
						})
				next
            next
			//StatusBar
			status=new qStatusBar(frmMain)
			{
                showMessage("Ready",0)
            }
			setwindowflags(Qt_dialog)
			setStatusbar(status)
			show()
        }
		exec()
	}

//Restart the game by re init buttons status
func reStart
    for i=1 to 9
        lst[i]=0
        btns[i].setText("-")
    next
isXTurn=true

func Disp x
    if isXTurn=true and lst[x]=0
		btns[x].setText("X")
		lst[x]=1
		isXTurn=false
	but isXTurn=false and lst[x]=0
        btns[x].setText("O")
        lst[x]=2
        isXTurn=true
    ok

	winner = CheckWinner()
	#if there is no Winner and still there is ability to winner
	#continue playing.
	if winner<1 return ok

	//Who is the winner!
    switch winner
        on 1
            new qMessagebox(frmMain)
            {
				SetWindowTitle("We have a winner!")
                SetText("Good job X you won!")
                show()
            }
        on 2
			new qMessagebox(frmMain)
            {
				SetWindowTitle("We have a winner!")
                SetText("Good job O you won!")
                show()
            }
        on 3
            new qMessagebox(frmMain)
            {
                SetWindowTitle("Oh no it's a tie")
                SetText("Oh no it's a tie!")
                show()
            }
    off
    reStart()

func CheckWinner
        //vertical check
        for v=1 to 9 step 3
            if lst[v]!=0 and lst[v+1]!=0 and lst[v+2]!=0
				if lst[v]=lst[v+1] and lst[v+1]=lst[v+2]
                    return lst[v]
                ok
            ok
        next
        //horzintal
        for h=1 to 3
            if lst[h]!=0 and lst[h+3]!=0 and lst[h+6]!=0
                if lst[h]=lst[h+3] and lst[h+3]=lst[h+6]
                    return lst[h]
                ok
            ok
        next
        //Cross
        if lst[1]!=0 and lst[5]!=0 and lst[9]!=0
            if lst[1]=lst[5] and lst[5]=lst[9] return lst[1] ok
        ok
        if lst[3]!=0 and lst[5]!=0 and lst[7]!=0
            if lst[3]=lst[5] and lst[5]=lst[7] return lst[3] ok
        ok
        //tie
        tie=true
        for i=1 to 9
            if lst[i]=0 tie=false exit ok
        next
        if tie=true return 3 ok return 0


*        Temperature conversion    10/09/2015
TEMPERAT CSECT
         USING  TEMPERAT,R15
         LA     R4,1               i=1
         LA     R5,TT              @tt(1)
         LA     R6,IDE             @ide(1)
LOOPI    CH     R4,=AL2((T-TT)/8)  do i=1 to hbound(tt)
         BH     ELOOPI
         ZAP    T,0(8,R5)          t=tt(i)
         CVD    R4,DW              store to packed decimal
         UNPK   PG(1),DW+7(1)      unpack
         OI     PG,X'F0'           zap sign
         MVI    PG+1,C' '
         MVC    PG+2(12),0(R6)     ide(i)
         XPRNT  PG,14              output i
         MVC    PG(12),=C'Kelvin:     '
         MVC    ZN,EDMASKN         load mask
         EDMK   ZN,T+5             t (PL3)
         BCTR   R1,0               sign location
         MVC    0(1,R1),ZN+L'ZN-1  put sign
         MVC    PG+12(L'ZN-1),ZN   value
         MVC    PG+19(2),=C' K'    unit
         XPRNT  PG,21              output Kelvin
         MVC    PG(12),=C'Celsius:    '
         ZAP    DW,T               t
         SP     DW,=P'273.15'      t-273.15
         MVC    ZN,EDMASKN         load mask
         EDMK   ZN,DW+5            (PL3)
         BCTR   R1,0               sign location
         MVC    0(1,R1),ZN+L'ZN-1  put sign
         MVC    PG+12(L'ZN-1),ZN   value
         MVC    PG+19(2),=C' C'    unit
         XPRNT  PG,21              output Celsius
         MVC    PG(12),=C'Fahrenheit: '
         ZAP    DW,T               t
         MP     DW,=P'18'          *18
         DP     DW,=PL3'10'        /10
         ZAP    DW,DW(5)
         SP     DW,=P'459.67'      t*1.8-459.67
         MVC    ZN,EDMASKN         load mask
         EDMK   ZN,DW+5            (PL3)
         BCTR   R1,0               sign location
         MVC    0(1,R1),ZN+L'ZN-1  put sign
         MVC    PG+12(L'ZN-1),ZN   value
         MVC    PG+19(2),=C' F'    unit
         XPRNT  PG,21              output Fahrenheit
         MVC    PG(12),=C'Rankine:    '
         ZAP    DW,T               t
         MP     DW,=P'18'          *18
         DP     DW,=PL3'10'        /10
         ZAP    DW,DW(5)           t*1.8
         MVC    ZN,EDMASKN         load mask
         EDMK   ZN,DW+5            (PL3)
         BCTR   R1,0               sign location
         MVC    0(1,R1),ZN+L'ZN-1  put sign
         MVC    PG+12(L'ZN-1),ZN   value
         MVC    PG+19(2),=C' R'    unit
         XPRNT  PG,21              output Rankine
         LA     R4,1(R4)           i=i+1
         LA     R5,8(R5)           @tt(i)
         LA     R6,12(R6)          @ide(i)
         B      LOOPI
ELOOPI   XR     R15,R15
         BR     R14
IDE      DC     CL12'absolute',CL12'ice melts',CL12'water boils'
TT       DC     PL8'0.00',PL8'273.15',PL8'373.15'
T        DS     PL8
PG       DS     CL24
ZN       DS     ZL8                5num
DW       DS     D                  PL8 15num
EDMASKN  DC     X'402021204B202060'     CL8 5num
         YREGS
         END    TEMPERAT


: KtoC \ n -- n
    273.15 n:-
;

: KtoF \ n -- n
    1.8 n:* 459.67 n:-
;

: KtoR \ n -- n
    1.8 n:*
;

: KtoCFR \ n --
    dup dup dup
    . " degrees Kelvin" . cr
    KtoC
    . " degrees Celcius" . cr
    KtoF
    . " degrees Fahrenheit" . cr
    KtoR
    . " degrees Rankine" . cr
;

: app:main \
    argc 0 n:=
    if
        "Syntax" . cr "    temp.8th number" . cr
    else
        0 args >n KtoCFR
    then
    bye
;


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

PROC K2C(REAL POINTER k,c)
  REAL tmp

  ValR("273.15",tmp)
  RealSub(k,tmp,c)
RETURN

PROC K2F(REAL POINTER k,f)
  REAL tmp1,tmp2,tmp3

  ValR("1.8",tmp1)
  ValR("459.67",tmp2)
  RealMult(k,tmp1,tmp3)
  RealSub(tmp3,tmp2,f)
RETURN

PROC K2R(REAL POINTER k,f)
  REAL tmp

  ValR("1.8",tmp)
  RealMult(k,tmp,f)
RETURN

PROC Test(CHAR ARRAY text REAL POINTER k)
  REAL res

  PrintE(text)
  Print("      Kelvin: ") PrintRE(k)

  K2C(k,res)
  Print("     Celsius: ") PrintRE(res)

  K2F(k,res)
  Print("  Fahrenheit: ") PrintRE(res)

  K2R(k,res)
  Print("     Rankine: ") PrintRE(res)

  PutE()
RETURN

PROC Main()
  REAL k

  Put(125) PutE() ;clear screen

  ValR("0",k) Test("Absolute zero",k)
  ValR("273.15",k) Test("Ice melts",k)
  ValR("373.15",k) Test("Water boils",k)
RETURN


module TicTacToe
  LINES = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]

  class Game
    def initialize(player_1_class, player_2_class)
      @board = Array.new(10) # we ignore index 0 for convenience

      @current_player_id = 0
      @players = [player_1_class.new(self, "X"), player_2_class.new(self, "O")]
      puts "#{current_player} goes first."
    end
    attr_reader :board, :current_player_id

    def play
      loop do
        place_player_marker(current_player)

        if player_has_won?(current_player)
          puts "#{current_player} wins!"
          print_board
          return
        elsif board_full?
          puts "It's a draw."
          print_board
          return
        end

        switch_players!
      end
    end

    def free_positions
      (1..9).select {|position| @board[position].nil?}
    end

    def place_player_marker(player)
      position = player.select_position!
      puts "#{player} selects #{player.marker} position #{position}"
      @board[position] = player.marker
    end

    def player_has_won?(player)
      LINES.any? do |line|
        line.all? {|position| @board[position] == player.marker}
      end
    end

    def board_full?
      free_positions.empty?
    end

    def other_player_id
      1 - @current_player_id
    end

    def switch_players!
      @current_player_id = other_player_id
    end

    def current_player
      @players[current_player_id]
    end

    def opponent
      @players[other_player_id]
    end

    def turn_num
      10 - free_positions.size
    end

    def print_board
      col_separator, row_separator = " | ", "--+---+--"
      label_for_position = lambda{|position| @board[position] ? @board[position] : position}

      row_for_display = lambda{|row| row.map(&label_for_position).join(col_separator)}
      row_positions = [[1,2,3], [4,5,6], [7,8,9]]
      rows_for_display = row_positions.map(&row_for_display)
      puts rows_for_display.join("\n" + row_separator + "\n")
    end
  end

  class Player
    def initialize(game, marker)
      @game = game
      @marker = marker
    end
    attr_reader :marker
  end

  class HumanPlayer < Player
    def select_position!
      @game.print_board
      loop do
        print "Select your #{marker} position: "
        selection = gets.to_i
        return selection if @game.free_positions.include?(selection)
        puts "Position #{selection} is not available. Try again."
      end
    end

    def to_s
      "Human"
    end
  end

  class ComputerPlayer < Player
    DEBUG = false # edit this line if necessary

    def group_positions_by_markers(line)
      markers = line.group_by {|position| @game.board[position]}
      markers.default = []
      markers
    end

    def select_position!
      opponent_marker = @game.opponent.marker

      winning_or_blocking_position = look_for_winning_or_blocking_position(opponent_marker)
      return winning_or_blocking_position if winning_or_blocking_position

      if corner_trap_defense_needed?
        return corner_trap_defense_position(opponent_marker)
      end

      # could make this smarter by sometimes doing corner trap offense

      return random_prioritized_position
    end

    def look_for_winning_or_blocking_position(opponent_marker)
      for line in LINES
        markers = group_positions_by_markers(line)
        next if markers[nil].length != 1
        if markers[self.marker].length == 2
          log_debug "winning on line #{line.join}"
          return markers[nil].first
        elsif markers[opponent_marker].length == 2
          log_debug "could block on line #{line.join}"
          blocking_position = markers[nil].first
        end
      end
      if blocking_position
        log_debug "blocking at #{blocking_position}"
        return blocking_position
      end
    end

    def corner_trap_defense_needed?
      corner_positions = [1, 3, 7, 9]
      opponent_chose_a_corner = corner_positions.any?{|pos| @game.board[pos] != nil}
      return @game.turn_num == 2 && opponent_chose_a_corner
    end

    def corner_trap_defense_position(opponent_marker)
      # if you respond in the center or the opposite corner, the opponent can force you to lose
      log_debug "defending against corner start by playing adjacent"
      # playing in an adjacent corner could also be safe, but would require more logic later on
      opponent_position = @game.board.find_index {|marker| marker == opponent_marker}
      safe_responses = {1=>[2,4], 3=>[2,6], 7=>[4,8], 9=>[6,8]}
      return safe_responses[opponent_position].sample
    end

    def random_prioritized_position
      log_debug "picking random position, favoring center and then corners"
      ([5] + [1,3,7,9].shuffle + [2,4,6,8].shuffle).find do |pos|
        @game.free_positions.include?(pos)
      end
    end

    def log_debug(message)
      puts "#{self}: #{message}" if DEBUG
    end

    def to_s
      "Computer#{@game.current_player_id}"
    end
  end
end

include TicTacToe

Game.new(ComputerPlayer, ComputerPlayer).play
puts
players_with_human = [HumanPlayer, ComputerPlayer].shuffle
Game.new(*players_with_human).play


with Ada.Float_Text_IO, Ada.Text_IO;  use Ada.Float_Text_IO, Ada.Text_IO;

procedure Temperatur_Conversion is
   K: Float;
   function C return Float is (K - 273.15);
   function F return Float is (K * 1.8 - 459.67);
   function R return Float is (K * 1.8);
begin
   Get(K); New_Line;                                           -- Format
   Put("K: "); Put(K, Fore => 4, Aft => 2, Exp => 0); New_Line;-- K: dddd.dd
   Put("C: "); Put(C, Fore => 4, Aft => 2, Exp => 0); New_Line;-- C: dddd.dd
   Put("F: "); Put(F, Fore => 4, Aft => 2, Exp => 0); New_Line;-- F: dddd.dd
   Put("R: "); Put(R, Fore => 4, Aft => 2, Exp => 0); New_Line;-- R: dddd.dd
end;


void
show(integer symbol, real temperature)
{
    o_form("%c /d2p2w8/\n", symbol, temperature);
}

integer
main(void)
{
    real k;

    k = atof(argv(1));

    show('K', k);
    show('C', k - 273.15);
    show('F', k * 1.8 - 459.67);
    show('R', k * 1.8);

    return 0;
}


' ---------------------------
'  TIC TAC TOE
' ---------------------------
winBox$ = "123 456 789 159 147 258 369 357"
boxPos$ = "123 231 456 564 789 897 159 591 357 753 132 465 798 174 285 396 159 471 582 693 147 258 369 195 375"
ai$     = "519628374"
ox$     = "OX"
[newGame]
for i = 1 to 9
 box$(i) = ""
next i
goto [shoTic]

[loop]
for j = 1 to 2
 tic$ = mid$(ox$,j,1)
 for i = 1 to 25
  b$	= word$(boxPos$,i," ")
  b1	= val(mid$(b$,1,1))
  b2	= val(mid$(b$,2,1))
  b3	= val(mid$(b$,3,1))
  if box$(b1) = tic$ AND box$(b2) = tic$ AND box$(b3) = "" then
     box$(b3)  = "O"
     goto [shoTic]
 end if
 next i
next j
if box$(1) = "O" AND box$(5) = "X" and box$(9) = "X" then
 if box$(3) = "" then
   box$(3) = "O"
   goto [shoTic]
 end if
 if box$(7) = "" then
   box$(7) = "O"
   goto [shoTic]
 end if
end if
for i = 1 to 9
 b1 = val(mid$(ai$,i,1))
 if box$(b1) = "" then
   box$(b1)  = "O"
   exit for
 end if
next i

[shoTic]
cls
' ----------------------------------------
' show tic tac toe screen
' ----------------------------------------
html "

"
for i = 1 to 9
  html "
"
    if box$(i) <> "" then
     html box$(i)
    else
    button #box, " ";box$(i);" ", [doTic]
           #box  setkey(str$(i))
    end if
    if i mod 3 = 0 then html "

"
next i
html "
"
gosub [checkWin]
wait

[doTic]
box$(val(EventKey$)) = "X"
turn          = 1
gosub [checkWin]
goto [loop]

' --- check for a winner ----------
[checkWin]
for i = 1 to 8
 b$ = word$(winBox$,i," ")
 b1 = val(mid$(b$,1,1))
 b2 = val(mid$(b$,2,1))
 b3 = val(mid$(b$,3,1))
 if box$(b1) = "O" and box$(b2) = "O" and box$(b3) = "O" then
   print "You Lose!"
   goto [playAgain]
 end if
 if box$(b1) = "X" and box$(b2) = "X" and box$(b3) = "X" then
   print "You Win!"
   goto [playAgain]
 end if
next i

moveCount = 0
for i = 1 to 9
 if box$(i) <> "" then moveCount = moveCount + 1
next i
if moveCount = 9 then
  print "Draw!"
  goto [playAgain]
end if
RETURN

[playAgain]
input "Play again (y/n)";p$
if upper$(p$) = "Y" then goto [newGame]
end


BEGIN
   REAL kelvin;
   read (kelvin);
   FORMAT f = $g(8,2), " K = ", g(8,2)xgl$;
   printf ((f, kelvin, kelvin - 273.15, "C"));
   printf ((f, kelvin, 9.0 * kelvin / 5.0, "R"));
   printf ((f, kelvin, 9.0 * kelvin / 5.0 - 459.67, "F"))
END


BEGIN
    DECIMAL K, C, F, R;
    WRITE( "Temperature in Kelvin:" );
    READ( K );
    C := K - 273.15;
    F := K * 1.8 - 459.67;
    R := K * 1.8;
    WRITE( K, " Kelvin is equivalent to" );
    WRITE( C, " degrees Celsius" );
    WRITE( F, " degrees Fahrenheit" );
    WRITE( R, " degrees Rankine" );
END


use GameState::{ComputerWin, Draw, PlayerWin, Playing};

use rand::prelude::*;

#[derive(PartialEq, Debug)]
enum GameState {
    PlayerWin,
    ComputerWin,
    Draw,
    Playing,
}

type Board = [[char; 3]; 3];

fn main() {
    let mut rng = StdRng::from_entropy();

    let mut board: Board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']];

    draw_board(board);
    loop {
        player_turn(&mut board);
        if check_win(board) != Playing {
            break;
        }
        computer_turn(&mut rng, &mut board);
        if check_win(board) != Playing {
            break;
        }
        draw_board(board);
    }

    draw_board(board);
    let announcement = match check_win(board) {
        PlayerWin => "The Player has won!",
        ComputerWin => "The Computer has won!",
        Draw => "Draw!",
        Playing => unreachable!(),
    };
    println!("{}", announcement);
}

fn is_empty(cell: &char) -> bool {
    *cell != 'X' && *cell != 'O'
}

fn check_win(board: Board) -> GameState {
    // check for win
    for (i, row) in board.iter().enumerate() {
        if row[0] == row[1] && row[0] == row[2] {
            return which_win(row[0]);
        } else if board[0][i] == board[1][i] && board[0][i] == board[2][i] {
            return which_win(board[0][i]);
        }
    }
    if board[0][0] == board[1][1] && board[0][0] == board[2][2] {
        return which_win(board[0][0]);
    } else if board[0][2] == board[1][1] && board[0][2] == board[2][0] {
        return which_win(board[0][2]);
    }

    // check if it's not a draw
    let is_draw = board.iter().flatten().any(is_empty);
    if is_draw {
        Playing
    } else {
        Draw
    }
}

fn which_win(s: char) -> GameState {
    match s {
        'X' => PlayerWin,
        'O' => ComputerWin,
        _ => unreachable!(),
    }
}

fn player_turn(board: &mut Board) {
    use std::io;

    println!("Player, enter your field of choice!: ");
    let mut ln = String::new();
    io::stdin()
        .read_line(&mut ln)
        .expect("Failed to read stdin");
    let choice = ln.trim().parse::<usize>().expect("Failed to parse input");
    let row = (choice - 1) / 3;
    let col = (choice - 1) % 3;

    if board[row][col] == 'X' || board[row][col] == 'O' {
        println!("Someone already took this field!");
        player_turn(board);
    } else {
        board[row][col] = 'X';
    }
}

fn computer_turn<R: Rng>(rng: &mut R, board: &mut Board) {
    let possible_choices: Vec<_> = board
        .iter()
        .flatten()
        .enumerate()
        .filter(|&(_, c)| is_empty(c))
        .map(|(i, _)| i)
        .collect();

    let choice = possible_choices.choose(rng).unwrap();
    println!("Computer chose: {}", choice);
    let row = choice / 3;
    let col = choice % 3;
    board[row][col] = 'O';
}

fn draw_board(board: Board) {
    for row in &board {
        println!("{} {} {}", row[0], row[1], row[2]);
    }
}


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

F is_tau_number(n)
   I n <= 0
      R 0B
   R 0 == n % tau(n)

V n = 1
[Int] ans
L ans.len < 100
   I is_tau_number(n)
      ans.append(n)
   n++
print(ans)


/* MISTRAL - a flavour of Hopper */

#include <mistral.h>

INICIAR:
   TAMAÑO DE MEMORIA 20
   temperatura=0
   RECIBIR PARÁMETRO NUMÉRICO(2), GUARDAR EN (temperatura);
   TOMAR("KELVIN     : ",temperatura, NL)
   CON( "CELSIUS    : ", temperatura ), CALCULAR( Conversión Kelvin a Celsius ),    NUEVA LÍNEA
   CON( "FAHRENHEIT : ", temperatura ), CALCULAR( Conversión Kelvin a Fahrenheit ), NUEVA LÍNEA
   CON( "RANKINE    : ", temperatura ), CALCULAR( Conversión Kelvin a Rankine ),    NUEVA LÍNEA
   IMPRIMIR CON SALTO
FINALIZAR

SUBRUTINAS

FUNCIÓN(Conversión Kelvin a Celsius, k)
    REDONDEAR(RESTAR(k, 273.15), 2)
RETORNAR

FUNCIÓN( Conversión Kelvin a Fahrenheit, k)
    REDONDEAR( {k} MULTIPLICADO POR(1.8) MENOS( 459.67), 2)
RETORNAR

FUNCIÓN( Conversión Kelvin a Rankine, k)
RETORNAR ( {k} POR (1.8), REDONDEADO AL DECIMAL(2) )


use framework "Foundation" -- Yosemite onwards, for the toLowerCase() function

-- KELVIN TO OTHER SCALE -----------------------------------------------------

-- kelvinAs :: ScaleName -> Num -> Num
on kelvinAs(strOtherScale, n)
    heatBabel(n, "Kelvin", strOtherScale)
end kelvinAs

-- MORE GENERAL CONVERSION ---------------------------------------------------

-- heatBabel :: n -> ScaleName -> ScaleName -> Num
on heatBabel(n, strFromScale, strToScale)
    set ratio to 9 / 5
    set cels to 273.15
    set fahr to 459.67

    script reading
        on |λ|(x, strFrom)
            if strFrom = "k" then
                x as real
            else if strFrom = "c" then
                x + cels
            else if strFrom = "f" then
                (fahr + x) * ratio
            else
                x / ratio
            end if
        end |λ|
    end script

    script writing
        on |λ|(x, strTo)
            if strTo = "k" then
                x
            else if strTo = "c" then
                x - cels
            else if strTo = "f" then
                (x * ratio) - fahr
            else
                x * ratio
            end if
        end |λ|
    end script

    writing's |λ|(reading's |λ|(n, ¬
        toLower(text 1 of strFromScale)), ¬
        toLower(text 1 of strToScale))
end heatBabel

-- TEST ----------------------------------------------------------------------
on kelvinTranslations(n)
    script translations
        on |λ|(x)
            {x, kelvinAs(x, n)}
        end |λ|
    end script

    map(translations, {"K", "C", "F", "R"})
end kelvinTranslations

on run
    script tabbed
        on |λ|(x)
            intercalate(tab, x)
        end |λ|
    end script

    intercalate(linefeed, map(tabbed, kelvinTranslations(21)))
end run

-- GENERIC FUNCTIONS ---------------------------------------------------------

-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    return strJoined
end intercalate

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- toLower :: String -> String
on toLower(str)
    set ca to current application
    ((ca's NSString's stringWithString:(str))'s ¬
        lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower


package object tictactoe {
  val Human = 'X'
  val Computer = 'O'
  val BaseBoard = ('1' to '9').toList
  val WinnerLines = List((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))
  val randomGen = new util.Random(System.currentTimeMillis)
}

package tictactoe {

class Board(aBoard : List[Char] = BaseBoard) {

  def availableMoves = aBoard.filter(c => c != Human && c != Computer)

  def availableMovesIdxs = for ((c,i) <- aBoard.zipWithIndex if c != Human && c != Computer) yield i

  def computerPlays = new Board(aBoard.updated(availableMovesIdxs(randomGen.nextInt(availableMovesIdxs.length)), Computer))

  def humanPlays(move : Char) = new Board(aBoard.updated(aBoard.indexOf(move), Human))

  def isDraw = aBoard.forall(c => c == Human || c == Computer)

  def isWinner(winner : Char) =
    WinnerLines.exists{case (i,j,k) => aBoard(i) == winner && aBoard(j) == winner && aBoard(k) == winner}

  def isOver = isWinner(Computer) || isWinner(Human) || isDraw

  def print {
    aBoard.grouped(3).foreach(row => println(row(0) + " " + row(1) + " " + row(2)))
  }

  def printOverMessage {
    if (isWinner(Human)) println("You win.")
    else if (isWinner(Computer)) println("Computer wins.")
    else if (isDraw) println("It's a draw.")
    else println("Not over yet, or something went wrong.")
  }

}

object TicTacToe extends App {

   def play(board : Board, turn : Char) {

    // Reads a char from input until it is one of
    // the available moves in the current board
    def readValidMove() : Char = {
      print("Choose a move: ")
      val validMoves = board.availableMoves
      val move = readChar
      if (validMoves.contains(move)) {
        move
      } else {
        println("Invalid move. Choose another one in " + validMoves)
        readValidMove()
      }
    }

    board.print

    if (board.isOver) {
      board.printOverMessage
      return
    }

    if (turn == Human) { // Human plays
      val nextBoard = board.humanPlays(readValidMove)
      play(nextBoard, Computer)
    } else { // Computer plays
      println("Computer plays: ")
      val nextBoard = board.computerPlays
      play(nextBoard, Human)
    }
  }

  play(new Board(),Human)

}

}


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 n=[1],max=[100],count=[0],divCount

  WHILE count<max
  DO
    divCount=DivisorCount(n)
    IF n MOD divCount=0 THEN
      PrintC(n) Put(32)
      count==+1
    FI
    n==+1
  OD
RETURN


BEGIN # find tau numbers - numbers divisible by the count of theoir divisors #
    # 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 #
            INT p := 1;
            WHILE  p +:= 2;
                   ( 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 tau limit  = 100;
        INT tau count := 0;
        print( ( "The first ", whole( tau limit, 0 ), " tau numbers:", newline ) );
        FOR n WHILE tau count < tau limit DO
            IF n MOD divisor count( n ) = 0 THEN
                tau count +:= 1;
                print( ( whole( n, -6 ) ) );
                IF tau count MOD 10 = 0 THEN print( ( newline ) ) FI
            FI
        OD
    END
END


begin

integer array dcount[1:1100];
integer i, j, n;

integer function mod(a,b);
integer a,b;
mod := a-a/b*b;

% Calculate counts of divisors for 1 .. 1100 %
for i := 1 step 1 until 1100 do dcount[i] := 1;
for i := 2 step 1 until 1100 do
begin
    j := i;
    while j <= 1100 do
    begin
        dcount[j] := dcount[j] + 1;
        j := j + i;
    end;
end;

n := 0;
i := 1;
while n < 100 do
begin
    if mod(i, dcount[i])=0 then
    begin
        if mod(n, 10)=0
            then write(i)
            else writeon(i);
        n := n + 1;
    end;
    i := i + 1;
end;
end


convertKelvins: function [k][
    #[
        celcius:    k - 273.15
        fahrenheit: (k * 9/5.0)-459.67
        rankine:    k * 9/5.0
    ]
]

print convertKelvins 100


MsgBox, % "Kelvin:`t`t 21.00 K`n"
        . "Celsius:`t`t" kelvinToCelsius(21) " C`n"
        . "Fahrenheit:`t" kelvinToFahrenheit(21) " F`n"
        . "Rankine:`t`t" kelvinToRankine(21) " R`n"

kelvinToCelsius(k)
{
    return, round(k - 273.15, 2)
}
kelvinToFahrenheit(k)
{
    return, round(k * 1.8 - 459.67, 2)
}
kelvinToRankine(k)
{
    return, round(k * 1.8, 2)
}


function [] = startGame()
    //Board size and marks
    N = 3;
    marks = ["X" "O"];

    //Creating empty board
    board = string(zeros(N,N));
    for i = 1:(N*N)
        board(i) = "";
    end

    //Initialising players
    clc();
    players= [%F %F];
    players = playerSetup(marks);

    //Console header
    header = [strsplit(marks(1)+" is ----")';...
              strsplit(marks(2)+" is ----")'];
    for i = 1:2
        if players(i) then
            header(i,6:10) = strsplit("P"+string(i)+".  ");
        else
            header(i,6:10) = strsplit("COMP.");
        end
    end

    //Game loop
    sleep(1000);
    win_flag = %F;
    count = 0;
    while count<N*N
        //Clear console, and print header and board
        clc();
        printf("%s\n %s\n",strcat(header(1,:)),strcat(header(2,:)));
        dispBoard(board);

        //Find which player should move
        player_n = modulo(count,2) + 1;

        if players(player_n) == %T then
            //Human plays
            pos = [];
            valid_move = %F;
            disp(marks(player_n)+"''s turn.");
            while valid_move ~= %T
                [pos,valid_move] = readHumanMove(board);
                if ~valid_move then
                    disp("You should input a valid cell number.");
                end
            end

            if valid_move then
                board = updateBoard(board,pos,marks(player_n));
            else
                error("Invalid move.");
            end
        else
            //Computer plays
            disp("Computer is playing.");
            board = ComputerMove(board,marks(player_n),marks);
            sleep(800);
        end

        //Count number of movements
        count = count + 1;

        //Check if the game has finished
        [win_flag,winning_mark] = detectWin(board)
        if win_flag then
            break
        end
    end

    //Clear screen at the end of game
    clc();
    disp("Game finished:");
    dispBoard(board);

    //Print results
    if win_flag then
        disp(winning_mark+" won!");
    else
        disp("It''s a tie.");
    end

    //Play again?
    play_again = "";
    while play_again ~= "Y" & play_again ~= "N"
        play_again = input("Would you like to play again? (Y/N)","s");
        play_again = strsplit(play_again);
        play_again = convstr(play_again(1),"u");

        if play_again ~= "Y" & play_again ~= "N" then
            disp("Invalid answer.");
        end
    end

    if play_again == "Y" then
        startGame();
    else
        disp("Quit game.");
    end
endfunction

function players = playerSetup(marks)
    //Determines who plays which mark
    players = [%F %F]; //True for human, Flase for computer

    printf("\n%s always starts.\n",marks(1));
    for i = 1:2
        user_input = "";
        while user_input ~= "Y" & user_input ~= "N"
            user_input = input("Would you like to play as "+marks(i)+"? (Y/N)","s");
            user_input = strsplit(user_input);
            user_input = convstr(user_input(1),"u");

            if user_input ~= "Y" & user_input ~= "N" then
                disp("Invalid answer.");
            end
        end

        //Print choice
        if user_input == "Y" then
            players(i) = %T;
            printf("%s shall be player %d (P%d).\n\n",marks(i),i,i);
        else
            printf("%s shall be the computer (COMP).\n\n",marks(i));
        end
    end
endfunction

function [] = dispBoard(board)
    //Print ASCII board on console

    //Get board marks
    marks = [" " " "];
    mark_inds = find(board ~= "");
    if mark_inds ~= [] then
        marks(1) = board(mark_inds(1));
        mark_inds = find( (board ~= "") & (board ~= marks(1)) );
        if mark_inds ~= [] then
            marks(2) = board(mark_inds(1));
        end
    end

    //Transpose to display for humans
    //[compatibility with readHumanMove()]
    disp_board = board';

    rows = 3*size(board,'r');
    cols = 4*size(board,'c');
    ascii_board = string(zeros(rows, cols));

    mark_1=[...
    strsplit("   |")';...
    strsplit(" "+marks(1)+" |")';...
    strsplit("___|")'];

    mark_2=[...
    strsplit("   |")';...
    strsplit(" "+marks(2)+" |")';...
    strsplit("___|")'];

    Blank_mark=[...
    strsplit("   |")';...
    strsplit("   |")';...
    strsplit("___|")'];

    for r = ([1:size(board,'r')] - 1 )
        for c = ([1:size(board,'c')] - 1)
            if disp_board(r+1,c+1) == marks(1) then
                ascii_board((r*3 + 1):((r+1)*3),...
                            (c*4 + 1):((c+1)*4)) = mark_1;
            elseif disp_board(r+1,c+1) == marks(2) then
                ascii_board((r*3 + 1):((r+1)*3),...
                            (c*4 + 1):((c+1)*4)) = mark_2;
            else
                ascii_board((r*3 + 1):((r+1)*3),...
                            (c*4 + 1):((c+1)*4)) = Blank_mark;
            end
        end
    end

    for i = 1:cols
        if modulo(i,4)>0 then
            ascii_board(rows,i) = " ";
        end
    end

    for i = 1:rows
        ascii_board(i,cols) = " ";
    end

    printf("\n");
    for i = 1:size(ascii_board,'r')
        printf("%s\n",strcat(ascii_board(i,:)))
    end
endfunction

function moves_board = availableMoves(board)
    //Find empty cells on the board
    moves_board = board;

    for i = 1:(size(board,'r')*size(board,'c'))
        if board(i) == "" then
            moves_board(i) = string(i);
        else
            moves_board(i) = "_";
        end
    end
endfunction

function varargout = readHumanMove(board)
    //Read human input
    printf("\nAvailable cells:");
    moves_board = availableMoves(board);
    disp(moves_board');

    x = input("\nEnter a move (0 to quit game): ");

    valid = %F;
    pos = 0;
    total = size(moves_board,'r') * size(moves_board,'c');

    //Check if it is a valid move
    if x == 0 then
        disp("Quit game.")
        abort
    elseif (x>=1 & x<=total) then
        if (moves_board(x) == string(x)) then
            valid = %T;
            pos = x;
        end
    end

    varargout = list(pos,valid);
endfunction

function varargout = updateBoard(board,pos,player)
    //Add move to the board
    if board(pos) ~= "" then
        error('Error: Invalid move.');
    end

    board(pos) = player

    varargout = list(board);
endfunction

function varargout = detectWin(board)
    //Detect if there is a winner or not
    win_flag = %F;
    winner = "";

    //Get board marks
    marks = ["" ""];
    mark_inds = find(board ~= "");
    marks(1) = board(mark_inds(1))
    mark_inds = find( (board ~= "") & (board ~= marks(1)) );
    marks(2) = board(mark_inds(1));

    //If there is a minimum number of moves, check if there is a winner
    n_moves = find(~(board == ""));
    n_moves = length(n_moves)

    if n_moves >= size(board,'r') then
        board_X = (board == marks(1));
        board_O = (board == marks(2));

        for i = 1:size(board,'r')
            //Check rows
            if find(~board_X(i,:)) == [] then
                win_flag = %T;
                winner = marks(1);
                break
            end
            if find(~board_O(i,:)) == [] then
                win_flag = %T;
                winner = marks(2);
                break
            end

            //Check columns
            if find(~board_X(:,i)) == [] then
                win_flag = %T;
                winner = marks(1);
                break
            end
            if find(~board_O(:,i)) == [] then
                win_flag = %T;
                winner = marks(2);
                break
            end
        end

        //Check diagonal
        if ~win_flag then
            if find(~diag(board_X)) == [] then
                win_flag = %T;
                winner = marks(1);
            elseif find(~diag(board_O)) == [] then
                win_flag = %T;
                winner = marks(2);
            end
        end

        //Check anti-diagonal
        if ~win_flag then
            board_X = board_X(:,$:-1:1);
            board_O = board_O(:,$:-1:1);

            if find(~diag(board_X)) == [] then
                win_flag = %T;
                winner = marks(1);
            elseif find(~diag(board_O)) == [] then
                win_flag = %T;
                winner = marks(2);
            end
        end
    end

    varargout = list(win_flag,winner)
endfunction

function threat_pos = findThreat(board,player)
    //Returns a list of moves that can finish the game

    //Available moves
    move_inds = find(~( availableMoves(board) == "_" ));

    //If there is a minimum number of moves, check if there is a threat
    threat_pos = [];
    if (size(board,'r')*size(board,'c')) - length(move_inds) >...
       (size(board,'r') - 1) then
        for i = 1:length(move_inds)
            temp_board = updateBoard(board,move_inds(i),player);
            [win_flag,winner] = detectWin(temp_board);
            if win_flag & winner == player then
                threat_pos = [threat_pos move_inds(i)];
            end
        end
    end
endfunction

function varargout = ComputerMove(board,mark,all_marks)
    //Atomatically add a move to the board with no human input

    //Find winning moves moves
    move_inds = findThreat(board,mark);

    //If there are no winning moves, find opponent's winning moves
    //to block opponent's victory
    if move_inds == [] then
        if mark == all_marks(1) then
            opponent = all_marks(2);
        elseif mark == all_marks(2) then
            opponent = all_marks(1);
        end

        move_inds = findThreat(board,opponent);
    end

    //If there are no winning moves or threats, find all possible moves
    if move_inds == [] then
        move_inds = find(~( availableMoves(board) == "_" ));
    end

    //Choose a random move among the selected possible moves
    pos = grand(1,"prm",move_inds);
    pos = pos(1);

    //Update board by adding a new mark
    board(pos) = mark;

    varargout = list(board);
endfunction

startGame()


on factorCount(n)
    if (n < 1) then return 0
    set counter to 2
    set sqrt to n ^ 0.5
    if (sqrt mod 1 = 0) then set counter to 1
    repeat with i from (sqrt div 1) to 2 by -1
        if (n mod i = 0) then set counter to counter + 2
    end repeat

    return counter
end factorCount

-- Task code:
local output, n, counter, astid
set output to {"First 100 tau numbers:"}
set n to 0
set counter to 0
repeat until (counter = 100)
    set n to n + 1
    if (n mod (factorCount(n)) = 0) then
        set counter to counter + 1
        if (counter mod 20 = 1) then set end of output to linefeed
        set end of output to text -5 thru -1 of ("    " & n)
    end if
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
set output to output as text
set AppleScript's text item delimiters to astid
return output


tau: function [x] -> size factors x

found: 0
i:1
while [found<100][
    if 0 = i % tau i [
        prints pad to :string i 5
        found: found + 1
        if 0 = found % 10 -> print ""
    ]
    i: i + 1
]


;  ### USAGE - TESTING PURPOSES ONLY

Local Const $_KELVIN = 21
ConsoleWrite("Kelvin: " & $_KELVIN & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "C") & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "F") & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "R") & @CRLF)

;   ### KELVIN TEMPERATURE CONVERSIONS

Func Kelvin($degrees, $conversion)
    Select
        Case $conversion = "C"
            Return Round($degrees - 273.15, 2)
        Case $conversion = "F"
            Return Round(($degrees * 1.8) - 459.67, 2)
        Case $conversion = "R"
            Return Round($degrees * 1.8, 2)
    EndSelect
EndFunc ;==> Kelvin


# syntax: AWK -f TEMPERATURE_CONVERSION.AWK
BEGIN {
    while (1) {
      printf("\nKelvin degrees? ")
      getline K
      if (K ~ /^$/) {
        break
      }
      if (K < 0) {
        print("K must be >= 0")
        continue
      }
      printf("K = %.2f\n",K)
      printf("C = %.2f\n",K - 273.15)
      printf("F = %.2f\n",K * 1.8 - 459.67)
      printf("R = %.2f\n",K * 1.8)
    }
    exit(0)
}


--Setup
DROP TABLE IF EXISTS board;
CREATE TABLE board (p CHAR, r INTEGER, c INTEGER);
INSERT INTO board VALUES('.', 0, 0),('.', 0, 1),('.', 0, 2),('.', 1, 0),('.', 1, 1),('.', 1, 2),('.', 2, 0),('.', 2, 1),('.', 2, 2);

-- Use a trigger for move events
DROP TRIGGER IF EXISTS after_moved;
CREATE TRIGGER after_moved after UPDATE ON board FOR each ROW WHEN NEW.p <> '.' AND NEW.p <> 'O'
BEGIN

    -- Verify move is valid
    SELECT
        CASE
            WHEN (SELECT v FROM msg) LIKE '%Wins!' THEN raise(ABORT, 'The game is already over.')
            WHEN (SELECT OLD.p FROM board WHERE rowid = rid) <> '.' THEN raise(ABORT, 'That position has already been taken.  Please choose an available position.')
            WHEN NEW.p <> 'X' THEN raise(ABORT, 'Please place an ''X''')
        END
    FROM (
        SELECT rowid rid FROM board
        WHERE p = NEW.p
        EXCEPT
        SELECT p FROM board WHERE p = OLD.p
    );

    -- Check for game over
    UPDATE msg SET v = (
        SELECT
            CASE
                WHEN MAX(num) >= 3 THEN 'X Wins!'
                WHEN (SELECT COUNT(*) FROM board WHERE p = '.') = 0 THEN 'Cat Wins!'
                ELSE 'Move made'
            END
        FROM ( -- Is Game Over
            SELECT COUNT(*) num FROM board WHERE p = 'X' GROUP BY r UNION -- Horz
            SELECT COUNT(*) num FROM board WHERE p = 'X' GROUP BY c UNION -- Vert
            SELECT COUNT(*) num FROM board WHERE p = 'X' AND r = c UNION -- Diag TL->BR
            SELECT COUNT(*) num FROM board WHERE p = 'X' AND (2-r) = c -- Diag TR->BL
        )
    );

    --Have computer player make a random move
    UPDATE board SET p = 'O'
    WHERE rowid = (SELECT rid FROM (SELECT MAX(rnd),rid FROM (SELECT rowid rid, random() rnd FROM board WHERE p = '.')))
    AND (SELECT v FROM msg) NOT LIKE '%Wins!';
    --NOTE: SQLite doesn't allow update order by in triggers, otherwise we could just use this beautiful line:
    -- update board set p = 'O' where p = '.' order by random() limit 1;

    --Check to see if the computer player won
    UPDATE msg SET v = (
        SELECT
            CASE
                WHEN MAX(num) >= 3 THEN 'O Wins!'
                ELSE v
            END
        FROM ( -- Is Game Over
            SELECT COUNT(*) num FROM board WHERE p = 'O' GROUP BY r UNION -- Horz
            SELECT COUNT(*) num FROM board WHERE p = 'O' GROUP BY c UNION -- Vert
            SELECT COUNT(*) num FROM board WHERE p = 'O' AND r = c UNION -- Diag TL->BR
            SELECT COUNT(*) num FROM board WHERE p = 'O' AND (2-r) = c -- Diag TR->BL
        )
    );

END;

-- UI to display the logical board as a grid
DROP VIEW IF EXISTS ui;
CREATE VIEW ui AS
SELECT CASE WHEN p = '.' THEN col0.rowid ELSE p END c0, c1, c2
FROM board AS col0
JOIN (SELECT CASE WHEN p = '.' THEN board.rowid ELSE p END c1, r FROM board WHERE c = 1) AS col1 ON col0.r = col1.r
JOIN (SELECT CASE WHEN p = '.' THEN board.rowid ELSE p END  c2, r FROM board WHERE c = 2) AS col2 ON col0.r = col2.r
WHERE c = 0;

DROP TABLE IF EXISTS msg;
CREATE TABLE msg (v text);
INSERT INTO msg VALUES('');

-- Readme
SELECT * FROM ui;
.print "Use this to play:"
.print "->update board set p = 'X' where rowid = ?; select * from ui; select * from msg;"'


# syntax: GAWK -f TAU_NUMBER.AWK
BEGIN {
    print("The first 100 tau numbers:")
    while (count < 100) {
      i++
      if (i % count_divisors(i) == 0) {
        printf("%4d ",i)
        if (++count % 10 == 0) {
          printf("\n")
        }
      }
    }
    exit(0)
}
function count_divisors(n,  count,i) {
    for (i=1; i*i<=n; i++) {
      if (n % i == 0) {
        count += (i == n / i) ? 1 : 2
      }
    }
    return(count)
}


10 DEFINT A-Z
20 S=0: N=1
30 C=1
40 IF N<>1 THEN FOR I=1 TO N/2: C=C-(N MOD I=0): NEXT
50 IF N MOD C=0 THEN PRINT N,: S=S+1
60 N=N+1
70 IF S<100 THEN 30
80 END


get "libhdr"

// Count the divisors of 1..N
let divcounts(v, n) be
$(  // Every positive number is divisible by 1
    for i=1 to n do v!i := 1;
    for i=2 to n do
    $(  let j = i
        while j <= n do
        $(  // J is divisible by I
            v!j := v!j + 1
            j := j + i
        $)
    $)
$)

// Given a stored vector of divisors counts, is a number a tau number?
let tau(v, i) = i rem v!i = 0

let start() be
$(  let dvec = vec 1100
    let n, seen = 1, 0

    divcounts(dvec, 1100) // find amount of divisors for each number
    while seen < 100 do
    $(  if tau(dvec, n) then
        $(  writed(n, 5)
            seen := seen + 1
            if seen rem 10 = 0 then wrch('*N')
        $)
        n := n + 1
    $)
$)


#include <stdio.h>

unsigned int divisor_count(unsigned int n) {
    unsigned int total = 1;
    unsigned int p;

    // Deal with powers of 2 first
    for (; (n & 1) == 0; n >>= 1) {
        ++total;
    }
    // Odd prime factors up to the square root
    for (p = 3; p * p <= n; p += 2) {
        unsigned int count = 1;
        for (; n % p == 0; n /= p) {
            ++count;
        }
        total *= count;
    }
    // If n > 1 then it's prime
    if (n > 1) {
        total *= 2;
    }
    return total;
}

int main() {
    const unsigned int limit = 100;
    unsigned int count = 0;
    unsigned int n;

    printf("The first %d tau numbers are:\n", limit);
    for (n = 1; count < limit; ++n) {
        if (n % divisor_count(n) == 0) {
            printf("%6d", n);
            ++count;
            if (count % 10 == 0) {
                printf("\n");
            }
        }
    }

    return 0;
}


10 REM TRANSLATION OF AWK VERSION
20 INPUT "KELVIN DEGREES",K
30 IF K <= 0 THEN END: REM A VALUE OF ZERO OR LESS WILL END PROGRAM
40 LET C = K - 273.15
50 LET F = K * 1.8 - 459.67
60 LET R = K * 1.8
70 PRINT K; " KELVIN IS EQUIVALENT TO"
80 PRINT C; " DEGREES CELSIUS"
90 PRINT F; " DEGREES FAHRENHEIT"
100 PRINT R; " DEGREES RANKINE"
110 GOTO 20


do
  print "Kelvin degrees (>=0): ";
  input K
  until K>=0

print "K = " + string(K)
print "C = " + string(K - 273.15)
print "F = " + string(K * 1.8 - 459.67)
print "R = " + string(K * 1.8)


import Darwin

enum Token : CustomStringConvertible {
	case cross, circle

	func matches(tokens: [Token?]) -> Bool {
		for token in tokens {
			guard let t = token, t == self else {
				return false
			}
		}
		return true
	}

	func emptyCell(in tokens: [Token?]) -> Int? {
		if tokens[0] == nil
		&& tokens[1] == self
		&& tokens[2] == self {
			return 0
		} else
		if tokens[0] == self
		&& tokens[1] == nil
		&& tokens[2] == self {
			return 1
		} else
		if tokens[0] == self
		&& tokens[1] == self
		&& tokens[2] == nil {
			return 2
		}
		return nil
	}

	var description: String {
		switch self {
			case .cross: return "x"
			case .circle: return "o"
		}
	}
}

struct Board {
	var cells: [Token?] = [nil, nil, nil, nil, nil, nil, nil, nil, nil]

	func cells(atCol col: Int) -> [Token?] {
		return [cells[col], cells[col + 3], cells[col + 6]]
	}

	func cells(atRow row: Int) -> [Token?] {
		return [cells[row * 3], cells[row * 3 + 1], cells[row * 3 + 2]]
	}

	func cellsTopLeft() -> [Token?] {
		return [cells[0], cells[4], cells[8]]
	}

	func cellsBottomLeft() -> [Token?] {
		return [cells[6], cells[4], cells[2]]
	}

	func winner() -> Token? {
		let r0 = cells(atRow: 0)
		let r1 = cells(atRow: 1)
		let r2 = cells(atRow: 2)
		let c0 = cells(atCol: 0)
		let c1 = cells(atCol: 1)
		let c2 = cells(atCol: 2)
		let tl = cellsTopLeft()
		let bl = cellsBottomLeft()

		if Token.cross.matches(tokens: r0)
		|| Token.cross.matches(tokens: r1)
		|| Token.cross.matches(tokens: r2)
		|| Token.cross.matches(tokens: c0)
		|| Token.cross.matches(tokens: c1)
		|| Token.cross.matches(tokens: c2)
		|| Token.cross.matches(tokens: tl)
		|| Token.cross.matches(tokens: bl) {
			return .cross
		} else
		if Token.circle.matches(tokens: r0)
		|| Token.circle.matches(tokens: r1)
		|| Token.circle.matches(tokens: r2)
		|| Token.circle.matches(tokens: c0)
		|| Token.circle.matches(tokens: c1)
		|| Token.circle.matches(tokens: c2)
		|| Token.circle.matches(tokens: tl)
		|| Token.circle.matches(tokens: bl) {
			return .circle
		}
		return nil
	}

	func atCapacity() -> Bool {
		return cells.filter { $0 == nil }.count == 0
	}

	mutating func play(token: Token, at location: Int) {
		cells[location] = token
	}

	func findBestLocation(for player: Token) -> Int? {
		let r0 = cells(atRow: 0)
		let r1 = cells(atRow: 1)
		let r2 = cells(atRow: 2)
		let c0 = cells(atCol: 0)
		let c1 = cells(atCol: 1)
		let c2 = cells(atCol: 2)
		let tl = cellsTopLeft()
		let bl = cellsBottomLeft()

		if let cell = player.emptyCell(in: r0) {
			return cell
		} else if let cell = player.emptyCell(in: r1) {
			return cell + 3
		} else if let cell = player.emptyCell(in: r2) {
			return cell + 6
		} else if let cell = player.emptyCell(in: c0) {
			return cell * 3
		} else if let cell = player.emptyCell(in: c1) {
			return cell * 3 + 1
		} else if let cell = player.emptyCell(in: c2) {
			return cell * 3 + 2
		} else if let cell = player.emptyCell(in: tl) {
			return cell == 0 ? 0 : (cell == 1 ? 4 : 8)
		} else if let cell = player.emptyCell(in: bl) {
			return cell == 0 ? 6 : (cell == 1 ? 4 : 2)
		}
		return nil
	}

	func findMove() -> Int {
		let empties = cells.enumerated().filter { $0.1 == nil }
		let r = Int(arc4random()) % empties.count
		return empties[r].0
	}
}

extension Board : CustomStringConvertible {
	var description: String {
		var result = "\n---------------\n"
		for (idx, cell) in cells.enumerated() {
			if let cell = cell {
				result += "| \(cell) |"
			} else {
				result += "| \(idx) |"
			}

			if (idx + 1) % 3 == 0 {
				result += "\n---------------\n"
			}
		}
		return result
	}
}

while true {
	var board = Board()
	print("Who do you want to play as ('o' or 'x'): ", separator: "", terminator: "")
	let answer = readLine()?.characters.first ?? "x"

	var player: Token = answer == "x" ? .cross : .circle
	var pc: Token = player == .cross ? .circle : .cross

	print(board)

	while true {
		print("Choose cell to play on: ", separator: "", terminator: "")
		var pos = Int(readLine() ?? "0") ?? 0
		while !board.atCapacity() && board.cells[pos] != nil {
			print("Invalid move. Choose cell to play on: ", separator: "", terminator: "")
			pos = Int(readLine() ?? "0") ?? 0
		}

		if board.atCapacity() {
			print("Draw")
			break
		}

		board.play(token: player, at: pos)
		print(board)

		if let winner = board.winner() {
			print("winner is \(winner)")
			break
		} else if board.atCapacity() {
			print("Draw")
			break
		}

		if let win = board.findBestLocation(for: pc) {
			board.play(token: pc, at: win)
		} else if let def = board.findBestLocation(for: player) {
			board.play(token: pc, at: def)
		} else {
			board.play(token: pc, at: board.findMove())
		}

		print(board)

		if let winner = board.winner() {
			print("winner is \(winner)")
			break
		}
	}
}


#include <iomanip>
#include <iostream>

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

int main() {
    const unsigned int limit = 100;
    std::cout << "The first " << limit << " tau numbers are:\n";
    unsigned int count = 0;
    for (unsigned int n = 1; count < limit; ++n) {
        if (n % divisor_count(n) == 0) {
            std::cout << std::setw(6) << n;
            ++count;
            if (count % 10 == 0)
                std::cout << '\n';
        }
    }
}


% Count the divisors of [1..N]
count_divisors = proc (n: int) returns (sequence[int])
    divs: array[int] := array[int]$fill(1, n, 1)
    for i: int in int$from_to(2, n) do
        for j: int in int$from_to_by(i, n, i) do
            divs[j] := divs[j] + 1
        end
    end
    return(sequence[int]$a2s(divs))
end count_divisors

% Find Tau numbers up to a given limit
tau_numbers = iter (lim: int) yields (int)
    divs: sequence[int] := count_divisors(lim)
    n: int := 0
    while n < lim do
        n := n + 1
        if n // divs[n] = 0 then yield(n) end
    end
end tau_numbers

% Show the first 100 Tau numbers
start_up = proc ()
    po: stream := stream$primary_output()
    seen: int := 0

    for n: int in tau_numbers(1100) do
        seen := seen + 1
        stream$putright(po, int$unparse(n), 5)
        if seen // 10 = 0 then stream$putl(po, "") end
        if seen >= 100 then break end
    end
end start_up


include "cowgol.coh";

# Get count of positive divisors of number
sub pos_div(num: uint16): (count: uint16) is
    count := 1;
    if num != 1 then
        var cur: uint16 := 1;
        while cur <= num/2 loop
            if num % cur == 0 then
                count := count + 1;
            end if;
            cur := cur + 1;
        end loop;
    end if;
end sub;

# Print first 100 Tau numbers
var nums: uint8 := 0;
var cur: uint16 := 0;
var col: uint16 := 10;
while nums < 100 loop
    cur := cur + 1;
    if cur % pos_div(cur) == 0 then
        print_i16(cur);
        col := col - 1;
        if col == 0 then
            print_nl();
            col := 10;
        else
            print_char('\t');
        end if;
        nums := nums + 1;
    end if;
end loop;


REPEAT
  INPUT "Kelvin degrees (>=0): " K
UNTIL K>=0
@%=&20208
PRINT '"K = " K
PRINT "C = " K - 273.15
PRINT "F = " K * 1.8 - 459.67
PRINT "R = " K * 1.8
END


( ( rational2fixedpoint
  =   minus fixedpointnumber number decimals
    .   !arg:(#?number.~<0:~/#?decimals)
      & ( !number:0&"0.0"
        |     ( !number:>0&
              | -1*!number:?number&"-"
              )
            : ?minus
          & !number+1/2*10^(-1*!decimals):?number
          & !minus div$(!number.1) ".":?fixedpointnumber
          &   whl
            ' ( !decimals+-1:~<0:?decimals
              &     !fixedpointnumber
                    div$(mod$(!number.1)*10:?number.1)
                : ?fixedpointnumber
              )
          & str$!fixedpointnumber
        )
  )
& ( fixedpoint2rational
  =   integerpart fractionalpart decimals
    .   @( !arg
         :   #?integerpart
             ( "." ?fractionalpart
             | &0:?fractionalpart
             )
         )
      & @(!fractionalpart:? #?fractionalpart [?decimals)
      &   !integerpart
        +   (!integerpart:<0&-1|1)
          * 10^(-1*!decimals)
          * !fractionalpart
  )
&   whl
  ' ( put$"Enter Kelvin temperature:"
    & fixedpoint2rational$(get'(,STR)):?kelvin
    & !kelvin+-27315/100:?celcius
    & (degree=.str$(chu$(x2d$b0) !arg))
    & out$(rational2fixedpoint$(!kelvin.2) K)
    & out$(rational2fixedpoint$(!celcius.2) degree$C)
    & out$(rational2fixedpoint$(!celcius*9/5+32.2) degree$F)
    & out$(rational2fixedpoint$(!kelvin*9/5.2) degree$Ra)
    & out$(rational2fixedpoint$(!celcius*4/5.2) degree$Ré)
    )
& done!
)


processor Tic-Tac-Toe
  @: [1..9 -> (position:$) -> $::value];

  source isWonOrDone
    [[email protected](1..3) -> #, [email protected](4..6) -> #, [email protected](7..9) -> #,
      [email protected](1..9:3) -> #, [email protected](2..9:3) -> #, [email protected](3..9:3) -> #,
      [email protected]([1,5,9]) -> #, [email protected]([3,5,7]) -> #
    ] -> \(
        when <=[]?([email protected] <~[<1..9>]>)> do 'draw' !
        when <~=[]> do $(1) !
      \) !
    when <[<=$(first)::raw>+ VOID]> do '$(first); wins!'!
  end isWonOrDone

  source validMoves
    [email protected] -> \[i](<1..9> $ !\) !
  end validMoves

  templates move
    when <?([email protected]($.position) <position>)> do @Tic-Tac-Toe($.position): $.mark;
      $ !
    otherwise
      'Incorrect move$#10;' -> !OUT::write
  end move

  source showString
    '$:1..9:3 -> '$#10;[email protected]($..$+2)...;';$#10;' !
  end showString
end Tic-Tac-Toe

composer toInt
  <INT>
end toInt

source play
  def board: $Tic-Tac-Toe;
  @: 'X';
  templates getMove
    [] -> #
    when <=[]> do
      $board::showString -> !OUT::write
      '[email protected]; to move $board::validMoves;:$#10;' -> !OUT::write
      [{mark: [email protected], position: $IN::readline -> toInt} -> board::move] -> #
    otherwise
      $(1) !
  end getMove

  $getMove -> #
  when <{}> do
    '$.mark; played $.position;$#10;' -> !OUT::write
    @: [email protected] -> \(<='X'> 'O'! <='O'> 'X' !\);
    [$board::isWonOrDone] -> \(
      when <=[]> do $getMove!
      otherwise '$(1);$#10;' -> !OUT::write
    \) -> #
end play

$play -> !VOID


import std.stdio;

uint divisor_count(uint n) {
    uint total = 1;
    // Deal with powers of 2 first
    for (; (n & 1) == 0; n >>= 1) {
        ++total;
    }
    // Odd prime factors up to the square root
    for (uint p = 3; p * p <= n; p += 2) {
        uint count = 1;
        for (; n % p == 0; n /= p) {
            ++count;
        }
        total *= count;
    }
    // If n > 1 then it's prime
    if (n > 1) {
        total *= 2;
    }
    return total;
}

void main() {
    immutable limit = 100;
    writeln("The first ", limit, " tau numbers are:");
    uint count = 0;
    for (uint n = 1; count < limit; ++n) {
        if (n % divisor_count(n) == 0) {
            writef("%6d", n);
            ++count;
            if (count % 10 == 0) {
                writeln;
            }
        }
    }
}


program Tau_number;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function CountDivisors(n: Integer): Integer;
begin
  Result := 0;
  var i := 1;
  var k := 2;
  if (n mod 2) = 0 then
    k := 1;

  while i * i <= n do
  begin
    if (n mod i) = 0 then
    begin
      inc(Result);
      var j := n div i;
      if j <> i then
        inc(Result);
    end;
    inc(i, k);
  end;
end;

begin
  Writeln('The first 100 tau numbers are:');
  var count := 0;
  var i := 1;
  while count < 100 do
  begin
    var tf := CountDivisors(i);
    if i mod tf = 0 then
    begin
      write(format('%4d ', [i]));
      inc(count);
      if count mod 10 = 0 then
        writeln;
    end;
    inc(i);
  end;

  {$IFNDEF UNIX}  readln; {$ENDIF}
end.


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

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

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

double kelvinToRankine(double k){
    return k * 1.8;
}
void convertKelvin(double kelvin) {
    printf("K %.2f\n", kelvin);
    printf("C %.2f\n", kelvinToCelsius(kelvin));
    printf("F %.2f\n", kelvinToFahrenheit(kelvin));
    printf("R %.2f", kelvinToRankine(kelvin));
}

int main(int argc, const char * argv[])
{
    if (argc > 1) {
        double kelvin = atof(argv[1]);
        convertKelvin(kelvin);
    }
    return 0;
}


using System;

namespace TemperatureConversion
{
    class Program
    {
        static Func<double, double> ConvertKelvinToFahrenheit = x => (x * 1.8) - 459.67;
        static Func<double, double> ConvertKelvinToRankine = x => x * 1.8;
        static Func<double, double> ConvertKelvinToCelsius = x => x = 273.13;

        static void Main(string[] args)
        {
            Console.Write("Enter a Kelvin Temperature: ");
            string inputVal = Console.ReadLine();
            double kelvinTemp = 0f;

            if (double.TryParse(inputVal, out kelvinTemp))
            {
                Console.WriteLine(string.Format("Kelvin: {0}", kelvinTemp));
                Console.WriteLine(string.Format("Fahrenheit: {0}", ConvertKelvinToFahrenheit(kelvinTemp)));
                Console.WriteLine(string.Format("Rankine: {0}", ConvertKelvinToRankine(kelvinTemp)));
                Console.WriteLine(string.Format("Celsius: {0}", ConvertKelvinToCelsius(kelvinTemp)));
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Invalid input value: " + inputVal);
            }
        }
    }
}


package require Tcl 8.6

# This code splits the players from the core game engine
oo::class create TicTacToe {
    variable board player letter who
    constructor {player1class player2class} {
	set board {1 2 3 4 5 6 7 8 9}
	set player(0) [$player1class new [self] [set letter(0) "X"]]
	set player(1) [$player2class new [self] [set letter(1) "O"]]
	set who 0
    }

    method PrintBoard {} {
	lassign $board a1 b1 c1 a2 b2 c2 a3 b3 c3
	puts [format " %s | %s | %s" $a1 $b1 $c1]
	puts "---+---+---"
	puts [format " %s | %s | %s" $a2 $b2 $c2]
	puts "---+---+---"
	puts [format " %s | %s | %s" $a3 $b3 $c3]
    }

    method WinForSomeone {} {
	foreach w {
	    {0 1 2} {3 4 5} {6 7 8} {0 3 6} {1 4 7} {2 5 8} {0 4 8} {2 4 6}
	} {
	    set b [lindex $board [lindex $w 0]]
	    if {$b ni "X O"} continue
	    foreach i $w {if {[lindex $board $i] ne $b} break}
	    if {[lindex $board $i] eq $b} {
		foreach p $w {lappend w1 [expr {$p+1}]}
		return [list $b $w1]
	    }
	}
	return ""
    }

    method status {} {
	return $board
    }

    method IsDraw {} {
	foreach b $board {if {[string is digit $b]} {return false}}
	return true
    }

    method legalMoves {} {
	foreach b $board {if {[string is digit $b]} {lappend legal $b}}
	return $legal
    }

    method DoATurn {} {
	set legal [my legalMoves]
	my PrintBoard
	while 1 {
	    set move [$player($who) turn]
	    if {$move in $legal} break
	    puts "Illegal move!"
	}
	lset board [expr {$move - 1}] $letter($who)
	$player($who) describeMove $move
	set who [expr {1 - $who}]
	return [my WinForSomeone]
    }

    method game {} {
        puts "    Tic-tac-toe game player.
    Input the index of where you wish to place your mark at your turn.\n"
	while {![my IsDraw]} {
	    set winner [my DoATurn]
	    if {$winner eq ""} continue
	    lassign $winner winLetter winSites
	    my PrintBoard
	    puts "\n$winLetter wins across \[[join $winSites {, }]\]"
	    return $winLetter
	}
	puts "\nA draw"
    }
}

# Stupid robotic player
oo::class create RandomRoboPlayer {
    variable g
    constructor {game letter} {
	set g $game
    }
    method turn {} {
	set legal [$g legalMoves]
	return [lindex $legal [expr {int(rand()*[llength $legal])}]]
    }
    method describeMove {move} {
	puts "I go at $move"
    }
}

# Interactive human player delegate
oo::class create HumanPlayer {
    variable g char
    constructor {game letter} {
	set g $game
	set char $letter
    }
    method turn {} {
	set legal [$g legalMoves]
	puts ">>> Put your $char in any of these positions: [join $legal {}]"
	while 1 {
	    puts -nonewline ">>> "
	    flush stdout
	    gets stdin number
	    if {$number in $legal} break
	    puts ">>> Whoops I don't understand the input!"
	}
	return $number
    }
    method describeMove {move} {
	puts "You went at $move"
    }
}

# Assemble the pieces
set ttt [TicTacToe new HumanPlayer RandomRoboPlayer]
$ttt game


/* Generate a table of the amount of divisors for each number */
proc nonrec div_count([*]word divs) void:
    word max, i, j;
    max := dim(divs,1)-1;
    divs[0] := 0;
    for i from 1 upto max do divs[i] := 1 od;
    for i from 2 upto max do
        for j from i by i upto max do
            divs[j] := divs[j] + 1
        od
    od
corp

/* Find Tau numbers */
proc nonrec main() void:
    [1100]word divs;
    word n, seen;

    div_count(divs);
    seen := 0;
    n := 0;

    while n := n + 1; seen < 100 do
        if n % divs[n] = 0 then
            seen := seen + 1;
            write(n:5);
            if seen % 10 = 0 then writeln() fi
        fi
    od
corp


// Tau number. Nigel Galloway: March 9th., 2021
Seq.initInfinite((+)1)|>Seq.filter(fun n->n%(tau n)=0)|>Seq.take 100|>Seq.iter(printf "%d "); printfn ""


USING: assocs grouping io kernel lists lists.lazy math
math.functions math.primes.factors prettyprint sequences
sequences.extras ;

: tau ( n -- count ) group-factors values [ 1 + ] map-product ;

: tau? ( n -- ? ) dup tau divisor? ;

: taus ( -- list ) 1 lfrom [ tau? ] lfilter ;

! Task
"The first 100 tau numbers are:" print
100 taus ltake list>array 10 group simple-table.


Func Istau(t) =
    if t<3 then Return(1) else
        numdiv:=2;
        for q = 2 to t\2 do
            if Divides(q, t) then numdiv:=numdiv+1 fi;
        od;
        if Divides(numdiv, t)=1 then Return(1) else Return(0) fi;
    fi;
    .;

numtau:=0;
i:=0;

while numtau<100 do
    i:=i+1;
    if Istau(i) = 1 then
        numtau:=numtau+1;
        !(i,'   ');
        if Divides(10, numtau) then !! fi;
    fi;
od;


: divisor_count ( n -- n )
  1 >r
  begin
    dup 2 mod 0=
  while
    r> 1+ >r
    2/
  repeat
  3
  begin
    2dup dup * >=
  while
    1 >r
    begin
      2dup mod 0=
    while
      r> 1+ >r
      tuck / swap
    repeat
    2r> * >r
    2 +
  repeat
  drop 1 > if r> 2* else r> then ;

: print_tau_numbers ( n -- )
  ." The first " dup . ." tau numbers are:" cr
  0 >r
  1
  begin
    over [email protected] >
  while
    dup dup divisor_count mod 0= if
      dup 6 .r
      r> 1+
      dup 10 mod 0= if cr else space then
      >r
    then
    1+
  repeat
  2drop rdrop ;

100 print_tau_numbers
bye


    REM Tic-tac-toe for Tiny BASIC
    REM
    REM Released as public domain by Damian Gareth Walker, 2019
    REM Created: 21-Sep-2019

    REM --- Variables
    REM     A   - first square in line examined
    REM     B   - second square in line examined
    REM     C   - third square in line examined
    REM     D   - player whose pieces to count
    REM     E   - number of DREM s pieces on a line
    REM     F   - first square of line to examine
    REM     G   - game winner
    REM     H   - which side the human takes
    REM     I   - increment for line to examine
    REM     L   - line to examine
    REM     M   - where to move (various uses)
    REM     N   - piece found in a square
    REM     P   - player currently playing
    REM     Q   - square to examine
    REM     R-Z - contents of the board

    REM --- Main Program
    GOSUB 40
    GOSUB 60
    GOSUB 80
    END

    REM --- Subroutine to initialise the game
    REM     Outputs: H - Human play order
    REM              P - Whose turn it is
 40 PRINT "Tic tac toe. Board positions are:"
    PRINT " 1  2  3"
    PRINT " 4  5  6"
    PRINT " 7  8  9"
    PRINT "Play first or second (1/2)?"
    INPUT H
    IF H<1 THEN GOTO 40
    IF H>2 THEN GOTO 40
    LET P=1
    RETURN

    REM --- Subroutine to take turns
    REM     Inputs:  H - who is the human
    REM              P - whose turn it is
    REM     Outputs: G - who won the game
 60 IF P=H THEN GOSUB 100
    IF P<>H THEN GOSUB 120
    GOSUB 200
    IF G>0 THEN RETURN
    LET P=3-P
    IF R=0 THEN GOTO 60
    IF S=0 THEN GOTO 60
    IF T=0 THEN GOTO 60
    IF U=0 THEN GOTO 60
    IF V=0 THEN GOTO 60
    IF W=0 THEN GOTO 60
    IF X=0 THEN GOTO 60
    IF Y=0 THEN GOTO 60
    IF Z=0 THEN GOTO 60
    RETURN

    REM --- Victory
    REM Inputs: H   - which side was the human
    REM         P   - player who won
 80 IF G=H THEN PRINT "You win!"
    IF G<>0 THEN IF G<>H THEN PRINT "Computer wins"
    IF G=0 THEN PRINT "A draw"
    RETURN

    REM --- Subroutine to allow the player to move
    REM     Inputs:  P   - player number
    REM     Outputs: M   - where the player wishes to move
100 PRINT "Move? "
    INPUT Q
    IF Q<1 THEN GOTO 100
    IF Q>9 THEN GOTO 100
    GOSUB 220
    IF N<>0 THEN GOTO 100
    LET M=Q
    GOSUB 240
    RETURN

    REM --- Subroutine to make the computerREM s move
    REM     Inputs:  P   - player number
    REM     Outputs: M   - the move chosen
120 LET M=0
    LET D=3-H
    GOSUB 145
    IF M>0 THEN GOTO 135
    LET D=H
    GOSUB 145
    IF M=0 THEN IF V=0 THEN LET M=5
    IF M=0 THEN IF R=0 THEN LET M=1
    IF M=0 THEN IF T=0 THEN LET M=3
    IF M=0 THEN IF X=0 THEN LET M=7
    IF M=0 THEN IF Z=0 THEN LET M=9
    IF M=0 THEN IF S=0 THEN LET M=2
    IF M=0 THEN IF U=0 THEN LET M=4
    IF M=0 THEN IF Y=0 THEN LET M=8
    IF M=0 THEN IF W=0 THEN LET M=6
135 GOSUB 240
    PRINT "Computer move ",M
    RETURN

    REM --- Identify moves to win or avoid a loss
    REM     Inputs:  D   - player whose pieces weREM re counting
    REM     Changes: E   - number of pieces on line being scanned
    REM              F   - first square in winning line
    REM              I   - increment of winning line
    REM              L   - line being scanned (counter)
145 LET L=1
146 GOSUB 170
    IF E<2 THEN GOTO 152
    IF A=0 THEN LET M=F
    IF B=0 THEN LET M=F+I
    IF C=0 THEN LET M=F+I+I
    IF M>0 THEN RETURN
152 LET L=L+1
    IF L<9 THEN GOTO 146
    RETURN

    REM --- Count a playerREM s pieces on a line
    REM     Inputs:  D   - player whose pieces weREM re counting
    REM              L   - line number
    REM     Changes: F   - first square on the line
    REM              I   - increment of the line
    REM              Q   - individual squares to examine
    REM     Outputs: A   - contents of first square
    REM              B   - contents of second square
    REM              C   - contents of third square
    REM              E   - number of the playerREM s pieces
170 IF L>3 THEN GOTO 174
    LET F=3*L-2
    LET I=1
    GOTO 180
174 IF L>6 THEN GOTO 178
    LET F=L-3
    LET I=3
    GOTO 180
178 LET F=1+2*(L-7)
    LET I=4-2*(L-7)
180 LET E=0
    LET Q=F
    GOSUB 220
    LET A=N
    IF N=D THEN LET E=E+1
    LET Q=Q+I
    GOSUB 220
    LET B=N
    IF N=D THEN LET E=E+1
    LET Q=Q+I
    GOSUB 220
    LET C=N
    IF N=D THEN LET E=E+1
    RETURN

    REM --- Subroutine to check for a win
    REM     Inputs:  R-Z - board squares
    REM     Outputs: G   - the winning player (0 for neither)
200 LET G=0
    IF R>0 THEN IF R=S THEN IF S=T THEN LET G=R
    IF U>0 THEN IF U=V THEN IF V=W THEN LET G=U
    IF X>0 THEN IF X=Y THEN IF Y=Z THEN LET G=X
    IF R>0 THEN IF R=U THEN IF U=X THEN LET G=R
    IF S>0 THEN IF S=V THEN IF V=Y THEN LET G=S
    IF T>0 THEN IF T=W THEN IF W=Z THEN LET G=T
    IF R>0 THEN IF R=V THEN IF V=Z THEN LET G=R
    IF T>0 THEN IF T=V THEN IF V=X THEN LET G=T
    RETURN

    REM --- Subroutine to see what piece is in a square
    REM     Inputs:  Q   - the square to check
    REM              R-Z - the contents of the squares
    REM     Outputs: N   - the piece in that square
220 LET N=0
    IF Q=1 THEN LET N=R
    IF Q=2 THEN LET N=S
    IF Q=3 THEN LET N=T
    IF Q=4 THEN LET N=U
    IF Q=5 THEN LET N=V
    IF Q=6 THEN LET N=W
    IF Q=7 THEN LET N=X
    IF Q=8 THEN LET N=Y
    IF Q=9 THEN LET N=Z
    RETURN

    REM --- Subroutine to put a piece in a square
    REM     Inputs:  P   - the player whose piece should be placed
    REM              M   - the square to put the piece in
    REM     Changes: R-Z - the contents of the squares
240 IF M=1 THEN LET R=P
    IF M=2 THEN LET S=P
    IF M=3 THEN LET T=P
    IF M=4 THEN LET U=P
    IF M=5 THEN LET V=P
    IF M=6 THEN LET W=P
    IF M=7 THEN LET X=P
    IF M=8 THEN LET Y=P
    IF M=9 THEN LET Z=P
    RETURN


function numdiv( n as uinteger ) as uinteger
    dim as uinteger c = 2
    for i as uinteger = 2 to (n+1)\2
        if n mod i = 0 then c += 1
    next i
    return c
end function

function istau( n as uinteger ) as boolean
    if n = 1 then return true
    if n mod numdiv(n) = 0 then return true else return false
end function

dim as uinteger c = 0, i=1
while c < 100
    if istau(i) then
        print i,
        c += 1
        if c mod 10 = 0 then print
    end if
    i += 1
wend


tau = {|x| x mod length[allFactors[x]] == 0}
println[formatTable[columnize[first[select[count[1], tau], 100], 10], "right"]]


package main

import "fmt"

func countDivisors(n int) int {
    count := 0
    i := 1
    k := 2
    if n%2 == 0 {
        k = 1
    }
    for i*i <= n {
        if n%i == 0 {
            count++
            j := n / i
            if j != i {
                count++
            }
        }
        i += k
    }
    return count
}

func main() {
    fmt.Println("The first 100 tau numbers are:")
    count := 0
    i := 1
    for count < 100 {
        tf := countDivisors(i)
        if i%tf == 0 {
            fmt.Printf("%4d  ", i)
            count++
            if count%10 == 0 {
                fmt.Println()
            }
        }
        i++
    }
}


shared void run() {

    void printKelvinConversions(Float kelvin) {
        value celsius = kelvin - 273.15;
        value rankine = kelvin * 9.0 / 5.0;
        value fahrenheit = rankine - 459.67;

        print("Kelvin:     ``formatFloat(kelvin, 2, 2)``
               Celsius:    ``formatFloat(celsius, 2, 2)``
               Fahrenheit: ``formatFloat(fahrenheit, 2, 2)``
               Rankine:    ``formatFloat(rankine, 2, 2)``");
    }

    printKelvinConversions(21.0);

}


(defn to-celsius [k]
  (- k 273.15))
(defn to-fahrenheit [k]
  (- (* k 1.8) 459.67))
(defn to-rankine [k]
  (* k 1.8))

(defn temperature-conversion [k]
  (if (number? k)
    (format "Celsius: %.2f Fahrenheit: %.2f Rankine: %.2f"
      (to-celsius k) (to-fahrenheit k) (to-rankine k))
    (format "Error: Non-numeric value entered.")))


#!/usr/bin/env bash
# play tic-tac-toe
main() {
  local play_again=1
  while (( play_again )); do
    local board=(1 2 3 4 5 6 7 8 9) tokens=(X O)
    show_board "${board[@]}"
    # player colors: computer is red, human is green
    local computer=31 human=32
    if (( RANDOM % 2 )); then
      players=(computer human)
      colors=($computer $human)
      printf 'I go first!\n'
    else
      players=(human computer)
      colors=($human $computer)
      printf 'You go first!\n'
    fi
    local token winner
    local -i turn=0
    while ! winner=$(winner "${board[@]}"); do
      token=${tokens[turn%2]}
      case "${players[turn%2]}" in
        human) board=($(human_turn "$token" "${board[@]}"));;
        computer) board=($(computer_turn "$token" "${board[@]}"));;
        *) printf 'Unknown player "%s"\n' "${players[turn%2]}"; exit 1;;
      esac
      show_board "${board[@]}" | sed -e "s/${tokens[0]}/"$'\e['"${colors[0]}"$'m&\e[0m/g' \
                                     -e "s/${tokens[1]}/"$'\e['"${colors[1]}"$'m&\e[0m/g'

      (( turn=turn+1 ))
   done
   case "$winner${players[0]}" in
     Ohuman|Xcomputer) printf 'I win!\n';;
     Xhuman|Ocomputer) printf 'You win!\n';;
     cat*) printf 'The cat wins!\n';;
   esac
   yorn 'Play again'
   play_again=$(( ! $? ))
 done
}

show_board() {
  printf '\n'
  printf '%s %s %s\n' "[email protected]"
  printf '\n'
}

winner() {
  local board=("[email protected]") i j k
  local lines=("0 1 2" "0 3 6" "0 4 8" "1 4 7"
               "2 4 6" "2 5 8" "3 4 5" "6 7 8")
  local line i j k
  for line in "${lines[@]}"; do
    read i j k <<<"$line"
    local token=${board[i]}
    if [[ "${board[j]}" == $token && "${board[k]}" == $token ]]; then
      printf '%s\n' "$token"
      return 0
    fi
  done
  case "${board[*]}" in
    *[1-9]*) return 1;;
    *) printf 'cat\n'; return 0;;
  esac
}

human_turn() {
  local token=$1
  shift
  local board=("[email protected]")
  local n=0
  while (( n < 1 || n > 9 )) || [[ "${board[n-1]}" != $n ]]; do
    printf 'Enter space number: ' "$n"  "${board[n-1]}" >/dev/tty
    read n </dev/tty >/dev/tty 2>&1
  done
  board[n-1]=$token
  printf '%s\n' "${board[@]}"
}

computer_turn() {
  local token=$1
  shift
  local board=("[email protected]")
  local i=0 blanks=() choice
  for (( i=0; i<9; ++i )); do
    if [[ "${board[i]}" == [1-9] ]]; then
      blanks+=("$i")
    fi
  done
  choice=${blanks[RANDOM % ${#blanks[@]}]}
  board[choice]=$token
  printf '%s\n' "${board[@]}"
}

yorn() {
  local yorn=
  while [[ $yorn != [Yy]* && $yorn != [Nn]* ]]; do
    printf '%s? ' "$*"
    read yorn
  done
  [[ $yorn == [Yy]* ]]
}

main "[email protected]"


tau :: Integral a => a -> a
tau n | n <= 0 = error "Not a positive integer"
tau n = go 0 (1, 1)
    where
    yo i = (i, i * i)
    go r (i, ii)
        | n < ii = r
        | n == ii = r + 1
        | 0 == mod n i = go (r + 2) (yo $ i + 1)
        | otherwise = go r (yo $ i + 1)

isTau :: Integral a => a -> Bool
isTau n = 0 == mod n (tau n)

main = print . take 100 . filter isTau $ [1..]


   tau_number=: 0 = (|~ [email protected]>)
   tally_factors=: [: */ 1 + _&q:


public class Tau {
    private static long divisorCount(long n) {
        long total = 1;
        // Deal with powers of 2 first
        for (; (n & 1) == 0; n >>= 1) {
            ++total;
        }
        // Odd prime factors up to the square root
        for (long p = 3; p * p <= n; p += 2) {
            long count = 1;
            for (; n % p == 0; n /= p) {
                ++count;
            }
            total *= count;
        }
        // If n > 1 then it's prime
        if (n > 1) {
            total *= 2;
        }
        return total;
    }

    public static void main(String[] args) {
        final long limit = 100;
        System.out.printf("The first %d tau numbers are:%n", limit);
        long count = 0;
        for (long n = 1; count < limit; ++n) {
            if (n % divisorCount(n) == 0) {
                System.out.printf("%6d", n);
                ++count;
                if (count % 10 == 0) {
                    System.out.println();
                }
            }
        }
    }
}


kelvin = proc (k: real) returns (real)
    return(k)
end kelvin

celsius = proc (k: real) returns (real)
    return(k - 273.15)
end celsius

rankine = proc (k: real) returns (real)
    return(k * 9./5.)
end rankine

fahrenheit = proc (k: real) returns (real)
    return(rankine(k) - 459.67)
end fahrenheit

conv = struct[letter: char, func: proctype (real) returns (real)]

convs = sequence[conv]$[
    conv${letter: 'K', func: kelvin},
    conv${letter: 'C', func: celsius},
    conv${letter: 'F', func: fahrenheit},
    conv${letter: 'R', func: rankine}
]

start_up = proc ()
    pi: stream := stream$primary_input()
    po: stream := stream$primary_output()

    stream$puts(po, "Enter temperature in Kelvin: ")
    k: real := real$parse(stream$getl(pi))

    for c: conv in sequence[conv]$elements(convs) do
        stream$putc(po, c.letter)
        stream$puts(po, "  ")
        stream$putl(po, f_form(c.func(k), 6, 2))
    end
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. temp-conversion.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       78  Kelvin-Rankine-Ratio    VALUE 0.5556. *> 5 / 9 to 4 d.p.
       78  Kelvin-Celsius-Diff     VALUE 273.15.
       78  Rankine-Fahrenheit-Diff VALUE 459.67.

       01  temp-kelvin             PIC S9(8)V99.
       01  temp-rankine            PIC S9(8)V99.

       01  kelvin                  PIC -(7)9.99.
       01  celsius                 PIC -(7)9.99.
       01  rankine                 PIC -(7)9.99.
       01  fahrenheit              PIC -(7)9.99.

       PROCEDURE DIVISION.
           DISPLAY "Enter a temperature in Kelvin to convert: " NO ADVANCING
           ACCEPT temp-kelvin

           MOVE temp-kelvin TO kelvin
           DISPLAY "K " kelvin

           SUBTRACT Kelvin-Celsius-Diff FROM temp-kelvin GIVING celsius
           DISPLAY "C " celsius

           DIVIDE temp-kelvin BY Kelvin-Rankine-Ratio
               GIVING temp-rankine, rankine
           SUBTRACT Rankine-Fahrenheit-Diff FROM temp-rankine GIVING fahrenheit

           DISPLAY "F " fahrenheit
           DISPLAY "R " rankine

           GOBACK
           .


Option Explicit

Private Lines(1 To 3, 1 To 3) As String
Private Nb As Byte, player As Byte
Private GameWin As Boolean, GameOver As Boolean

Sub Main_TicTacToe()
Dim p As String

    InitLines
    printLines Nb
    Do
        p = WhoPlay
        Debug.Print p & " play"
        If p = "Human" Then
            Call HumanPlay
            GameWin = IsWinner("X")
        Else
            Call ComputerPlay
            GameWin = IsWinner("O")
        End If
        If Not GameWin Then GameOver = IsEnd
    Loop Until GameWin Or GameOver
    If Not GameOver Then
        Debug.Print p & " Win !"
    Else
        Debug.Print "Game Over!"
    End If
End Sub

Sub InitLines(Optional S As String)
Dim i As Byte, j As Byte
    Nb = 0: player = 0
    For i = LBound(Lines, 1) To UBound(Lines, 1)
        For j = LBound(Lines, 2) To UBound(Lines, 2)
            Lines(i, j) = "#"
        Next j
    Next i
End Sub

Sub printLines(Nb As Byte)
Dim i As Byte, j As Byte, strT As String
    Debug.Print "Loop " & Nb
    For i = LBound(Lines, 1) To UBound(Lines, 1)
        For j = LBound(Lines, 2) To UBound(Lines, 2)
            strT = strT & Lines(i, j)
        Next j
        Debug.Print strT
        strT = vbNullString
    Next i
End Sub

Function WhoPlay(Optional S As String) As String
    If player = 0 Then
        player = 1
        WhoPlay = "Human"
    Else
        player = 0
        WhoPlay = "Computer"
    End If
End Function

Sub HumanPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean

    Do
        L = Application.InputBox("Choose the row", "Numeric only", Type:=1)
        If L > 0 And L < 4 Then
            C = Application.InputBox("Choose the column", "Numeric only", Type:=1)
            If C > 0 And C < 4 Then
                If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
                    Lines(L, C) = "X"
                    Nb = Nb + 1
                    printLines Nb
                    GoodPlay = True
                End If
            End If
        End If
    Loop Until GoodPlay
End Sub

Sub ComputerPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean

    Randomize Timer
    Do
        L = Int((Rnd * 3) + 1)
        C = Int((Rnd * 3) + 1)
        If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
            Lines(L, C) = "O"
            Nb = Nb + 1
            printLines Nb
            GoodPlay = True
        End If
    Loop Until GoodPlay
End Sub

Function IsWinner(S As String) As Boolean
Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String

    Ch = String(UBound(Lines, 1), S)
    'check lines & columns
    For i = LBound(Lines, 1) To UBound(Lines, 1)
        For j = LBound(Lines, 2) To UBound(Lines, 2)
            strTL = strTL & Lines(i, j)
            strTC = strTC & Lines(j, i)
        Next j
        If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For
        strTL = vbNullString: strTC = vbNullString
    Next i
    'check diagonales
    strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3)
    strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1)
    If strTL = Ch Or strTC = Ch Then IsWinner = True
End Function

Function IsEnd() As Boolean
Dim i As Byte, j As Byte

    For i = LBound(Lines, 1) To UBound(Lines, 1)
        For j = LBound(Lines, 2) To UBound(Lines, 2)
            If Lines(i, j) = "#" Then Exit Function
        Next j
    Next i
    IsEnd = True
End Function


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

# For pretty-printing
def nwise($n):
  def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
  n;

def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;


using Primes

function numfactors(n)
    f = [one(n)]
    for (p, e) in factor(n)
        f = reduce(vcat, [f * p^j for j in 1:e], init = f)
    end
    length(f)
end

function taunumbers(toget = 100)
    n = 0
    for i in 1:100000000
        if i % numfactors(i) == 0
            n += 1
            print(rpad(i, 5), n % 20 == 0 ? " \n" : "")
            n == toget && break
        end
    end
end

taunumbers()


function divisor_count(n)
    local total = 1

    -- Deal with powers of 2 first
    while (n & 1) == 0 do
        total = total + 1
        n = n >> 1
    end
    -- Odd prime factors up to the square root
    local p = 3
    while p * p <= n do
        local count = 1
        while n % p == 0 do
            count = count + 1
            n = math.floor(n / p)
        end
        total = total * count
        p = p + 2
    end
    -- If n > 1 then it's prime
    if n > 1 then
        total = total * 2
    end
    return total
end

local limit = 100
local count = 0
print("The first " .. limit .. " tau numbers are:")
local n = 1
while count < limit do
    if n % divisor_count(n) == 0 then
        io.write(string.format("%6d", n))
        count = count + 1
        if count % 10 == 0 then
            print()
        end
    end
    n = n + 1
end


            NORMAL MODE IS INTEGER

            INTERNAL FUNCTION(N)
                ENTRY TO POSDIV.
                COUNT = 1
                THROUGH DIV, FOR I=2, 1, I.G.N
DIV             WHENEVER N/I*I.E.N, COUNT = COUNT+1
                FUNCTION RETURN COUNT
            END OF FUNCTION

            SEEN=0
            THROUGH TAU, FOR X=1, 1, SEEN.GE.100
            DIVS=POSDIV.(X)
            WHENEVER X/DIVS*DIVS.E.X
                PRINT FORMAT NUM,X
                SEEN = SEEN+1
TAU         END OF CONDITIONAL

            VECTOR VALUES NUM = $I4*$
            END OF PROGRAM


Take[Select[Range[10000], Divisible[#, Length[Divisors[#]]] &], 100]


(defun to-celsius (k)
  (- k 273.15))
(defun to-fahrenheit (k)
  (- (* k 1.8) 459.67))
(defun to-rankine (k)
  (* k 1.8))

(defun temperature-conversion ()
  (let ((k (read)))
    (if (numberp k)
      (format t "Celsius: ~d~%Fahrenheit: ~d~%Rankine: ~d~%"
        (to-celsius k) (to-fahrenheit k) (to-rankine k))
      (format t "Error: Non-numeric value entered."))))


double kelvinToCelsius(in double k) pure nothrow @safe {
    return k - 273.15;
}

double kelvinToFahrenheit(in double k) pure nothrow @safe {
    return k * 1.8 - 459.67;
}

double kelvinToRankine(in double k) pure nothrow @safe {
    return k * 1.8;
}

unittest {
    import std.math: approxEqual;
    assert(approxEqual(kelvinToCelsius(21.0), -252.15));
    assert(approxEqual(kelvinToFahrenheit(21.0), -421.87));
    assert(approxEqual(kelvinToRankine(21.0), 37.8));
}

void main(string[] args) {
    import std.stdio, std.conv, std.string;

    if (args.length == 2 && isNumeric(args[1])) {
        immutable kelvin = to!double(args[1]);
        if (kelvin >= 0) {
            writefln("K  %2.2f", kelvin);
            writefln("C  %2.2f", kelvinToCelsius(kelvin));
            writefln("F  %2.2f", kelvinToFahrenheit(kelvin));
            writefln("R  %2.2f", kelvinToRankine(kelvin));
        } else
            writefln("%2.2f K is below absolute zero", kelvin);
    }
}