Data update

This commit is contained in:
Ingy döt Net 2026-02-01 16:33:20 -08:00
parent 5150844a7d
commit 4bb20c9b71
7735 changed files with 38060 additions and 199180 deletions

View file

@ -1,5 +1,5 @@
V doors = [0B] * 100
L(i) 100
L(i) 0.<100
L(j) (i .< 100).step(i + 1)
doors[j] = !doors[j]
print(Door (i + 1): (I doors[i] {open} E close))

View file

@ -1,58 +1,45 @@
;------------------------------------------------------
; useful equates
;------------------------------------------------------
wboot equ 0 ; jump to BIOS warm boot routine
bdos equ 5 ; BDOS entry
conout equ 2 ; BDOS console output function
bdos equ 5 ; BDOS entry
conout equ 2 ; BDOS console output function
putstr equ 9 ; BDOS print string function
ndoors equ 100
ndoors equ 100 ; number of doors
;
org 100h
lxi sp,stack ; set our own stack
lxi d,signon ; print signon message
lxi d,intro ; print introductory message
mvi c,putstr
call bdos
call bdos
;
; generate sequence of squares from 1 to specified limit
; generate sequence of squares to specified limit
; HL holds the current square
; DE holds the increment
; BC holds the negative of the limit
;
gensqr:
lxi h,1 ; starting value of square
gensqr: lxi h,1 ; starting value of square
lxi d,3 ; starting value of increment
lxi b,ndoors+1
sqrs2:
call cmpbchl ; have we exceeded the limit?
jnc done ; we're finished
call putdec ; otherwise print current square
mvi a,' ' ; separate with a space
call putchr
dad d ; square += incrememnt
inx d ; increment += 2
lxi b,-ndoors
sqrs2: call putdec ; otherwise print current square
mvi a,' ' ; separate with a space
call putchr
push h ; have we reached the limit?
dad b
pop h
jc done ; CY if HL > limit
dad d ; square += incrememnt
inx d ; increment += 2
inx d
jmp sqrs2 ; repeat until finished
jmp sqrs2 ; repeat until finished
;
done: jmp wboot ; exit to command prompt
;
;---------------------------------------------------
; 16-bit unsigned comparison of HL and BC
; if HL = BC then Z flag set
; if HL < BC then CY flag set (NC if HL >= BC)
;------------------------------------------------------
cmpbchl:
mov a,h
cmp b
rnz
mov a,l
cmp c
ret
done: jmp wboot ; exit with warm boot
;---------------------------------------------------
; console output of char in A register
;---------------------------------------------------
putchr: push h
push d
push b
putchr: push h
push d
push b
mov e,a
mvi c,conout
call bdos
call bdos
pop b
pop d
pop h
@ -61,9 +48,9 @@ putchr: push h
; Output decimal number to console
; HL holds 16-bit unsigned binary number to print
;---------------------------------------------------
putdec: push b
push d
push h
putdec: push b
push d
push h
lxi b,-10
lxi d,-1
putdec2:
@ -78,7 +65,7 @@ putdec2:
cnz putdec ; recursive call
mov a,e
adi '0'
call putchr
call putchr
pop h
pop d
pop b
@ -86,7 +73,7 @@ putdec2:
;---------------------------------------------------
; data area and stack
;---------------------------------------------------
signon: db 'The open doors are: $'
intro: db 'The open doors are: $'
stack equ $+128 ; 64-level stack
;
end

View file

@ -1,22 +0,0 @@
with Ada.Text_Io; use Ada.Text_Io;
procedure Doors is
type Door_State is (Closed, Open);
type Door_List is array(Positive range 1..100) of Door_State;
The_Doors : Door_List := (others => Closed);
begin
for I in 1..100 loop
for J in The_Doors'range loop
if J mod I = 0 then
if The_Doors(J) = Closed then
The_Doors(J) := Open;
else
The_Doors(J) := Closed;
end if;
end if;
end loop;
end loop;
for I in The_Doors'range loop
Put_Line(Integer'Image(I) & " is " & Door_State'Image(The_Doors(I)));
end loop;
end Doors;

View file

@ -1,16 +0,0 @@
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
procedure Doors_Optimized is
Num : Float;
begin
for I in 1..100 loop
Num := Sqrt(Float(I));
Put(Integer'Image(I) & " is ");
if Float'Floor(Num) = Num then
Put_Line("Opened");
else
Put_Line("Closed");
end if;
end loop;
end Doors_Optimized;

View file

@ -1,19 +0,0 @@
# find the first few squares via the unoptimised door flipping method
scope
local doorMax := 100;
local door;
create register door( doorMax );
# set all doors to closed
for i to doorMax do door[ i ] := false od;
# repeatedly flip the doors
for i to doorMax do
for j from i to doorMax by i do door[ j ] := not door[ j ] od
od;
# display the results
for i to doorMax do if door[ i ] then write( " ", i ) fi od; print()
epocs

View file

@ -1,17 +0,0 @@
#include <array.au3>
$doors = 100
;door array, 0 = closed, 1 = open
Local $door[$doors +1]
For $ii = 1 To $doors
For $i = $ii To $doors Step $ii
$door[$i] = Not $door[$i]
next
Next
;display to screen
For $i = 1 To $doors
ConsoleWrite (Number($door[$i])& " ")
If Mod($i,10) = 0 Then ConsoleWrite(@CRLF)
Next

View file

@ -1,18 +0,0 @@
(defun CreateDoors (n / doors)
(repeat n
(setq doors (cons nil doors))
)
)
(defun Doors (doors / cnt)
(setq cnt 0)
(mapcar
'(lambda (d)
(zerop (rem (sqrt (setq cnt (1+ cnt))) 1))
)
doors
)
)
> (Doors (CreateDoors 100))
(T nil nil T nil nil nil nil T nil nil nil nil nil nil T nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil)

View file

@ -1,33 +0,0 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. 100Doors.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Current-n PIC 9(3).
01 StepSize PIC 9(3).
01 DoorTable.
02 Doors PIC 9(1) OCCURS 100 TIMES.
88 ClosedDoor VALUE ZERO.
01 Idx PIC 9(3).
PROCEDURE DIVISION.
Begin.
INITIALIZE DoorTable
PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100
PERFORM VARYING Current-n FROM StepSize BY StepSize
UNTIL Current-n > 100
SUBTRACT Doors (Current-n) FROM 1 GIVING Doors (Current-n)
END-PERFORM
END-PERFORM
PERFORM VARYING Idx FROM 1 BY 1
UNTIL Idx > 100
IF ClosedDoor (Idx)
DISPLAY Idx " is closed."
ELSE
DISPLAY Idx " is open."
END-IF
END-PERFORM
STOP RUN
.

View file

@ -1,26 +0,0 @@
Require Import List.
Fixpoint rep {A} (a : A) n :=
match n with
| O => nil
| S n' => a::(rep a n')
end.
Fixpoint flip (l : list bool) (n k : nat) : list bool :=
match l with
| nil => nil
| cons h t => match k with
| O => (negb h) :: (flip t n n)
| S k' => h :: (flip t n k')
end
end.
Definition flipeach l n := flip l n n.
Fixpoint flipwhile l n :=
match n with
| O => flipeach l 0
| S n' => flipwhile (flipeach l (S n')) n'
end.
Definition prison cells := flipwhile (rep false cells) cells.

View file

@ -1,13 +0,0 @@
Require Import List.
Fixpoint prisoo' nd n k accu :=
match nd with
| O => rev accu
| S nd' => let ra := match k with
| O => (true, S n, (n + n))
| S k' => (false, n, k')
end in
prisoo' nd' (snd (fst ra)) (snd ra) ((fst (fst ra))::accu)
end.
Definition prisoo cells := prisoo' cells 1 0 nil.

View file

@ -1 +0,0 @@
Goal prison 100 = prisoo 100. compute. reflexivity. Qed.

View file

@ -1 +0,0 @@
Goal forall n, prison n = prisoo n. Abort.

View file

@ -1,7 +1,7 @@
import system'routines;
import extensions;
public program()
public Program()
{
var Doors := Array.allocate(100).populate::(n=>false);
for(int i := 0; i < 100; i++)

View file

@ -1,83 +0,0 @@
(defun create-doors ()
"Returns a list of closed doors
Each door only has two status: open or closed.
If a door is closed it has the value 0, if it's open it has the value 1."
(let ((return_value '(0))
;; There is already a door in the return_value, so k starts at 1
;; otherwise we would need to compare k against 99 and not 100 in
;; the while loop
(k 1))
(while (< k 100)
(setq return_value (cons 0 return_value))
(setq k (+ 1 k)))
return_value))
(defun toggle-single-door (doors)
"Toggle the stat of the door at the `car' position of the DOORS list
DOORS is a list of integers with either the value 0 or 1 and it represents
a row of doors.
Returns a list where the `car' of the list has it's value toggled (if open
it becomes closed, if closed it becomes open)."
(if (= (car doors) 1)
(cons 0 (cdr doors))
(cons 1 (cdr doors))))
(defun toggle-doors (doors step original-step)
"Step through all elements of the doors' list and toggle a door when step is 1
DOORS is a list of integers with either the value 0 or 1 and it represents
a row of doors.
STEP is the number of doors we still need to transverse before we arrive
at a door that has to be toggled.
ORIGINAL-STEP is the value of the argument step when this function is
called for the first time.
Returns a list of doors"
(cond ((null doors)
'())
((= step 1)
(cons (car (toggle-single-door doors))
(toggle-doors (cdr doors) original-step original-step)))
(t
(cons (car doors)
(toggle-doors (cdr doors) (- step 1) original-step)))))
(defun main-program ()
"The main loop for the program"
(let ((doors_list (create-doors))
(k 1)
;; We need to define max-specpdl-size and max-specpdl-size to big
;; numbers otherwise the loop reaches the max recursion depth and
;; throws an error.
;; If you want more information about these variables, press Ctrl
;; and h at the same time and then press v and then type the name
;; of the variable that you want to read the documentation.
(max-specpdl-size 5000)
(max-lisp-eval-depth 2000))
(while (< k 101)
(setq doors_list (toggle-doors doors_list k k))
(setq k (+ 1 k)))
doors_list))
(defun print-doors (doors)
"This function prints the values of the doors into the current buffer.
DOORS is a list of integers with either the value 0 or 1 and it represents
a row of doors.
"
;; As in the main-program function, we need to set the variable
;; max-lisp-eval-depth to a big number so it doesn't reach max recursion
;; depth.
(let ((max-lisp-eval-depth 5000))
(unless (null doors)
(insert (int-to-string (car doors)))
(print-doors (cdr doors)))))
;; Returns a list with the final solution
(main-program)
;; Print the final solution on the buffer
(print-doors (main-program))

View file

@ -1,16 +0,0 @@
(defun one-hundred-doors(initial-state)
"Turn doors in INITIAL-STATE according to 100 Doors problem."
(interactive "nEnter initial doors' state (as a number): ")
(cl-loop for x from 1 to 100
do (cl-loop for y from (1- x) to 99 by x
do (setq initial-state (logxor initial-state (ash 1 y)))))
(let ((counter 1)
(open-doors nil))
(while (> initial-state 0)
(when (eq (mod initial-state 2) 1)
(push counter open-doors))
(cl-incf counter)
(setq initial-state (/ initial-state 2)))
(message "Open doors are %s" (reverse open-doors))))
(one-hundred-doors 0)

View file

@ -1,23 +0,0 @@
-- doors.ex
include std/console.e
sequence doors
doors = repeat( 0, 100 ) -- 1 to 100, initialised to false
for pass = 1 to 100 do
for door = pass to 100 by pass do
--printf( 1, "%d", doors[door] )
--printf( 1, "%d", not doors[door] )
doors[door] = not doors[door]
end for
end for
sequence oc
for i = 1 to 100 do
if doors[i] then
oc = "open"
else
oc = "closed"
end if
printf( 1, "door %d is %s\n", { i, oc } )
end for

View file

@ -1,23 +0,0 @@
class Main
{
static public function main()
{
findOpenDoors( 100 );
}
static function findOpenDoors( n : Int )
{
var door = [];
for( i in 0...n + 1 ){ door[ i ] = false; }
for( i in 1...n + 1 ){
var j = i;
while( j <= n ){
door[ j ] = ! door[ j ];
j += i;
}
}
for( i in 1...n + 1 ){
if( door[ i ] ){ Sys.print( ' $i' ); }
}
}
}

View file

@ -1,18 +0,0 @@
class RosettaDemo
{
static public function main()
{
findOpenLockers(100);
}
static function findOpenLockers(n : Int)
{
var i = 1;
while((i*i) <= n)
{
Sys.println(i*i);
i++;
}
}
}

View file

@ -2,7 +2,7 @@
(for i (range 1 101)
i2 (range (dec i) 100 i)
(var! doors (set-at [i2] (! (i2 doors))))
(var! doors (set-at [i2] (not (i2 doors))))
(continue))
(-> (xmap vec doors)

View file

@ -1,9 +1,4 @@
REM Author.....: Eva Broccoli
REM Date.......: 23 May 2025
REM Description: OPL solution for "100 doors" task on https://rosettacode.org
REM Tested with: Psion Series 3a & Series 5
REM Contact....: eva.klassen@kittymail.com
REM https://github.com/Eva-Broccoli/OPL-Rosetta-Code/blob/main/A100door.opl
PROC main:
LOCAL door%(100),i%,j%
i%=1

View file

@ -1,24 +1,22 @@
package main
package doors
import "core:fmt"
main :: proc() {
using fmt
doors: [100]bool
Door_State :: enum {Closed, Open}
for every_n := 1; every_n < len(doors); every_n += 1 {
i := every_n - 1
for true {
if i >= len(doors) do break
doors := [?]Door_State { 0..<100 = .Closed }
doors[i] = !doors[i]
for i in 1..=100 {
for j := i-1; j < 100; j += i {
if doors[j] == .Closed {
doors[j] = .Open
} else {
doors[j] = .Closed
}
}
}
for state, i in doors {
println("Door: ",int(i+1)," -> ",state)
}
i += every_n
}
}
for &door, i in doors {
if door do fmt.printf("%d ", i + 1)
}
}

View file

@ -1,7 +1,6 @@
package main
import "core:fmt"
import "core:math"
main :: proc() {
using fmt
@ -11,12 +10,15 @@ main :: proc() {
doors := [?]Door_State { 0..<100 = .Closed }
for i in 1..=100 {
res := math.sqrt_f64( f64(i) )
if math.mod_f64( res, 1) == 0 {
doors[i-1] = .Open
} else {
doors[i-1] = .Closed
}
println("Door: ", i, " -> ", doors[i-1])
for j := i-1; j < 100; j += i {
if doors[j] == .Closed {
doors[j] = .Open
} else {
doors[j] = .Closed
}
}
}
for state, i in doors {
println("Door: ",int(i+1)," -> ",state)
}
}

View file

@ -1,14 +0,0 @@
$doors = @(0..99)
for($i=0; $i -lt 100; $i++) {
$doors[$i] = 0 # start with all doors closed
}
for($i=0; $i -lt 100; $i++) {
$step = $i + 1
for($j=$i; $j -lt 100; $j = $j + $step) {
$doors[$j] = $doors[$j] -bxor 1
}
}
foreach($doornum in 1..100) {
if($doors[($doornum-1)] -eq $true) {"$doornum open"}
else {"$doornum closed"}
}

View file

@ -1,37 +0,0 @@
function Get-DoorState($NumberOfDoors)
{
begin
{
$Doors = @()
$Multiple = 1
}
process
{
for ($i = 1; $i -le $NumberOfDoors; $i++)
{
$Door = [pscustomobject]@{
Name = $i
Open = $false
}
$Doors += $Door
}
While ($Multiple -le $NumberOfDoors)
{
Foreach ($Door in $Doors)
{
if ($Door.name % $Multiple -eq 0)
{
If ($Door.open -eq $False){$Door.open = $True}
Else {$Door.open = $False}
}
}
$Multiple++
}
}
end {$Doors}
}

View file

@ -1,2 +0,0 @@
$doors = 1..100 | ForEach-Object {0}
1..100 | ForEach-Object { $a=$_;1..100 | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1 }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } }

View file

@ -1,3 +0,0 @@
$doors = 1..100 | ForEach-Object {0}
$visited = 1..100
1..100 | ForEach-Object { $a=$_;$visited[0..([math]::floor(100/$a)-1)] | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1;$visited[$_/$a-1]+=($_/$a) }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } }

View file

@ -1,3 +0,0 @@
1..100|foreach-object {$pipe += "toggle $_ |"} -begin {$pipe=""}
filter toggle($pass) {$_.door = $_.door -xor !($_.index % $pass);$_}
invoke-expression "1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host"

View file

@ -1,6 +0,0 @@
Workflow Calc-Doors {
Foreach parallel ($number in 1..100) {
"Door " + $number.ToString("0000") + ": " + @{$true="Closed";$false="Open"}[([Math]::pow($number, 0.5)%1) -ne 0]
}
}
Calc-Doors | sort

View file

@ -1 +0,0 @@
1..10|%{"Door "+ $_*$_ + " is open"}

View file

@ -1,6 +1,2 @@
for i in range(1, 101):
if i**0.5 % 1:
state='closed'
else:
state='open'
print("Door {}:{}".format(i, state))
print(f"Door {i}:{"closed" if i**0.5 % 1 else "open"}")

View file

@ -1 +1 @@
for i in range(1,11): print("Door %s is open" % i**2)
for i in range(1,11): print(f"Door {i**2} is open")

View file

@ -1,5 +0,0 @@
doors: array/initial 100 'closed
repeat i 100 [
door: at doors i
forskip door i [change door either 'open = first door ['closed] ['open]]
]

View file

@ -1,26 +0,0 @@
;; Create a bitset with capacity for 100 bits (representing 100 doors)
;; Each bit represents a door state: 0 = closed, 1 = open
doors: make bitset! 100
;; Outer loop: Make 100 passes (i = 1 to 100)
repeat i 100 [
;; Inner loop: Check each door position (j = 1 to 100)
repeat j 100 [
;; If door j index is divisible by pass number i (no remainder)
if zero? (j // i) [
;; Toggle the door's bit:
;; doors/:j accesses door j in the bitset
;; 'not' flips the bit value (0 -> 1, 1 -> 0)
doors/:j: not doors/:j
]
]
]
;; Final loop: Check which doors are open, print their numbers
repeat i 100 [
;; If door i's bit is set (open)
if doors/:i [
;; Print the door's number and that it is open
print ["door" i "is open"]
]
]

View file

@ -1,6 +0,0 @@
;; Loop variable i from 1 to 10 (since 10^2 = 100, covers doors 1 to 100)
repeat i 10 [
;; Print that door number (i squared) is open
;; These are exactly the doors with perfect square numbers: 1, 4, 9, ..., 100
print ["door" (i * i) "is open"]
]

View file

@ -1,21 +0,0 @@
Dim doorIsOpen(100), pass, currentDoor, text
For currentDoor = 0 To 99
doorIsOpen(currentDoor) = False
Next
For pass = 0 To 99
For currentDoor = pass To 99 Step pass + 1
doorIsOpen(currentDoor) = Not doorIsOpen(currentDoor)
Next
Next
For currentDoor = 0 To 99
text = "Door #" & currentDoor + 1 & " is "
If doorIsOpen(currentDoor) Then
text = text & "open."
Else
text = text & "closed."
End If
WScript.Echo(text)
Next

View file

@ -1,28 +0,0 @@
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity DOORS is
port (CLK: in std_logic; OUTPUT: out std_logic_vector(1 to 100));
end DOORS;
architecture Behavioral of DOORS is
begin
process (CLK)
variable TEMP: std_logic_vector(1 to 100);
begin
--setup closed doors
TEMP := (others => '0');
--looping through
for i in 1 to TEMP'length loop
for j in i to TEMP'length loop
if (j mod i) = 0 then
TEMP(j) := not TEMP(j);
end if;
end loop;
end loop;
--assign output
OUTPUT <= TEMP;
end process;
end Behavioral;

View file

@ -1,34 +0,0 @@
LIBRARY ieee;
USE ieee.std_logic_1164.all;
entity doors is
port (
clk : in std_logic;
reset : in std_logic;
door : buffer std_logic_vector(1 to 100)
);
end entity doors;
architecture rtl of doors is
signal step : integer range 1 to 101;
signal addr : integer range 1 to 201;
begin
proc_step: process(clk, reset)
begin
if reset = '1' then
step <= 1;
addr <= 1;
door <= (others => '0');
elsif rising_edge(clk) then
if addr <= 100 then
door(addr) <= not door(addr);
addr <= addr + step;
elsif step <= 100 then
addr <= step + 1;
step <= step + 1;
end if;
end if;
end process;
end;

View file

@ -5,7 +5,7 @@ F play_random(n)
L 0 .< n
random:shuffle(&in_drawer)
V found = 0B
L(prisoner) 100
L(prisoner) 0.<100
found = 0B
L(reveal) random:sample(sampler, 50)
V card = in_drawer[reveal]
@ -24,7 +24,7 @@ F play_optimal(n)
L 0 .< n
random:shuffle(&in_drawer)
V found = 0B
L(prisoner) 100
L(prisoner) 0.<100
V reveal = prisoner
found = 0B
L 50

View file

@ -1,23 +0,0 @@
package Prisoners is
type Win_Percentage is digits 2 range 0.0 .. 100.0;
type Drawers is array (1 .. 100) of Positive;
function Play_Game
(Repetitions : in Positive;
Strategy : not null access function
(Cupboard : in Drawers; Max_Prisoners : Integer;
Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)
return Win_Percentage;
-- Play the game with a specified number of repetitions, the chosen strategy
-- is passed to this function
function Optimal_Strategy
(Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;
Prisoner_Number : Integer) return Boolean;
function Random_Strategy
(Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;
Prisoner_Number : Integer) return Boolean;
end Prisoners;

View file

@ -1,128 +0,0 @@
pragma Ada_2012;
with Ada.Numerics.Discrete_Random;
with Ada.Text_IO; use Ada.Text_IO;
package body Prisoners is
subtype Drawer_Range is Positive range 1 .. 100;
package Random_Drawer is new Ada.Numerics.Discrete_Random (Drawer_Range);
use Random_Drawer;
-- Helper procedures to initialise and shuffle the drawers
procedure Swap (A, B : Positive; Cupboard : in out Drawers) is
Temp : Positive;
begin
Temp := Cupboard (B);
Cupboard (B) := Cupboard (A);
Cupboard (A) := Temp;
end Swap;
procedure Shuffle (Cupboard : in out Drawers) is
G : Generator;
begin
Reset (G);
for I in Cupboard'Range loop
Swap (I, Random (G), Cupboard);
end loop;
end Shuffle;
procedure Initialise_Drawers (Cupboard : in out Drawers) is
begin
for I in Cupboard'Range loop
Cupboard (I) := I;
end loop;
Shuffle (Cupboard);
end Initialise_Drawers;
-- The two strategies for playing the game
function Optimal_Strategy
(Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;
Prisoner_Number : Integer) return Boolean
is
Current_Card : Positive;
begin
Current_Card := Cupboard (Prisoner_Number);
if Current_Card = Prisoner_Number then
return True;
else
for I in Integer range 1 .. Max_Attempts loop
Current_Card := Cupboard (Current_Card);
if Current_Card = Prisoner_Number then
return True;
end if;
end loop;
end if;
return False;
end Optimal_Strategy;
function Random_Strategy
(Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;
Prisoner_Number : Integer) return Boolean
is
Current_Card : Positive;
G : Generator;
begin
Reset (G);
Current_Card := Cupboard (Prisoner_Number);
if Current_Card = Prisoner_Number then
return True;
else
for I in Integer range 1 .. Max_Attempts loop
Current_Card := Cupboard (Random (G));
if Current_Card = Prisoner_Number then
return True;
end if;
end loop;
end if;
return False;
end Random_Strategy;
function Prisoners_Attempts
(Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer;
Strategy : not null access function
(Cupboard : in Drawers; Max_Prisoners : Integer;
Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)
return Boolean
is
begin
for Prisoner_Number in Integer range 1 .. Max_Prisoners loop
if not Strategy
(Cupboard, Max_Prisoners, Max_Attempts, Prisoner_Number)
then
return False;
end if;
end loop;
return True;
end Prisoners_Attempts;
-- The function to play the game itself
function Play_Game
(Repetitions : in Positive;
Strategy : not null access function
(Cupboard : in Drawers; Max_Prisoners : Integer;
Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean)
return Win_Percentage
is
Cupboard : Drawers;
Win, Game_Count : Natural := 0;
Number_Of_Prisoners : constant Integer := 100;
Max_Attempts : constant Integer := 50;
begin
loop
Initialise_Drawers (Cupboard);
if Prisoners_Attempts
(Cupboard => Cupboard, Max_Prisoners => Number_Of_Prisoners,
Max_Attempts => Max_Attempts, Strategy => Strategy)
then
Win := Win + 1;
end if;
Game_Count := Game_Count + 1;
exit when Game_Count = Repetitions;
end loop;
return Win_Percentage ((Float (Win) / Float (Repetitions)) * 100.0);
end Play_Game;
end Prisoners;

View file

@ -1,17 +0,0 @@
with Prisoners; use Prisoners;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
Wins : Win_Percentage;
package Win_Percentage_IO is new Float_IO (Win_Percentage);
begin
Wins := Play_Game (100_000, Optimal_Strategy'Access);
Put ("Optimal Strategy = ");
Win_Percentage_IO.Put (Wins, 2, 2, 0);
Put ("%");
New_Line;
Wins := Play_Game (100_000, Random_Strategy'Access);
Put ("Random Strategy = ");
Win_Percentage_IO.Put (Wins, 2, 2, 0);
Put ("%");
end Main;

View file

@ -37,7 +37,7 @@ bool playRandom() {
double exec(const size_t n, bool function() play) {
size_t success = 0;
for (int i = n; i > 0; i--) {
for (size_t i = n; i > 0; i--) {
if (play()) {
success++;
}

View file

@ -1,121 +0,0 @@
### Clear Screen from old Output
Clear-Host
Function RandomOpening ()
{
$Prisoners = 1..100 | Sort-Object {Get-Random}
$Cupboard = 1..100 | Sort-Object {Get-Random}
## Loop for the Prisoners
$Survived = $true
for ($I=1;$I -le 100;$i++)
{
$OpeningListe = 1..100 | Sort-Object {Get-Random}
$Gefunden = $false
## Loop for the trys of every prisoner
for ($X=1;$X -le 50;$X++)
{
$OpenNumber = $OpeningListe[$X]
IF ($Cupboard[$OpenNumber] -eq $Prisoners[$I])
{
$Gefunden = $true
}
## Cancel loop if prisoner found his number (yeah i know, dirty way ^^ )
IF ($Gefunden)
{
$X = 55
}
}
IF ($Gefunden -eq $false)
{
$I = 120
$Survived = $false
}
}
Return $Survived
}
Function StrategyOpening ()
{
$Prisoners = 1..100 | Sort-Object {Get-Random}
$Cupboard = 1..100 | Sort-Object {Get-Random}
$Survived = $true
for ($I=1;$I -le 100;$i++)
{
$Gefunden = $false
$OpeningNumber = $Prisoners[$I-1]
for ($X=1;$X -le 50;$X++)
{
IF ($Cupboard[$OpeningNumber-1] -eq $Prisoners[$I-1])
{
$Gefunden = $true
}
else
{
$OpeningNumber = $Cupboard[$OpeningNumber-1]
}
IF ($Gefunden)
{
$X = 55
}
}
IF ($Gefunden -eq $false)
{
$I = 120
$Survived = $false
}
}
Return $Survived
}
$MaxRounds = 10000
Function TestRandom
{
$WinnerRandom = 0
for ($Round = 1; $Round -le $MaxRounds;$Round++)
{
IF (($Round%1000) -eq 0)
{
$Time = Get-Date
Write-Host "Currently we are at rount $Round at $Time"
}
$Rueckgabewert = RandomOpening
IF ($Rueckgabewert)
{
$WinnerRandom++
}
}
$Prozent = (100/$MaxRounds)*$WinnerRandom
Write-Host "There are $WinnerRandom survivors whit random opening. This is $Prozent percent"
}
Function TestStrategy
{
$WinnersStrategy = 0
for ($Round = 1; $Round -le $MaxRounds;$Round++)
{
IF (($Round%1000) -eq 0)
{
$Time = Get-Date
Write-Host "Currently we are at $Round at $Time"
}
$Rueckgabewert = StrategyOpening
IF ($Rueckgabewert)
{
$WinnersStrategy++
}
}
$Prozent = (100/$MaxRounds)*$WinnersStrategy
Write-Host "There are $WinnersStrategy survivors whit strategic opening. This is $Prozent percent"
}
Function Main ()
{
Clear-Host
TestRandom
TestStrategy
}
Main

View file

@ -1,62 +0,0 @@
option explicit
const npris=100
const ntries=50
const ntests=1000.
dim drawer(100),opened(100),i
for i=1 to npris: drawer(i)=i:next
shuffle drawer
wscript.echo rf(tests(false)/ntests*100,10," ") &" % success for random"
wscript.echo rf(tests(true) /ntests*100,10," ") &" % success for optimal strategy"
function rf(v,n,s) rf=right(string(n,s)& v,n):end function
sub shuffle(d) 'knut's shuffle
dim i,j,t
randomize timer
for i=1 to npris
j=int(rnd()*i+1)
t=d(i):d(i)=d(j):d(j)=t
next
end sub
function tests(strat)
dim cntp,i,j
tests=0
for i=1 to ntests
shuffle drawer
cntp=0
if strat then
for j=1 to npris
if not trystrat(j) then exit for
next
else
for j=1 to npris
if not tryrand(j) then exit for
next
end if
if j>=npris then tests=tests+1
next
end function
function tryrand(pris)
dim i,r
erase opened
for i=1 to ntries
do
r=int(rnd*npris+1)
loop until opened(r)=false
opened(r)=true
if drawer(r)= pris then tryrand=true : exit function
next
tryrand=false
end function
function trystrat(pris)
dim i,r
r=pris
for i=1 to ntries
if drawer(r)= pris then trystrat=true :exit function
r=drawer(r)
next
trystrat=false
end function

View file

@ -1,16 +0,0 @@
generic
Rows, Cols: Positive;
with function Name(N: Natural) return String; -- with Pre => (N < Rows*Cols);
-- Name(0) shall return the name for the empty tile
package Generic_Puzzle is
subtype Row_Type is Positive range 1 .. Rows;
subtype Col_Type is Positive range 1 .. Cols;
type Moves is (Up, Down, Left, Right);
type Move_Arr is array(Moves) of Boolean;
function Get_Point(Row: Row_Type; Col: Col_Type) return String;
function Possible return Move_Arr;
procedure Move(The_Move: Moves);
end Generic_Puzzle;

View file

@ -1,57 +0,0 @@
package body Generic_Puzzle is
Field: array(Row_Type, Col_Type) of Natural;
Current_R: Row_Type := Rows;
Current_C: Col_Type := Cols;
-- invariant: Field(Current_R, Current_C=0)
-- and for all R, C: Field(R, C) < R*C
-- and for all (R, C) /= (RR, CC): Field(R, C) /= Field(RR, CC)
function Get_Point(Row: Row_Type; Col: Col_Type) return String is
(Name(Field(Row, Col)));
function Possible return Move_Arr is
(Up => Current_R > 1, Down => Current_R < Rows,
Left => Current_C > 1, Right => Current_C < Cols);
procedure Move(The_Move: Moves) is
Old_R: Row_Type; Old_C: Col_Type; N: Natural;
begin
if not Possible(The_Move) then
raise Constraint_Error with "attempt to make impossible move";
else
-- remember current row and column
Old_R := Current_R;
Old_C := Current_C;
-- move the virtual cursor to a new position
case The_Move is
when Up => Current_R := Current_R - 1;
when Down => Current_R := Current_R + 1;
when Left => Current_C := Current_C - 1;
when Right => Current_C := Current_C + 1;
end case;
-- swap the tiles on the board
N := Field(Old_R, Old_C);
Field(Old_R, Old_C) := Field(Current_R, Current_C);
Field(Current_R, Current_C) := N;
end if;
end Move;
begin
declare -- set field to its basic setting
N: Positive := 1;
begin
for R in Row_Type loop
for C in Col_Type loop
if (R /= Current_R) or else (C /= Current_C) then
Field(R, C) := N;
N := N + 1;
else
Field(R, C) := 0;
end if;
end loop;
end loop;
end;
end Generic_Puzzle;

View file

@ -1,72 +0,0 @@
with Generic_Puzzle, Ada.Text_IO,
Ada.Numerics.Discrete_Random, Ada.Command_Line;
procedure Puzzle_15 is
function Image(N: Natural) return String is
(if N=0 then " " elsif N < 10 then " " & Integer'Image(N)
else Integer'Image(N));
package Puzzle is new Generic_Puzzle(Rows => 4, Cols => 4, Name => Image);
package Rnd is new Ada.Numerics.Discrete_Random(Puzzle.Moves);
Rand_Gen: Rnd.Generator;
Level: Natural := (if Ada.Command_Line.Argument_Count = 0 then 10
else Natural'Value(Ada.Command_Line.Argument(1)));
Initial_Moves: Natural := (2**(Level/2) + 2**((1+Level)/2))/2;
Texts: constant array(Puzzle.Moves) of String(1..9) :=
("u,U,^,8: ", "d,D,v,2: ", "l,L,<,4: ", "r,R,>,6: ");
Move_Counter: Natural := 0;
Command: Character;
begin
-- randomize board
for I in 1 .. Initial_Moves loop
declare
M: Puzzle.Moves := Rnd.Random(Rand_Gen);
begin
if Puzzle.Possible(M) then
Puzzle.Move(M);
end if;
end;
end loop;
-- read command and perform move
loop
-- Print board
for R in Puzzle.Row_Type loop
for C in Puzzle.Col_Type loop
Ada.Text_IO.Put(Puzzle.Get_Point(R, C));
end loop;
Ada.Text_IO.New_Line;
end loop;
Ada.Text_IO.Get(Command);
begin
case Command is
when 'u' | 'U' | '^' | '8' =>
Ada.Text_IO.Put_Line("Up!"); Puzzle.Move(Puzzle.Up);
when 'd' | 'D' | 'v' | '2' =>
Ada.Text_IO.Put_Line("Down!"); Puzzle.Move(Puzzle.Down);
when 'l' | 'L' | '<' | '4' =>
Ada.Text_IO.Put_Line("Left!"); Puzzle.Move(Puzzle.Left);
when 'r' | 'R' | '>' | '6' =>
Ada.Text_IO.Put_Line("Right!"); Puzzle.Move(Puzzle.Right);
when '!' =>
Ada.Text_IO.Put_Line(Natural'Image(Move_Counter) & " moves!");
exit;
when others =>
raise Constraint_Error with "wrong input";
end case;
Move_Counter := Move_Counter + 1;
exception when Constraint_Error =>
Ada.Text_IO.Put_Line("Possible Moves and Commands:");
for M in Puzzle.Moves loop
if Puzzle.Possible(M) then
Ada.Text_IO.Put(Texts(M) & Puzzle.Moves'Image(M) & " ");
end if;
end loop;
Ada.Text_IO.Put_Line("!: Quit");
end;
end loop;
end Puzzle_15;

View file

@ -1 +0,0 @@
package Puzzle is new Generic_Puzzle(Rows => 3, Cols => 3, Name => Image);

View file

@ -107,17 +107,13 @@ validMovement?: $[
movement :literal
][
pos: game\playerPosition
case [movement]
when? [='up]
-> return (not? in? pos [0..3])
when? [='down]
-> return (not? in? pos [12..15])
when? [='left]
-> return (not? in? pos [0 4 8 12])
when? [='right]
-> return (not? in? pos [3 7 11 15])
else
-> return false
case movement [
'up -> return (not? in? pos [0..3])
'down -> return (not? in? pos [12..15])
'left -> return (not? in? pos [0 4 8 12])
'right -> return (not? in? pos [3 7 11 15])
any -> return false
]
]
@ -130,13 +126,14 @@ validMovement?: $[
;; will be returned the same input as a :string
parseInput: $[inp :string][
lowerInp: lower inp
case [lowerInp]
when? [="w"] -> return 'up
when? [="a"] -> return 'left
when? [="s"] -> return 'down
when? [="d"] -> return 'right
when? [="q"] -> return 'quit
else -> return inp
case lowerInp [
"w" -> return 'up
"a" -> return 'left
"s" -> return 'down
"d" -> return 'right
"q" -> return 'quit
any -> return inp
]
]
;; Moves the player in Game's Table
@ -155,7 +152,7 @@ movePlayer: $[
playerPosition :integer
relativePosition :integer
][
try [
if throws? [
; 'otherPosition is the real index of the 'relativePosition
otherPosition: + playerPosition relativePosition
@ -168,20 +165,16 @@ movePlayer: $[
; -- Updates player's status
game\playerPosition: otherPosition
game\movements: inc game\movements
] else -> panic "'movement didn't checked."
] -> panic "'movement didn't checked."
]
case [movement]
when? [='up]
-> (updateGame game position (neg 4))
when? [='down]
-> (updateGame game position (4))
when? [='left]
-> (updateGame game position (neg 1))
when? [='right]
-> (updateGame game position (1))
else -> panic "'movement didn't checked."
case movement [
'up -> updateGame game position neg 4
'down -> updateGame game position 4
'left -> updateGame game position neg 1
'right -> updateGame game position 1
any -> panic "movement didn't check."
]
]
endGame: $[
@ -209,13 +202,12 @@ runGame: $[sampleTable :block][
-> endGame "Exiting game..."
validInp: validInput? command
if? validInp [
switch validInp [
validMov: validMovement? game command
(validMov)?
-> movePlayer game command
-> printWrongMovement command
] else
-> printWrongInput command
] -> printWrongInput command
if sampleTable = game
-> endGame "Congratulations! You won!"

View file

@ -1,151 +0,0 @@
>>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCOBOL 2.0
identification division.
program-id. fifteen.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01 r pic 9.
01 r-empty pic 9.
01 r-to pic 9.
01 r-from pic 9.
01 c pic 9.
01 c-empty pic 9.
01 c-to pic 9.
01 c-from pic 9.
01 display-table.
03 display-row occurs 4.
05 display-cell occurs 4 pic 99.
01 tile-number pic 99.
01 tile-flags pic x(16).
01 display-move value spaces.
03 tile-id pic 99.
01 row-separator pic x(21) value all '.'.
01 column-separator pic x(3) value ' . '.
01 inversions pic 99.
01 current-tile pic 99.
01 winning-display pic x(32) value
'01020304'
& '05060708'
& '09101112'
& '13141500'.
procedure division.
start-fifteen.
display 'start fifteen puzzle'
display ' enter a two-digit tile number and press <enter> to move'
display ' press <enter> only to exit'
*> tables with an odd number of inversions are not solvable
perform initialize-table with test after until inversions = 0
perform show-table
accept display-move
perform until display-move = spaces
perform move-tile
perform show-table
move spaces to display-move
accept display-move
end-perform
stop run
.
initialize-table.
compute tile-number = random(seconds-past-midnight) *> seed only
move spaces to tile-flags
move 0 to current-tile inversions
perform varying r from 1 by 1 until r > 4
after c from 1 by 1 until c > 4
perform with test after
until tile-flags(tile-number + 1:1) = space
compute tile-number = random() * 100
compute tile-number = mod(tile-number, 16)
end-perform
move 'x' to tile-flags(tile-number + 1:1)
if tile-number > 0 and < current-tile
add 1 to inversions
end-if
move tile-number to display-cell(r,c) current-tile
end-perform
compute inversions = mod(inversions,2)
.
show-table.
if display-table = winning-display
display 'winning'
end-if
display space row-separator
perform varying r from 1 by 1 until r > 4
perform varying c from 1 by 1 until c > 4
display column-separator with no advancing
if display-cell(r,c) = 00
display ' ' with no advancing
move r to r-empty
move c to c-empty
else
display display-cell(r,c) with no advancing
end-if
end-perform
display column-separator
end-perform
display space row-separator
.
move-tile.
if not (tile-id numeric and tile-id >= 01 and <= 15)
display 'invalid tile number'
exit paragraph
end-if
*> find the entered tile-id row and column (r,c)
perform varying r from 1 by 1 until r > 4
after c from 1 by 1 until c > 4
if display-cell(r,c) = tile-id
exit perform
end-if
end-perform
*> show-table filled (r-empty,c-empty)
evaluate true
when r = r-empty
if c-empty < c
*> shift left
perform varying c-to from c-empty by 1 until c-to > c
compute c-from = c-to + 1
move display-cell(r-empty,c-from) to display-cell(r-empty,c-to)
end-perform
else
*> shift right
perform varying c-to from c-empty by -1 until c-to < c
compute c-from = c-to - 1
move display-cell(r-empty,c-from) to display-cell(r-empty,c-to)
end-perform
end-if
move 00 to display-cell(r,c)
when c = c-empty
if r-empty < r
*>shift up
perform varying r-to from r-empty by 1 until r-to > r
compute r-from = r-to + 1
move display-cell(r-from,c-empty) to display-cell(r-to,c-empty)
end-perform
else
*> shift down
perform varying r-to from r-empty by -1 until r-to < r
compute r-from = r-to - 1
move display-cell(r-from,c-empty) to display-cell(r-to,c-empty)
end-perform
end-if
move 00 to display-cell(r,c)
when other
display 'invalid move'
end-evaluate
.
end program fifteen.

View file

@ -1,259 +0,0 @@
#15 Puzzle Game
$Script:Neighbours = @{
"1" = @("2","5")
"2" = @("1","3","6")
"3" = @("2","4","7")
"4" = @("3","8")
"5" = @("1","6","9")
"6" = @("2","5","7","10")
"7" = @("3","6","8","11")
"8" = @("4","7","12")
"9" = @("5","10","13")
"10" = @("6","9","11","14")
"11" = @("7","10","12","15")
"12" = @("8","11","0")
"13" = @("9","14")
"14" = @("10","13","15")
"15" = @("11","14","0")
"0" = @("12","15")
}
$script:blank = ''
#region XAML window definition
$xaml = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
MinWidth="200"
Width ="333.333"
Title="15 Game"
Topmost="True" Height="398.001" VerticalAlignment="Center" HorizontalAlignment="Center">
<Grid HorizontalAlignment="Center" Height="285" Margin="0" VerticalAlignment="Center" Width="300">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button x:Name="B_1" Content="01" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24"/>
<Button x:Name="B_2" Content="02" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="1"/>
<Button x:Name="B_3" Content="03" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="2"/>
<Button x:Name="B_4" Content="04" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="3"/>
<Button x:Name="B_5" Content="05" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Row="1"/>
<Button x:Name="B_6" Content="06" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="1" Grid.Row="1"/>
<Button x:Name="B_7" Content="07" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="2" Grid.Row="1"/>
<Button x:Name="B_8" Content="08" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="3" Grid.Row="1"/>
<Button x:Name="B_9" Content="09" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Margin="0,71,0,0" Grid.Row="1" Grid.RowSpan="2"/>
<Button x:Name="B_10" Content="10" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="1" Grid.Row="1" Margin="0,71,0,0" Grid.RowSpan="2"/>
<Button x:Name="B_11" Content="11" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="2" Grid.Row="1" Margin="0,71,0,0" Grid.RowSpan="2"/>
<Button x:Name="B_12" Content="12" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="3" Grid.Row="1" Margin="0,71,0,0" Grid.RowSpan="2"/>
<Button x:Name="B_13" Content="13" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Margin="0,71,0,0" Grid.Row="2" Grid.RowSpan="2"/>
<Button x:Name="B_14" Content="14" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="1" Grid.Row="2" Margin="0,71,0,0" Grid.RowSpan="2"/>
<Button x:Name="B_15" Content="15" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="72" FontSize="24" Grid.Column="2" Grid.Row="2" Margin="0,71,0,0" Grid.RowSpan="2"/>
<Button x:Name="B_0" Content="00" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="3" Grid.Row="2" Margin="0,71,0,0" Grid.RowSpan="2"/>
<Button x:Name="B_Jumble" Grid.ColumnSpan="2" Content="Jumble Tiles" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="0,81,0,-33" Grid.Row="3" VerticalAlignment="Top" Width="150"/>
</Grid>
</Window>
'@
#endregion
#region Code Behind
function Convert-XAMLtoWindow
{
param
(
[Parameter(Mandatory=$true)]
[string]
$XAML
)
Add-Type -AssemblyName PresentationFramework
$reader = [XML.XMLReader]::Create([IO.StringReader]$XAML)
$result = [Windows.Markup.XAMLReader]::Load($reader)
$reader.Close()
$reader = [XML.XMLReader]::Create([IO.StringReader]$XAML)
while ($reader.Read())
{
$name=$reader.GetAttribute('Name')
if (!$name) { $name=$reader.GetAttribute('x:Name') }
if($name)
{$result | Add-Member NoteProperty -Name $name -Value $result.FindName($name) -Force}
}
$reader.Close()
$result
}
function Show-WPFWindow
{
param
(
[Parameter(Mandatory=$true)]
[Windows.Window]
$Window
)
$result = $null
$null = $window.Dispatcher.InvokeAsync{
$result = $window.ShowDialog()
Set-Variable -Name result -Value $result -Scope 1
}.Wait()
$result
}
#endregion Code Behind
#region Convert XAML to Window
$window = Convert-XAMLtoWindow -XAML $xaml
#endregion
#region Define Event Handlers
function Test-Victory{
#Evaluate if all the labels are in the correct position
$victory = $true
foreach($num in 1..15){
if([int]$window."b_$num".Content -ne $num){$victory = $false;break}
}
return($victory)
}
function Test-Move($Number){
#Number is a string of the pressed button number.
if($Script:Neighbours[$Number] -contains $script:blank){
return($true)
} else {
return($false)
}
}
Function Move-Tile($Number,$Bypass){
if((!(Test-Victory)) -or $Bypass){
if(Test-Move $Number){
#Set the new window label
$window."B_$script:blank".content = $window."B_$Number".content
$window."B_$script:blank".background = $window."B_$Number".background
$window."B_$Number".background = "#FFDDDDDD"
#Set the new blank window label
$window."B_$Number".content = ''
#Enable the old blank tile
$window."B_$script:blank".isenabled = $true
#disable the new blank tile
$window."B_$Number".isenabled = $false
#set the new blank
$script:blank = $Number
}
}
}
function Move-TileRandom{
$lastmove = "1"
for($i=0;$i -lt 500;$i++){
$move = $Script:Neighbours[$script:blank] | Where-Object {$_ -ne $lastmove} | Get-Random
$lastmove = $move
Move-Tile $move $true
}
}
function Set-TileColour($Tile){
#I was curious about setting tiles to a checkerboard pattern at this stage. It's probably far better to just define it in the xaml
#Ignore the blank tile
if($Tile -ne 0){
#check if the row of the tile is odd or even
if((([math]::floor(($Tile - 1)/4)) % 2 -eq 0)){
#check if the tile is odd or even
if($Tile % 2 -eq 0){
$window."B_$Tile".Background = "#FFFF7878"
} else {
$window."B_$Tile".Background = "#FF9696FF"
}
}else{
if($Tile % 2 -eq 0){
$window."B_$Tile".Background = "#FF9696FF"
} else {
$window."B_$Tile".Background = "#FFFF7878"
}
}
} else {
$window.B_0.Background = "#FFDDDDDD"
}
}
$window.B_1.add_Click{
$n = "1"
move-tile $n
}
$window.B_2.add_Click{
$n = "2"
move-tile $n
}
$window.B_3.add_Click{
$n = "3"
move-tile $n
}
$window.B_4.add_Click{
$n = "4"
move-tile $n
}
$window.B_5.add_Click{
$n = "5"
move-tile $n
}
$window.B_6.add_Click{
$n = "6"
move-tile $n
}
$window.B_7.add_Click{
$n = "7"
move-tile $n
}
$window.B_8.add_Click{
$n = "8"
move-tile $n
}
$window.B_9.add_Click{
$n = "9"
move-tile $n
}
$window.B_10.add_Click{
$n = "10"
move-tile $n
}
$window.B_11.add_Click{
$n = "11"
move-tile $n
}
$window.B_12.add_Click{
$n = "12"
move-tile $n
}
$window.B_13.add_Click{
$n = "13"
move-tile $n
}
$window.B_14.add_Click{
$n = "14"
move-tile $n
}
$window.B_15.add_Click{
$n = "15"
move-tile $n
}
$window.B_0.add_Click{
$n = "0"
move-tile $n
}
$window.B_Jumble.add_Click{
Move-TileRandom
}
#endregion Event Handlers
(([math]::floor(("9" - 1)/4)) % 2 -eq 0)
#region Manipulate Window Content
#initial processing of tiles
$array = 0..15 | ForEach-Object {"{0:00}" -f $_}
0..15 | ForEach-Object {if($array[$_] -ne '00'){$window."B_$_".content = $array[$_]} else {$window."B_$_".content = '';$script:blank = "$_";$window."B_$_".isenabled = $false};Set-TileColour $_}
#Shove them around a bit
Move-TileRandom
#endregion
# Show Window
$result = Show-WPFWindow -Window $window

View file

@ -1,6 +0,0 @@
rebol [] random/seed now g: [style t box red [
if not find [0x108 108x0 0x-108 -108x0] face/offset - e/offset [exit]
x: face/offset face/offset: e/offset e/offset: x] across
] x: random repeat i 15 [append x:[] i] repeat i 15 [
repend g ['t mold x/:i random white] if find [4 8 12] i [append g 'return]
] append g [e: box] view layout g

View file

@ -1,108 +0,0 @@
'----------------15 game-------------------------------------
'WARNING: this script uses ANSI escape codes to position items on console so
'it won't work in Windows from XP to 8.1 where Microsoft removed ANSI support...
'Windows 10, 11 or 98 are ok!!!
option explicit
const maxshuffle=100 'level
dim ans0:ans0=chr(27)&"["
dim anscls:anscls=ans0 & "2J"
dim dirs:dirs=array(6,-1,-6,1)
dim a:a=array(-1,-1,-1,-1,-1,-1,_
-1, 1, 2, 3, 4,-1,_
-1, 5, 6, 7, 8,-1,_
-1, 9,10,11,12,-1,_
-1,13,14,15, 0,-1,_
-1,-1,-1,-1,-1,-1)
dim b(35)
dim pos0
dim s:s=Array("W+Enter: up Z+Enter: down A+Enter: left S+Enter right ",_
"Bad move!! ",_
"You did it! Another game? [y/n]+Enter ",_
"Bye! ")
do
shuffle
draw
toxy 10,1,s(0)
do
if usr(wait()) then
draw
toxy 10,1,s(0)
else
toxy 10,1,s(1)
end if
loop until checkend
toxy 10,1,s(2)
loop until wait()="n"
toxy 10,1,s(3)
function wait():
toxy 11,1,"":
wait=left(lcase(wscript.stdin.readline),1):
end function
sub toxy(x,y,s)
wscript.StdOut.Write ans0 & x & ";" & y & "H"& " "& s
end sub
sub draw
dim i,j
wscript.stdout.write anscls
for i=0 to 3 'row
for j=0 to 3 'col
toxy (j*2)+2,(i*3)+3,iif(b(j*6+i+7)<>0,b(j*6+i+7)," ")
next
next
toxy 10,1,""
end sub
function checkend
dim i
for i=0 to ubound(a)
if (b(i)<>a(i)) then checkend=false : exit function
next
checkend=true
end function
function move(d)
dim p1
p1=pos0+d
if b(p1) <>-1 then
b(pos0)=b(p1):
b(p1)=0:
pos0=p1:
move=true
else
move=false
end if
end function
sub shuffle
dim cnt,r,i
randomize timer
for i=0 to ubound(a):b(i)=a(i):next
pos0=28
cnt=0
do
r=int(rnd*4)
if move(dirs(r))=true then cnt=cnt+1
loop until cnt=maxshuffle
end sub
function iif(a,b,c): if a then iif=b else iif=c end if:end function
function usr(a)
dim d
select case lcase(a)
case "w" :d=-6
case "z" :d=6
case "a" :d=-1
case "s" :d=1
end select
usr= move(d)
end function

View file

@ -1,192 +0,0 @@
with Ada.Text_IO;
procedure Puzzle_15 is
type Direction is (Up, Down, Left, Right);
type Row_Type is range 0 .. 3;
type Col_Type is range 0 .. 3;
type Tile_Type is range 0 .. 15;
To_Col : constant array (Tile_Type) of Col_Type :=
(3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2);
To_Row : constant array (Tile_Type) of Row_Type :=
(3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3);
type Board_Type is array (Row_Type, Col_Type) of Tile_Type;
Solved_Board : constant Board_Type :=
((1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 0));
type Try_Type is
record
Board : Board_Type;
Move : Direction;
Cost : Integer;
Row : Row_Type;
Col : Col_Type;
end record;
Stack : array (0 .. 100) of Try_Type;
Top : Natural := 0;
Iteration_Count : Natural := 0;
procedure Move_Down is
Board : Board_Type := Stack (Top).Board;
Row : constant Row_Type := Stack (Top).Row;
Col : constant Col_Type := Stack (Top).Col;
Tile : constant Tile_Type := Board (Row + 1, Col);
Penalty : constant Integer :=
(if To_Row (Tile) <= Row then 0 else 1);
begin
Board (Row, Col) := Tile;
Board (Row + 1, Col) := 0;
Stack (Top + 1) := (Board => Board,
Move => Down,
Row => Row + 1,
Col => Col,
Cost => Stack (Top).Cost + Penalty);
end Move_Down;
procedure Move_Up is
Board : Board_Type := Stack (Top).Board;
Row : constant Row_Type := Stack (Top).Row;
Col : constant Col_Type := Stack (Top).Col;
Tile : constant Tile_Type := Board (Row - 1, Col);
Penalty : constant Integer :=
(if To_Row (Tile) >= Row then 0 else 1);
begin
Board (Row, Col) := Tile;
Board (Row - 1, Col) := 0;
Stack (Top + 1) := (Board => Board,
Move => Up,
Row => Row - 1,
Col => Col,
Cost => Stack (Top).Cost + Penalty);
end Move_Up;
procedure Move_Left is
Board : Board_Type := Stack (Top).Board;
Row : constant Row_Type := Stack (Top).Row;
Col : constant Col_Type := Stack (Top).Col;
Tile : constant Tile_Type := Board (Row, Col - 1);
Penalty : constant Integer :=
(if To_Col (Tile) >= Col then 0 else 1);
begin
Board (Row, Col) := Tile;
Board (Row, Col - 1) := 0;
Stack (Top + 1) := (Board => Board,
Move => Left,
Row => Row,
Col => Col - 1,
Cost => Stack (Top).Cost + Penalty);
end Move_Left;
procedure Move_Right is
Board : Board_Type := Stack (Top).Board;
Row : constant Row_Type := Stack (Top).Row;
Col : constant Col_Type := Stack (Top).Col;
Tile : constant Tile_Type := Board (Row, Col + 1);
Penalty : constant Integer :=
(if To_Col (Tile) <= Col then 0 else 1);
begin
Board (Row, Col) := Tile;
Board (Row, Col + 1) := 0;
Stack (Top + 1) := (Board => Board,
Move => Right,
Row => Row,
Col => Col + 1,
Cost => Stack (Top).Cost + Penalty);
end Move_Right;
function Is_Solution return Boolean;
function Test_Moves return Boolean is
begin
if
Stack (Top).Move /= Down and then
Stack (Top).Row /= Row_Type'First
then
Move_Up;
Top := Top + 1;
if Is_Solution then return True; end if;
Top := Top - 1;
end if;
if
Stack (Top).Move /= Up and then
Stack (Top).Row /= Row_Type'Last
then
Move_Down;
Top := Top + 1;
if Is_Solution then return True; end if;
Top := Top - 1;
end if;
if
Stack (Top).Move /= Right and then
Stack (Top).Col /= Col_Type'First
then
Move_Left;
Top := Top + 1;
if Is_Solution then return True; end if;
Top := Top - 1;
end if;
if
Stack (Top).Move /= Left and then
Stack (Top).Col /= Col_Type'Last
then
Move_Right;
Top := Top + 1;
if Is_Solution then return True; end if;
Top := Top - 1;
end if;
return False;
end Test_Moves;
function Is_Solution return Boolean is
use Ada.Text_IO;
begin
if Stack (Top).Board = Solved_Board then
Put ("Solved in " & Top'Image & " moves: ");
for R in 1 .. Top loop
Put (String'(Stack (R).Move'Image) (1));
end loop;
New_Line;
return True;
end if;
if Stack (Top).Cost <= Iteration_Count then
return Test_Moves;
end if;
return False;
end Is_Solution;
procedure Solve (Row : in Row_Type;
Col : in Col_Type;
Board : in Board_Type) is
begin
pragma Assert (Board (Row, Col) = 0);
Top := 0;
Iteration_Count := 0;
Stack (Top) := (Board => Board,
Row => Row,
Col => Col,
Move => Down,
Cost => 0);
while not Is_Solution loop
Iteration_Count := Iteration_Count + 1;
end loop;
end Solve;
begin
Solve (Row => 2,
Col => 0,
Board => ((15, 14, 1, 6),
(9, 11, 4, 12),
(0, 10, 7, 3),
(13, 8, 5, 2)));
end Puzzle_15;

View file

@ -1,41 +1,31 @@
# Solve a 15 puzzle https://rosettacode.org/wiki/15_puzzle_solver#Uiua
# Experimental!
T ← ↯4_4 ↻1⇡16
# Return shuffled copy of the input.
Shuffle ← ⊏⊸(⍏[⍥⚂]⧻)
# Positions of the numbers (not 0)
Pos ← ≡(⊢⊚⌕)↘1⇡16¤
T ← ↯4_4 ↻1⇡16
Pos ← ≡(⊢⊚⌕)↘1⇡16¤ # Positions of the numbers (not 0)
# Applying a very gentle weighting to certain cells massively
# speeds up the algorithm
Weights ← [[2 1 1 2] [2 1 1 2] [2 1 1 2] [2 1 1 1]]
Distance ← /+×⊡:Weights:≡/+⌵-⊙.∩Pos
Weights ← [[2 1 1 2] [2 1 1 2] [2 1 1 2] [2 1 1 1]]
Distance ← /+×⊡: Weights :≡/+⌵-⊙.∩Pos
Heuristic ← Distance T
# Four possible neighbours
Nfour ← [[1 0] [¯1 0] [0 1] [0 ¯1]]
# Actual neighbours at a point.
ValidN ← ≡(⊂)⊙¤:⟜(▽⊸(≥0≡/↧)▽⊸(<4≡/↥)+Nfour)¤
# Precalculate them.
ValidNs ← ⊞(□ ValidN⊟)⇡4 ⇡4
# Get the valid (from to) moves from this cell.
Moves ← °□⊡:ValidNs⊢⊚⌕0
# Swap the values at the indexes [0 1] [a b 2 3] -> [b a 2 3]
Swap ← ⍜(⊡|∘◌) ⊃(⇌⊙∘|⊡)
# List the possible next positions for a position
Next ← ⊙◌≡(Swap ⊙.)⊙¤⊸Moves
ValidN ← ≡⊟⊙¤▽≡/↧×⊃(≡₀<4|≡₀≥0).+Nfour¤. # Actual neighbours at a point.
ValidNs ← ⊞(□ValidN⊟).⇡4 # Precalculate them.
Moves ← °□⊡:ValidNs⊢⊚⌕0 # Get valid (from to) moves from grid.
Swap ← ⍜⊡⇌ # Swap the values at the indexes
Next ← ⊸≡⋅1 ≡Swap⊙¤⊸Moves # Next positions, set costs=1
Solve ← (
&p"Running..."&p.
⍜nowastar(Next|Heuristic|≍T)
&p$"Solving: _".
⍜now (⊢path(Next|≍|Heuristic):T)
&p$"_ seconds"
# Track the movement of the 0 between adjacent steps.
≡(/-)◫2◇≡(⊢⊚⌕0)⇌⊢
# Map each to a direction string and join.
/⊂⇌≡⍣("d" °¯1_0|"u" °1_0|"r" °0_¯1|"l" °0_1|∘)
≡/-⧈∘2◇≡(⊢⊚⌕0)⇌⊢ # Track the movement of the 0
˜≡get¤mapNfour"udlr" # Map to directions
)
# Uncomment one of the following lines to try random grids
# Uncomment one of the following lines to try these grids
# ⍥(Swap⊡⊸(⌊×⚂⧻)⊸Moves)90 T
# [[2 14 6 4] [5 1 3 8] [9 10 7 11] [13 0 15 12]] # Simple 40 shuffles
# [[5 1 2 3] [6 10 7 4] [13 9 11 8] [14 0 15 12]] # Simple 12 steps

View file

@ -1,177 +0,0 @@
with Ada.Text_IO; use Ada.Text_IO;
with System.Random_Numbers;
procedure Play_2048 is
-- ----- Keyboard management
type t_Keystroke is (Up, Down, Right, Left, Quit, Restart, Invalid);
-- Redefining this standard procedure as function to allow Get_Keystroke as an expression function
function Get_Immediate return Character is
begin
return Answer : Character do Ada.Text_IO.Get_Immediate(Answer);
end return;
end Get_Immediate;
Arrow_Prefix : constant Character := Character'Val(224); -- works for windows
function Get_Keystroke return t_Keystroke is
(case Get_Immediate is
when 'Q' | 'q' => Quit,
when 'R' | 'r' => Restart,
when 'W' | 'w' => Left,
when 'A' | 'a' => Up,
when 'S' | 's' => Down,
when 'D' | 'd' => Right,
-- Windows terminal
when Arrow_Prefix => (case Character'Pos(Get_Immediate) is
when 72 => Up,
when 75 => Left,
when 77 => Right,
when 80 => Down,
when others => Invalid),
-- Unix escape sequences
when ASCII.ESC => (case Get_Immediate is
when '[' => (case Get_Immediate is
when 'A' => Up,
when 'B' => Down,
when 'C' => Right,
when 'D' => Left,
when others => Invalid),
when others => Invalid),
when others => Invalid);
-- ----- Game data
function Random_Int is new System.Random_Numbers.Random_Discrete(Integer);
type t_List is array (Positive range <>) of Natural;
subtype t_Row is t_List (1..4);
type t_Board is array (1..4) of t_Row;
Board : t_Board;
New_Board : t_Board;
Blanks : Natural;
Score : Natural;
Generator : System.Random_Numbers.Generator;
-- ----- Displaying the board
procedure Display_Board is
Horizontal_Rule : constant String := "+----+----+----+----+";
function Center (Value : in String) return String is
((1..(2-(Value'Length-1)/2) => ' ') & -- Add leading spaces
Value(Value'First+1..Value'Last) & -- Trim the leading space of the raw number image
(1..(2-Value'Length/2) => ' ')); -- Add trailing spaces
begin
Put_Line (Horizontal_Rule);
for Row of Board loop
for Cell of Row loop
Put('|' & (if Cell = 0 then " " else Center(Cell'Img)));
end loop;
Put_Line("|");
Put_Line (Horizontal_Rule);
end loop;
Put_Line("Score =" & Score'Img);
end Display_Board;
-- ----- Game mechanics
procedure Add_Block is
Block_Offset : Positive := Random_Int(Generator, 1, Blanks);
begin
Blanks := Blanks-1;
for Row of Board loop
for Cell of Row loop
if Cell = 0 then
if Block_Offset = 1 then
Cell := (if Random_Int(Generator,1,10) = 1 then 4 else 2);
return;
else
Block_Offset := Block_Offset-1;
end if;
end if;
end loop;
end loop;
end Add_Block;
procedure Reset_Game is
begin
Board := (others => (others => 0));
Blanks := 16;
Score := 0;
Add_Block;
Add_Block;
end Reset_Game;
-- Moving and merging will always be performed leftward, hence the following transforms
function HFlip (What : in t_Row) return t_Row is
(What(4),What(3),What(2),What(1));
function VFlip (What : in t_Board) return t_Board is
(HFlip(What(1)),HFlip(What(2)),HFlip(What(3)),HFlip(What(4)));
function Transpose (What : in t_Board) return t_Board is
begin
return Answer : t_Board do
for Row in t_Board'Range loop
for Column in t_Row'Range loop
Answer(Column)(Row) := What(Row)(Column);
end loop;
end loop;
end return;
end Transpose;
-- For moving/merging, recursive expression functions will be used, but they
-- can't contain statements, hence the following sub-function used by Merge
function Add_Blank (Delta_Score : in Natural) return t_List is
begin
Blanks := Blanks+1;
Score := Score+Delta_Score;
return (1 => 0);
end Add_Blank;
function Move_Row (What : in t_List) return t_List is
(if What'Length = 1 then What
elsif What(What'First) = 0
then Move_Row(What(What'First+1..What'Last)) & (1 => 0)
else (1 => What(What'First)) & Move_Row(What(What'First+1..What'Last)));
function Merge (What : in t_List) return t_List is
(if What'Length <= 1 or else What(What'First) = 0 then What
elsif What(What'First) = What(What'First+1)
then (1 => 2*What(What'First)) & Merge(What(What'First+2..What'Last)) & Add_Blank(What(What'First))
else (1 => What(What'First)) & Merge(What(What'First+1..What'Last)));
function Move (What : in t_Board) return t_Board is
(Merge(Move_Row(What(1))),Merge(Move_Row(What(2))),Merge(Move_Row(What(3))),Merge(Move_Row(What(4))));
begin
System.Random_Numbers.Reset(Generator);
Main_Loop: loop
Reset_Game;
Game_Loop: loop
Display_Board;
case Get_Keystroke is
when Restart => exit Game_Loop;
when Quit => exit Main_Loop;
when Left => New_Board := Move(Board);
when Right => New_Board := VFlip(Move(VFlip(Board)));
when Up => New_Board := Transpose(Move(Transpose(Board)));
when Down => New_Board := Transpose(VFlip(Move(VFlip(Transpose(Board)))));
when others => null;
end case;
if New_Board = Board then
Put_Line ("Invalid move...");
elsif (for some Row of New_Board => (for some Cell of Row => Cell = 2048)) then
Display_Board;
Put_Line ("Win !");
exit Main_Loop;
else
Board := New_Board;
Add_Block; -- OK since the board has changed
if Blanks = 0
and then (for all Row in 1..4 =>
(for all Column in 1..3 =>
(Board(Row)(Column) /= Board(Row)(Column+1))))
and then (for all Row in 1..3 =>
(for all Column in 1..4 =>
(Board(Row)(Column) /= Board(Row+1)(Column)))) then
Display_Board;
Put_Line ("Lost !");
exit Main_Loop;
end if;
end if;
end loop Game_Loop;
end loop Main_Loop;
end Play_2048;

View file

@ -29,7 +29,7 @@ proc show .
gcolor 765
grect x y 19 19
v = brd[i]
h = 2 * floor log10 v
h = 2 * floor log v 10
gcolor 000
gtext x + 7 - h y + 7 brd[i]
.

View file

@ -1,228 +1,362 @@
// git repository at https://codeberg.org/Vulwsztyn/2048_zig
const std = @import("std");
const io = std.io;
const Random = std.Random;
const builtin = @import("builtin");
// UserMove enum representing possible moves
const UserMove = enum {
Up,
Down,
Left,
Right,
const Io = std.Io;
const Random = std.Random;
const fmt = std.fmt;
const mibu = @import("mibu");
const color = mibu.color;
const events = mibu.events;
const term = mibu.term;
const cursor = mibu.cursor;
// You can change these constants to modify the game behavior
const ROW_SIZE = 4; // program won't work if less than 2
const COL_SIZE = 4; // program won't work if less than 2
const TARGET_SCORE = 11; // 2^11 = 2048
const PROBABILITY_OF_FOUR_NUMERATOR = 10;
const PROBABILITY_OF_FOUR_DENOMINATOR = 100; // these 2 work in tandem to give chance of spawning a 4 instead of 2
const Dir = enum { up, down, left, right };
const Action = union(enum) {
Move: Dir,
Quit,
Noop,
};
// Game field type
const Field = [4][4]u32;
// Function to print the current game state
fn printGame(field: *const Field) void {
for (field) |row| {
std.debug.print("{any}\n", .{row});
}
}
// Function to get a user move
fn getUserMove() !UserMove {
const stdin = std.io.getStdIn().reader();
var buf: [2]u8 = undefined; // Buffer for input (character + newline)
while (true) {
const bytesRead = try stdin.read(&buf);
if (bytesRead < 1) continue;
switch (buf[0]) {
'a' => return UserMove.Left,
'w' => return UserMove.Up,
's' => return UserMove.Down,
'd' => return UserMove.Right,
else => {
std.debug.print("input was {c}: invalid character should be a,s,w or d\n", .{buf[0]});
},
fn spawn(comptime X: usize, comptime Y: usize, matrix_p: *[X][Y]u8, rand: Random) void {
var buffer: [X * Y]u8 = undefined;
var zero_indices = std.ArrayListUnmanaged(u8).initBuffer(&buffer);
for (matrix_p, 0..) |row, i| {
for (row, 0..) |val, j| {
if (val == 0) {
zero_indices.appendBounded(@intCast(i * Y + j)) catch unreachable;
}
}
}
const random_index = rand.intRangeAtMost(u8, 0, @intCast(zero_indices.items.len - 1));
const chosen = zero_indices.items[random_index];
const row = chosen / Y;
const col = chosen % Y;
const value: u8 = if (rand.intRangeAtMost(u8, 0, PROBABILITY_OF_FOUR_DENOMINATOR) < PROBABILITY_OF_FOUR_NUMERATOR) 2 else 1;
matrix_p[row][col] = value;
}
// This function implements user moves.
// For every element, it checks if the element is zero.
// If the element is zero, it looks against the direction of movement if any
// element is not zero, then moves it to its place and checks for a matching element.
// If the element is not zero, it looks for a match. If no match is found,
// it looks for the next element.
fn doGameStep(step: UserMove, field: *Field) void {
switch (step) {
.Left => {
for (field) |*row| {
for (0..4) |col| {
for ((col + 1)..4) |my_testCol| {
if (row[my_testCol] != 0) {
if (row[col] == 0) {
row[col] += row[my_testCol];
row[my_testCol] = 0;
} else if (row[col] == row[my_testCol]) {
row[col] += row[my_testCol];
row[my_testCol] = 0;
break;
} else {
break;
}
}
}
}
}
fn additives_for_previous(dir: Dir) [2]i8 {
// assuming that for a move in a direction, we look at the values at the end
// and check backwards
// e.g. for up, we look at the top row and check downwards
// so we return 1, 0 meaning one row down, same column
switch (dir) {
.up => {
return .{ 1, 0 };
},
.Right => {
for (field) |*row| {
var col: i32 = 3;
while (col >= 0) : (col -= 1) {
var my_testCol: i32 = col - 1;
while (my_testCol >= 0) : (my_testCol -= 1) {
if (row[@intCast(my_testCol)] != 0) {
if (row[@intCast(col)] == 0) {
row[@intCast(col)] += row[@intCast(my_testCol)];
row[@intCast(my_testCol)] = 0;
} else if (row[@intCast(col)] == row[@intCast(my_testCol)]) {
row[@intCast(col)] += row[@intCast(my_testCol)];
row[@intCast(my_testCol)] = 0;
break;
} else {
break;
}
}
}
}
}
.down => {
return .{ -1, 0 };
},
.Down => {
for (0..4) |col_idx| {
const col = col_idx; // Convert to immutable
var row: i32 = 3;
while (row >= 0) : (row -= 1) {
var my_testRow: i32 = row - 1;
while (my_testRow >= 0) : (my_testRow -= 1) {
if (field[@intCast(my_testRow)][col] != 0) {
if (field[@intCast(row)][col] == 0) {
field[@intCast(row)][col] += field[@intCast(my_testRow)][col];
field[@intCast(my_testRow)][col] = 0;
} else if (field[@intCast(row)][col] == field[@intCast(my_testRow)][col]) {
field[@intCast(row)][col] += field[@intCast(my_testRow)][col];
field[@intCast(my_testRow)][col] = 0;
break;
} else {
break;
}
}
}
}
}
.left => {
return .{ 0, 1 };
},
.Up => {
for (0..4) |col| {
for (0..4) |row| {
for ((row + 1)..4) |my_testRow| {
if (field[my_testRow][col] != 0) {
if (field[row][col] == 0) {
field[row][col] += field[my_testRow][col];
field[my_testRow][col] = 0;
} else if (field[row][col] == field[my_testRow][col]) {
field[row][col] += field[my_testRow][col];
field[my_testRow][col] = 0;
break;
} else {
break;
}
}
}
}
}
.right => {
return .{ 0, -1 };
},
}
}
// Spawn a new number (2 or 4) in a random empty cell
fn spawn(field: *Field, random: Random) void {
while (true) {
const x = random.uintLessThan(usize, 16); // Random position 0-15
const row = x % 4;
const col = (x / 4) % 4;
if (field[row][col] == 0) {
// 10% chance for a 4, 90% chance for a 2
if (random.uintLessThan(usize, 10) == 0) {
field[row][col] = 4;
} else {
field[row][col] = 2;
}
break;
}
}
}
// Check if fields are equal
fn areFieldsEqual(a: *const Field, b: *const Field) bool {
for (0..4) |i| {
for (0..4) |j| {
if (a[i][j] != b[i][j]) return false;
}
}
return true;
}
// Check if player has won (any tile equals 2048)
fn checkWin(field: *const Field) bool {
for (field) |row| {
for (row) |cell| {
if (cell == 2048) return true;
fn is_move_possible(comptime X: usize, comptime Y: usize, matrix_p: [X][Y]u8, dir: Dir) bool {
// checks if move is possible by checking if any tile can be moved or combined
const additives = additives_for_previous(dir);
for (0..X) |i| {
const i_signed: i8 = @intCast(i);
const new_i = i_signed + additives[0];
if (new_i < 0 or new_i >= X) continue;
for (0..Y) |j| {
const j_signed: i8 = @intCast(j);
const new_j = j_signed + additives[1];
if (new_j < 0 or new_j >= Y) continue;
const val = matrix_p[i][j];
const prev_val = matrix_p[@intCast(new_i)][@intCast(new_j)];
if (val != 0 and val == prev_val) return true;
if (val == 0 and prev_val != 0) return true;
}
}
return false;
}
pub fn main() !void {
var prng = std.Random.DefaultPrng.init(@intCast(std.time.milliTimestamp()));
const random = prng.random();
fn is_game_lost(comptime X: usize, comptime Y: usize, matrix_p: [X][Y]u8) bool {
// checks if move in any direction is possible
for (std.meta.tags(Dir)) |dir| {
if (is_move_possible(X, Y, matrix_p, dir)) {
return false;
}
}
return true;
}
var field: Field = [_][4]u32{[_]u32{0} ** 4} ** 4;
var my_test: Field = undefined;
gameLoop: while (true) {
// Check if there's still an open space
@memcpy(&my_test, &field);
spawn(&field, random);
// Check if any valid moves remain
var validMoveExists = false;
const moves = [_]UserMove{ .Up, .Down, .Left, .Right };
for (moves) |move| {
@memcpy(&my_test, &field);
doGameStep(move, &my_test);
if (!areFieldsEqual(&my_test, &field)) {
validMoveExists = true;
break;
fn is_game_won(comptime X: usize, comptime Y: usize, matrix_p: [X][Y]u8) bool {
for (matrix_p) |row| {
for (row) |val| {
if (val >= TARGET_SCORE) {
return true;
}
}
}
return false;
}
if (!validMoveExists) {
std.debug.print("No more valid moves, you lose\n", .{});
break :gameLoop;
}
fn last_positions(comptime X: usize, comptime Y: usize, dir: Dir, gpa: std.mem.Allocator) std.ArrayList([2]u8) {
// see comment in additives_for_previous
// e.g. for move up we start at the top row and go downwards
// this function returns the list positions in the top row (for that scenario)
var list: std.ArrayList([2]u8) = .empty;
switch (dir) {
.up => {
for (0..Y) |i| {
list.append(gpa, .{ 0, @intCast(i) }) catch unreachable;
}
},
.down => {
for (0..Y) |i| {
list.append(gpa, .{ X - 1, @intCast(i) }) catch unreachable;
}
},
.left => {
for (0..X) |i| {
list.append(gpa, .{ @intCast(i), 0 }) catch unreachable;
}
},
.right => {
for (0..X) |i| {
list.append(gpa, .{ @intCast(i), X - 1 }) catch unreachable;
}
},
}
return list;
}
// Print the current game state
printGame(&field);
std.debug.print("move the blocks\n", .{});
// Get and apply user move
@memcpy(&my_test, &field);
while (areFieldsEqual(&my_test, &field)) {
const move = try getUserMove();
doGameStep(move, &field);
}
// Check win condition
if (checkWin(&field)) {
printGame(&field);
std.debug.print("You Won!!\n", .{});
break :gameLoop;
fn move_matrix(comptime X: usize, comptime Y: usize, matrix_p: *[X][Y]u8, dir: Dir) void {
const gpa = std.heap.page_allocator;
const additives = additives_for_previous(dir);
var postions = last_positions(X, Y, dir, gpa);
defer postions.deinit(gpa);
std.debug.print("\n", .{});
for (postions.items) |pos| {
var target_row: i8 = @intCast(pos[0]);
var target_col: i8 = @intCast(pos[1]);
var target_val: u8 = matrix_p[pos[0]][pos[1]];
var current_row: i8 = target_row;
var current_col: i8 = target_col;
while (true) {
current_row += additives[0];
current_col += additives[1];
const went_out_of_bounds = current_row < 0 or current_row >= (X) or
current_col < 0 or current_col >= (Y);
if (went_out_of_bounds) {
break;
}
const current_val: u8 = matrix_p[@intCast(current_row)][@intCast(current_col)];
if (current_val == 0) {
// nothing to do,
continue;
}
if (target_val != 0 and target_val != current_val) {
// cannot combine, move target forward
// e.g 0 0 2 4 (for was target, now 2 becomes target)
matrix_p[@intCast(current_row)][@intCast(current_col)] = 0;
target_row = (target_row) + (additives[0]);
target_col = (target_col) + (additives[1]);
matrix_p[@intCast(target_row)][@intCast(target_col)] = current_val;
target_val = matrix_p[@intCast(target_row)][@intCast(target_col)];
continue;
}
if (target_val == 0) {
// move current to target
// e.g 0 0 2 0 -> 0 0 0 2 (2 remains target, since we want 0 2 2 0 to become 0 0 0 4)
matrix_p[@intCast(target_row)][@intCast(target_col)] = current_val;
target_val = current_val;
} else {
// combine
// e.g 0 0 2 2 -> 0 0 0 4 (with rightmost zero becoming target, since the movements are not greedy)
matrix_p[@intCast(target_row)][@intCast(target_col)] = target_val + 1;
target_val = 0;
target_row = target_row + (additives[0]);
target_col = target_col + (additives[1]);
}
// both in case of move and combine we clear current
matrix_p[@intCast(current_row)][@intCast(current_col)] = 0;
}
}
}
fn print(comptime X: usize, comptime Y: usize, matrix_p: [X][Y]u8, stdout: *Io.Writer) !void {
for (matrix_p, 0..) |row, i| {
try cursor.goTo(stdout, 1, 2 + i);
var buf: [100]u8 = undefined;
const all_together_slice = buf[0..];
for (row) |val| {
const value = if (val != 0) std.math.pow(u16, 2, @intCast(val)) else 0;
const value_as_str = if (val > 0) try fmt.bufPrint(all_together_slice, "{d}", .{value}) else "_";
try color.fg256(stdout, if (val > 1) @enumFromInt(val) else color.Color.white); // sets colour based on value
try stdout.print("{s:>5} ", .{value_as_str}); // prints with padding
}
try stdout.print("\x1b[K\n", .{});
}
}
fn init_matrix(comptime X: usize, comptime Y: usize, matrix_p: *[X][Y]u8) void {
// initializes matrix to all zeros
for (matrix_p) |*row| {
for (row) |*val| {
val.* = @intCast(0);
}
}
}
fn action_from_event(next: events.Event) Action {
switch (next) {
.key => |k| switch (k.code) {
.char => |c| switch (c) {
'c' => {
return .Quit;
},
'q' => {
return .Quit;
},
'w' => {
return .{ .Move = .up };
},
's' => {
return .{ .Move = .down };
},
'a' => {
return .{ .Move = .left };
},
'd' => {
return .{ .Move = .right };
},
'h' => {
return .{ .Move = .left };
},
'j' => {
return .{ .Move = .down };
},
'k' => {
return .{ .Move = .up };
},
'l' => {
return .{ .Move = .right };
},
else => {
return .Noop;
},
},
.up => {
return .{ .Move = .up };
},
.down => {
return .{ .Move = .down };
},
.left => {
return .{ .Move = .left };
},
.right => {
return .{ .Move = .right };
},
else => {
return .Noop;
},
},
else => {
return .Noop;
},
}
}
pub fn main() !void {
const row_size = ROW_SIZE;
const col_size = COL_SIZE;
var seed: u64 = undefined;
try std.posix.getrandom(std.mem.asBytes(&seed));
var prng = Random.DefaultPrng.init(seed);
const rand = prng.random();
var stdout_buffer: [1024]u8 = undefined;
const stdin = std.fs.File.stdin();
var stdout_file = std.fs.File.stdout();
var stdout_writer = stdout_file.writer(&stdout_buffer);
const stdout = &stdout_writer.interface;
if (!std.posix.isatty(stdin.handle)) {
try stdout.print("The current file descriptor is not a referring to a terminal.\n", .{});
return;
}
if (builtin.os.tag == .windows) {
try mibu.enableWindowsVTS(stdout.handle);
}
// Enable terminal raw mode, its very recommended when listening for events
var raw_term = try term.enableRawMode(stdin.handle);
defer raw_term.disableRawMode() catch {
std.debug.print("Failed to disable raw mode\n", .{});
};
try term.enterAlternateScreen(stdout);
defer term.exitAlternateScreen(stdout) catch {
std.debug.print("Failed to exit alternate screen\n", .{});
};
try cursor.hide(stdout);
defer cursor.show(stdout) catch {
std.debug.print("Failed to show cursor\n", .{});
};
try cursor.goTo(stdout, 1, 1);
try mibu.style.italic(stdout, true);
var matrix: [row_size][col_size]u8 = undefined;
init_matrix(row_size, col_size, &matrix);
spawn(row_size, col_size, &matrix, rand);
try stdout.print("move with wsad, hjkl, or arrows; quit with c or q\x1b[K\n", .{}); // prints with padding
try print(row_size, col_size, matrix, stdout);
try stdout.flush();
while (true) {
try cursor.goTo(stdout, 1, 2);
const next = try events.next(stdin);
const action = action_from_event(next);
switch (action) {
.Quit => break,
.Noop => continue,
.Move => |dir| {
if (is_move_possible(row_size, col_size, matrix, dir)) {
move_matrix(row_size, col_size, &matrix, dir);
try print(row_size, col_size, matrix, stdout);
if (is_game_won(row_size, col_size, matrix)) {
try cursor.goTo(stdout, 1, row_size + 3);
try stdout.print("You won! Congratulations!\n", .{});
try stdout.flush();
break;
}
spawn(row_size, col_size, &matrix, rand);
try print(row_size, col_size, matrix, stdout);
if (is_game_lost(row_size, col_size, matrix)) {
try cursor.goTo(stdout, 1, (row_size + 3));
try stdout.print("Game over! No more moves possible!\n", .{});
try stdout.flush();
break;
}
}
try stdout.flush();
},
}
}
}

View file

@ -1,108 +0,0 @@
with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Game_21 is
procedure Put (Item : String) is
begin
for Char of Item loop
Ada.Text_IO.Put (Char);
delay 0.010;
end loop;
end Put;
procedure New_Line is
begin
Ada.Text_IO.New_Line;
end New_Line;
procedure Put_Line (Item : String) is
begin
Put (Item);
New_Line;
end Put_LIne;
type Player_Kind is (Human, Computer);
type Score_Type is range 0 .. 21;
subtype Amount_Range is Score_Type range 1 .. 3;
package Amount_Generators is
new Ada.Numerics.Discrete_Random (Amount_Range);
Gen : Amount_Generators.Generator;
Total : Score_Type := 0;
Choice : Character;
Player : Player_Kind;
Amount : Amount_Range;
begin
Amount_Generators.Reset (Gen);
Put_Line ("--- The 21 Game ---"); New_Line;
Put ("Who is starting human or computer (h/c) ? ");
Ada.Text_IO.Get_Immediate (Choice);
New_Line;
case Choice is
when 'c' | 'C' => Player := Computer;
when 'h' | 'H' => Player := Human;
when others => return;
end case;
Play_Loop : loop
New_Line;
Put ("Runing total is "); Put (Total'Image); New_Line;
New_Line;
case Player is
when Human =>
Put_Line ("It is your turn !");
Input_Loop : loop
Put ("Enter choice 1 .. 3 (0 to end) : ");
Ada.Text_IO.Get_Immediate (Choice);
case Choice is
when '1' .. '3' =>
Amount := Amount_Range'Value ("" & Choice);
exit Input_Loop;
when '0' =>
exit Play_Loop;
when others =>
Put_Line ("Choice must be in 1 .. 3");
end case;
end loop Input_Loop;
New_Line;
when Computer =>
delay 1.500;
Amount := Amount_Generators.Random (Gen);
Put ("Computer chooses: "); Put (Amount'Image); New_Line;
delay 0.800;
end case;
New_Line;
Amount := Score_Type'Min (Amount, Score_Type'Last - Total);
Put (" "); Put (Total'Image); Put (" + "); Put (Amount'Image); Put (" = ");
Total := Total + Amount;
Put (Total'Image);
New_Line;
if Total = 21 then
New_Line;
Put ("... and we have a WINNER !!"); New_Line;
delay 0.500;
Put_Line (" ... and the winner is ...");
delay 1.000;
Put_Line (" " & Player'Image);
exit;
end if;
Player := (case Player is
when Computer => Human,
when Human => Computer);
end loop Play_Loop;
end Game_21;

View file

@ -5,7 +5,7 @@ print "-----------------------------"
players: ["A" "B"]
currentPlayer: sample players
nextPlayer: first players -- currentPlayer
runningTotal: new 0
runningTotal: 0
num: 0
getNum: function [][

View file

@ -6,7 +6,7 @@ Gui, add, text, xs vT, Total : 00
Gui, add, text, xs vComputer, Computer Dealt 00
Gui, add, text, xs Section, Player 1
loop, 3
Gui, add, button, x+5 vPlayer1_%A_Index% gTotal, % A_Index
Gui, add, button, x+5 vPlayer1_%A_Index% gTotal, % A_Index
Gui, add, button, xs vReset gReset, reset
Gui show,, 21 Game
Winners := [1,5,9,13,17,21]
@ -18,13 +18,13 @@ total := 0
GuiControl,, T, % "Total : " SubStr("00" Total, -1)
GuiControl,, Computer, % "Computer Waiting"
Loop 3
GuiControl, Enable, % "Player1_" A_Index
GuiControl, Enable, % "Player1_" A_Index
Random, rnd, 0, 1
if rnd
{
Loop 3
GuiControl, Disable, % "Player1_" A_Index
gosub ComputerTurn
Loop 3
GuiControl, Disable, % "Player1_" A_Index
gosub ComputerTurn
}
return
;-----------------------------------
@ -34,12 +34,12 @@ Total += Added
GuiControl,, T, % "Total : " SubStr("00" Total, -1)
if (total >= 21)
{
MsgBox % "Player 1 Wins"
gosub reset
return
MsgBox % "Player 1 Wins"
gosub reset
return
}
Loop 3
GuiControl, Disable, % "Player1_" A_Index
GuiControl, Disable, % "Player1_" A_Index
gosub, ComputerTurn
return
;-----------------------------------
@ -48,38 +48,38 @@ Gui, Submit, NoHide
Sleep 500
if RadioE
{
if (total < 13)
RadioC := true
else
RadioH := true
if (total < 13)
RadioC := true
else
RadioH := true
}
if RadioC
{
Random, Deal, 1, 3
total += Deal
Random, Deal, 1, 3
total += Deal
}
if RadioH
{
for i, v in Winners
if (total >= v)
continue
else
{
Deal := v - total
if Deal > 3
Random, Deal, 1, 3
total += Deal
break
}
for i, v in Winners
if (total >= v)
continue
else
{
Deal := v - total
if Deal > 3
Random, Deal, 1, 3
total += Deal
break
}
}
GuiControl,, T, % "Total : " SubStr("00" Total, -1)
GuiControl,, Computer, % "Computer Dealt " Deal
if (total=21)
{
MsgBox Computer Wins
gosub, reset
MsgBox Computer Wins
gosub, reset
}
else
Loop 3
GuiControl, Enable, % "Player1_" A_Index
Loop 3
GuiControl, Enable, % "Player1_" A_Index
return

View file

@ -8,81 +8,81 @@ const target: int = 21
# -1 is returned to request quit
func get_player_choice(total: int) -> int:
while true:
printraw("Player's choice: ")
var input: String = OS.read_string_from_stdin().strip_edges()
while true:
printraw("Player's choice: ")
var input: String = OS.read_string_from_stdin().strip_edges()
if input == "quit":
return -1
if input == "quit":
return -1
if not input.is_valid_int():
print("Please input an integer.")
continue
if not input.is_valid_int():
print("Please input an integer.")
continue
var input_int := int(input)
if input_int < 1 or input_int > 3:
print("Please pick a number from 1 to 3")
continue
var input_int := int(input)
if input_int < 1 or input_int > 3:
print("Please pick a number from 1 to 3")
continue
if input_int + total > target:
print("Please do not exceed a total of %d" % target)
continue
if input_int + total > target:
print("Please do not exceed a total of %d" % target)
continue
return input_int
return input_int
# This is required since Godot does not detect the unreachable code path
OS.crash("unreachable")
return 0
# This is required since Godot does not detect the unreachable code path
OS.crash("unreachable")
return 0
func get_computer_choice(total: int) -> int:
# This can be shortened using max() if you do not have type checking OCD
var remaining: int = target - total
return randi_range(1, 3 if remaining > 3 else remaining)
# This can be shortened using max() if you do not have type checking OCD
var remaining: int = target - total
return randi_range(1, 3 if remaining > 3 else remaining)
func play() -> void:
print("""\
print("""\
Welcome to the 21 game.
Type quit to exit.""")
var total: int = 0
var player: Player
match randi_range(1, 2):
1:
player = Player.Human
print("You will go first.")
2:
player = Player.Computer
print("The computer will go first.")
var total: int = 0
var player: Player
match randi_range(1, 2):
1:
player = Player.Human
print("You will go first.")
2:
player = Player.Computer
print("The computer will go first.")
while true:
print("\nThe total is %d" % total)
while true:
print("\nThe total is %d" % total)
var choice: int
match player:
Player.Human:
choice = get_player_choice(total)
if choice == -1:
return
Player.Computer:
choice = get_computer_choice(total)
print("The computer plays %d" % choice)
assert(1 <= choice and choice <= 3)
var choice: int
match player:
Player.Human:
choice = get_player_choice(total)
if choice == -1:
return
Player.Computer:
choice = get_computer_choice(total)
print("The computer plays %d" % choice)
assert(1 <= choice and choice <= 3)
total += choice
if total == target:
match player:
Player.Human: print("You win!")
Player.Computer: print("The computer won, you lose.")
return
assert(total < target)
total += choice
if total == target:
match player:
Player.Human: print("You win!")
Player.Computer: print("The computer won, you lose.")
return
assert(total < target)
match player:
Player.Human: player = Player.Computer
Player.Computer: player = Player.Human
match player:
Player.Human: player = Player.Computer
Player.Computer: player = Player.Human
func _process(_delta: float) -> bool:
randomize()
play()
return true
randomize()
play()
return true

View file

@ -1,62 +1,62 @@
from random import randint
def start():
game_count=0
print("Enter q to quit at any time.\nThe computer will choose first.\nRunning total is now {}".format(game_count))
roundno=1
while game_count<21:
print("\nROUND {}: \n".format(roundno))
t = select_count(game_count)
game_count = game_count+t
print("Running total is now {}\n".format(game_count))
if game_count>=21:
print("So, commiserations, the computer has won!")
return 0
t = request_count()
if not t:
print('OK,quitting the game')
return -1
game_count = game_count+t
print("Running total is now {}\n".format(game_count))
if game_count>=21:
print("So, congratulations, you've won!")
return 1
roundno+=1
game_count=0
print("Enter q to quit at any time.\nThe computer will choose first.\nRunning total is now {}".format(game_count))
roundno=1
while game_count<21:
print("\nROUND {}: \n".format(roundno))
t = select_count(game_count)
game_count = game_count+t
print("Running total is now {}\n".format(game_count))
if game_count>=21:
print("So, commiserations, the computer has won!")
return 0
t = request_count()
if not t:
print('OK,quitting the game')
return -1
game_count = game_count+t
print("Running total is now {}\n".format(game_count))
if game_count>=21:
print("So, congratulations, you've won!")
return 1
roundno+=1
def select_count(game_count):
'''selects a random number if the game_count is less than 18. otherwise chooses the winning number'''
if game_count<18:
t= randint(1,3)
else:
t = 21-game_count
print("The computer chooses {}".format(t))
return t
'''selects a random number if the game_count is less than 18. otherwise chooses the winning number'''
if game_count<18:
t= randint(1,3)
else:
t = 21-game_count
print("The computer chooses {}".format(t))
return t
def request_count():
'''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.'''
t=""
while True:
try:
t = raw_input('Your choice 1 to 3 :')
if int(t) in [1,2,3]:
return int(t)
else:
print("Out of range, try again")
except:
if t=="q":
return None
else:
print("Invalid Entry, try again")
'''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.'''
t=""
while True:
try:
t = raw_input('Your choice 1 to 3 :')
if int(t) in [1,2,3]:
return int(t)
else:
print("Out of range, try again")
except:
if t=="q":
return None
else:
print("Invalid Entry, try again")
c=0
m=0
r=True
while r:
o = start()
if o==-1:
break
else:
c+=1 if o==0 else 0
m+=1 if o==1 else 0
print("Computer wins {0} game, human wins {1} games".format(c,m))
t = raw_input("Another game?(press y to continue):")
r = (t=="y")
o = start()
if o==-1:
break
else:
c+=1 if o==0 else 0
m+=1 if o==1 else 0
print("Computer wins {0} game, human wins {1} games".format(c,m))
t = raw_input("Another game?(press y to continue):")
r = (t=="y")

View file

@ -100,9 +100,9 @@ func choose(ch,ym)
ok
func msgBox(text) {
m = new qMessageBox(win1) {
setWindowTitle("21 Game")
setText(text)
show()
}
m = new qMessageBox(win1) {
setWindowTitle("21 Game")
setText(text)
show()
}
}

View file

@ -1,446 +0,0 @@
>>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCobol 2.0
identification division.
program-id. twentyfoursolve.
environment division.
configuration section.
repository. function all intrinsic.
input-output section.
file-control.
select count-file
assign to count-file-name
file status count-file-status
organization line sequential.
data division.
file section.
fd count-file.
01 count-record pic x(7).
working-storage section.
01 count-file-name pic x(64) value 'solutioncounts'.
01 count-file-status pic xx.
01 command-area.
03 nd pic 9.
03 number-definition.
05 n occurs 4 pic 9.
03 number-definition-9 redefines number-definition
pic 9(4).
03 command-input pic x(16).
03 command pic x(5).
03 number-count pic 9999.
03 l1 pic 99.
03 l2 pic 99.
03 expressions pic zzz,zzz,zz9.
01 number-validation.
03 px pic 99.
03 permutations value
'1234'
& '1243'
& '1324'
& '1342'
& '1423'
& '1432'
& '2134'
& '2143'
& '2314'
& '2341'
& '2413'
& '2431'
& '3124'
& '3142'
& '3214'
& '3241'
& '3423'
& '3432'
& '4123'
& '4132'
& '4213'
& '4231'
& '4312'
& '4321'.
05 permutation occurs 24 pic x(4).
03 cpx pic 9.
03 current-permutation pic x(4).
03 od1 pic 9.
03 od2 pic 9.
03 od3 pic 9.
03 operator-definitions pic x(4) value '+-*/'.
03 cox pic 9.
03 current-operators pic x(3).
03 rpn-forms value
'nnonono'
& 'nnonnoo'
& 'nnnonoo'
& 'nnnoono'
& 'nnnnooo'.
05 rpn-form occurs 5 pic x(7).
03 rpx pic 9.
03 current-rpn-form pic x(7).
01 calculation-area.
03 oqx pic 99.
03 output-queue pic x(7).
03 work-number pic s9999.
03 top-numerator pic s9999 sign leading separate.
03 top-denominator pic s9999 sign leading separate.
03 rsx pic 9.
03 result-stack occurs 8.
05 numerator pic s9999.
05 denominator pic s9999.
03 divide-by-zero-error pic x.
01 totals.
03 s pic 999.
03 s-lim pic 999 value 600.
03 s-max pic 999 value 0.
03 solution occurs 600 pic x(7).
03 sc pic 999.
03 sc1 pic 999.
03 sc2 pic 9.
03 sc-max pic 999 value 0.
03 sc-lim pic 999 value 600.
03 solution-counts value zeros.
05 solution-count occurs 600 pic 999.
03 ns pic 9999.
03 ns-max pic 9999 value 0.
03 ns-lim pic 9999 value 6561.
03 number-solutions occurs 6561.
05 ns-number pic x(4).
05 ns-count pic 999.
03 record-counts pic 9999.
03 total-solutions pic 9999.
01 infix-area.
03 i pic 9.
03 i-s pic 9.
03 i-s1 pic 9.
03 i-work pic x(16).
03 i-stack occurs 7 pic x(13).
procedure division.
start-twentyfoursolve.
display 'start twentyfoursolve'
perform display-instructions
perform get-command
perform until command-input = spaces
display space
initialize command number-count
unstring command-input delimited by all space
into command number-count
move command-input to number-definition
move spaces to command-input
evaluate command
when 'h'
when 'help'
perform display-instructions
when 'list'
if ns-max = 0
perform load-solution-counts
end-if
perform list-counts
when 'show'
if ns-max = 0
perform load-solution-counts
end-if
perform show-numbers
when other
if number-definition-9 not numeric
display 'invalid number'
else
perform get-solutions
perform display-solutions
end-if
end-evaluate
if command-input = spaces
perform get-command
end-if
end-perform
display 'exit twentyfoursolve'
stop run
.
display-instructions.
display space
display 'enter a number <n> as four integers from 1-9 to see its solutions'
display 'enter list to see counts of solutions for all numbers'
display 'enter show <n> to see numbers having <n> solutions'
display '<enter> ends the program'
.
get-command.
display space
move spaces to command-input
display '(h for help)?' with no advancing
accept command-input
.
ask-for-more.
display space
move 0 to l1
add 1 to l2
if l2 = 10
display 'more (<enter>)?' with no advancing
accept command-input
move 0 to l2
end-if
.
list-counts.
add 1 to sc-max giving sc
display 'there are ' sc ' solution counts'
display space
display 'solutions/numbers'
move 0 to l1
move 0 to l2
perform varying sc from 1 by 1 until sc > sc-max
or command-input <> spaces
if solution-count(sc) > 0
subtract 1 from sc giving sc1 *> offset to capture zero counts
display sc1 '/' solution-count(sc) space with no advancing
add 1 to l1
if l1 = 8
perform ask-for-more
end-if
end-if
end-perform
if l1 > 0
display space
end-if
.
show-numbers. *> with number-count solutions
add 1 to number-count giving sc1 *> offset for zero count
evaluate true
when number-count >= sc-max
display 'no number has ' number-count ' solutions'
exit paragraph
when solution-count(sc1) = 1 and number-count = 1
display '1 number has 1 solution'
when solution-count(sc1) = 1
display '1 number has ' number-count ' solutions'
when number-count = 1
display solution-count(sc1) ' numbers have 1 solution'
when other
display solution-count(sc1) ' numbers have ' number-count ' solutions'
end-evaluate
display space
move 0 to l1
move 0 to l2
perform varying ns from 1 by 1 until ns > ns-max
or command-input <> spaces
if ns-count(ns) = number-count
display ns-number(ns) space with no advancing
add 1 to l1
if l1 = 14
perform ask-for-more
end-if
end-if
end-perform
if l1 > 0
display space
end-if
.
display-solutions.
evaluate s-max
when 0 display number-definition ' has no solutions'
when 1 display number-definition ' has 1 solution'
when other display number-definition ' has ' s-max ' solutions'
end-evaluate
display space
move 0 to l1
move 0 to l2
perform varying s from 1 by 1 until s > s-max
or command-input <> spaces
*> convert rpn solution(s) to infix
move 0 to i-s
perform varying i from 1 by 1 until i > 7
if solution(s)(i:1) >= '1' and <= '9'
add 1 to i-s
move solution(s)(i:1) to i-stack(i-s)
else
subtract 1 from i-s giving i-s1
move spaces to i-work
string '(' i-stack(i-s1) solution(s)(i:1) i-stack(i-s) ')'
delimited by space into i-work
move i-work to i-stack(i-s1)
subtract 1 from i-s
end-if
end-perform
display solution(s) space i-stack(1) space space with no advancing
add 1 to l1
if l1 = 3
perform ask-for-more
end-if
end-perform
if l1 > 0
display space
end-if
.
load-solution-counts.
move 0 to ns-max *> numbers and their solution count
move 0 to sc-max *> solution counts
move spaces to count-file-status
open input count-file
if count-file-status <> '00'
perform create-count-file
move 0 to ns-max *> numbers and their solution count
move 0 to sc-max *> solution counts
open input count-file
end-if
read count-file
move 0 to record-counts
move zeros to solution-counts
perform until count-file-status <> '00'
add 1 to record-counts
perform increment-ns-max
move count-record to number-solutions(ns-max)
add 1 to ns-count(ns-max) giving sc *> offset 1 for zero counts
if sc > sc-lim
display 'sc ' sc ' exceeds sc-lim ' sc-lim
stop run
end-if
if sc > sc-max
move sc to sc-max
end-if
add 1 to solution-count(sc)
read count-file
end-perform
close count-file
.
create-count-file.
open output count-file
display 'Counting solutions for all numbers'
display 'We will examine 9*9*9*9 numbers'
display 'For each number we will examine 4! permutations of the digits'
display 'For each permutation we will examine 4*4*4 combinations of operators'
display 'For each permutation and combination we will examine 5 rpn forms'
display 'We will count the number of unique solutions for the given number'
display 'Each number and its counts will be written to file ' trim(count-file-name)
compute expressions = 9*9*9*9*factorial(4)*4*4*4*5
display 'So we will evaluate ' trim(expressions) ' statements'
display 'This will take a few minutes'
display 'In the future if ' trim(count-file-name) ' exists, this step will be bypassed'
move 0 to record-counts
move 0 to total-solutions
perform varying n(1) from 1 by 1 until n(1) = 0
perform varying n(2) from 1 by 1 until n(2) = 0
display n(1) n(2) '..' *> show progress
perform varying n(3) from 1 by 1 until n(3) = 0
perform varying n(4) from 1 by 1 until n(4) = 0
perform get-solutions
perform increment-ns-max
move number-definition to ns-number(ns-max)
move s-max to ns-count(ns-max)
move number-solutions(ns-max) to count-record
write count-record
add s-max to total-solutions
add 1 to record-counts
add 1 to ns-count(ns-max) giving sc *> offset by 1 for zero counts
if sc > sc-lim
display 'error: ' sc ' solution count exceeds ' sc-lim
stop run
end-if
add 1 to solution-count(sc)
end-perform
end-perform
end-perform
end-perform
close count-file
display record-counts ' numbers and counts written to ' trim(count-file-name)
display total-solutions ' total solutions'
display space
.
increment-ns-max.
if ns-max >= ns-lim
display 'error: numbers exceeds ' ns-lim
stop run
end-if
add 1 to ns-max
.
get-solutions.
move 0 to s-max
perform varying px from 1 by 1 until px > 24
move permutation(px) to current-permutation
perform varying od1 from 1 by 1 until od1 > 4
move operator-definitions(od1:1) to current-operators(1:1)
perform varying od2 from 1 by 1 until od2 > 4
move operator-definitions(od2:1) to current-operators(2:1)
perform varying od3 from 1 by 1 until od3 > 4
move operator-definitions(od3:1) to current-operators(3:1)
perform varying rpx from 1 by 1 until rpx > 5
move rpn-form(rpx) to current-rpn-form
move 0 to cpx cox
move spaces to output-queue
perform varying oqx from 1 by 1 until oqx > 7
if current-rpn-form(oqx:1) = 'n'
add 1 to cpx
move current-permutation(cpx:1) to nd
move n(nd) to output-queue(oqx:1)
else
add 1 to cox
move current-operators(cox:1) to output-queue(oqx:1)
end-if
end-perform
perform evaluate-rpn
if divide-by-zero-error = space
and 24 * top-denominator = top-numerator
perform varying s from 1 by 1 until s > s-max
or solution(s) = output-queue
continue
end-perform
if s > s-max
if s >= s-lim
display 'error: solutions ' s ' for ' number-definition ' exceeds ' s-lim
stop run
end-if
move s to s-max
move output-queue to solution(s-max)
end-if
end-if
end-perform
end-perform
end-perform
end-perform
end-perform
.
evaluate-rpn.
move space to divide-by-zero-error
move 0 to rsx *> stack depth
perform varying oqx from 1 by 1 until oqx > 7
if output-queue(oqx:1) >= '1' and <= '9'
*> push the digit onto the stack
add 1 to rsx
move top-numerator to numerator(rsx)
move top-denominator to denominator(rsx)
move output-queue(oqx:1) to top-numerator
move 1 to top-denominator
else
*> apply the operation
evaluate output-queue(oqx:1)
when '+'
compute top-numerator = top-numerator * denominator(rsx)
+ top-denominator * numerator(rsx)
compute top-denominator = top-denominator * denominator(rsx)
when '-'
compute top-numerator = top-denominator * numerator(rsx)
- top-numerator * denominator(rsx)
compute top-denominator = top-denominator * denominator(rsx)
when '*'
compute top-numerator = top-numerator * numerator(rsx)
compute top-denominator = top-denominator * denominator(rsx)
when '/'
compute work-number = numerator(rsx) * top-denominator
compute top-denominator = denominator(rsx) * top-numerator
if top-denominator = 0
move 'y' to divide-by-zero-error
exit paragraph
end-if
move work-number to top-numerator
end-evaluate
*> pop the stack
subtract 1 from rsx
end-if
end-perform
.
end program twentyfoursolve.

View file

@ -1,172 +0,0 @@
with Ada.Float_Text_IO;
with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Game_24 is
subtype Digit is Character range '1' .. '9';
package Random_Digit is new Ada.Numerics.Discrete_Random (Digit);
Exp_Error : exception;
Digit_Generator : Random_Digit.Generator;
Given_Digits : array (1 .. 4) of Digit;
Float_Value : constant array (Digit) of Float :=
(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
function Apply_Op (L, R : Float; Op : Character) return Float is
begin
case Op is
when '+' =>
return L + R;
when '-' =>
return L - R;
when '*' =>
return L * R;
when '/' =>
return L / R;
when others =>
Ada.Text_IO.Put_Line ("Unexpected operator: " & Op);
raise Exp_Error;
end case;
end Apply_Op;
function Eval_Exp (E : String) return Float is
Flt : Float;
First : Positive := E'First;
Last : Positive;
function Match_Paren (Start : Positive) return Positive is
Pos : Positive := Start + 1;
Level : Natural := 1;
begin
loop
if Pos > E'Last then
Ada.Text_IO.Put_Line ("Unclosed parentheses.");
raise Exp_Error;
elsif E (Pos) = '(' then
Level := Level + 1;
elsif E (Pos) = ')' then
Level := Level - 1;
exit when Level = 0;
end if;
Pos := Pos + 1;
end loop;
return Pos;
end Match_Paren;
begin
if E (First) = '(' then
Last := Match_Paren (First);
Flt := Eval_Exp (E (First + 1 .. Last - 1));
elsif E (First) in Digit then
Last := First;
Flt := Float_Value (E (First));
else
Ada.Text_IO.Put_Line ("Unexpected character: " & E (First));
raise Exp_Error;
end if;
loop
if Last = E'Last then
return Flt;
elsif Last = E'Last - 1 then
Ada.Text_IO.Put_Line ("Unexpected end of expression.");
raise Exp_Error;
end if;
First := Last + 2;
if E (First) = '(' then
Last := Match_Paren (First);
Flt := Apply_Op (Flt, Eval_Exp (E (First + 1 .. Last - 1)),
Op => E (First - 1));
elsif E (First) in Digit then
Last := First;
Flt := Apply_Op (Flt, Float_Value (E (First)),
Op => E (First - 1));
else
Ada.Text_IO.Put_Line ("Unexpected character: " & E (First));
raise Exp_Error;
end if;
end loop;
end Eval_Exp;
begin
Ada.Text_IO.Put_Line ("24 Game");
Ada.Text_IO.Put_Line ("- Enter Q to Quit");
Ada.Text_IO.Put_Line ("- Enter N for New digits");
Ada.Text_IO.Put_Line ("Note: Operators are evaluated left-to-right");
Ada.Text_IO.Put_Line (" (use parentheses to override)");
Random_Digit.Reset (Digit_Generator);
<<GEN_DIGITS>>
Ada.Text_IO.Put_Line ("Generating 4 digits...");
for I in Given_Digits'Range loop
Given_Digits (I) := Random_Digit.Random (Digit_Generator);
end loop;
<<GET_EXP>>
Ada.Text_IO.Put ("Your Digits:");
for I in Given_Digits'Range loop
Ada.Text_IO.Put (" " & Given_Digits (I));
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("Enter your Expression: ");
declare
Value : Float;
Response : constant String := Ada.Text_IO.Get_Line;
Prev_Ch : Character := ' ';
Unused_Digits : array (Given_Digits'Range) of Boolean :=
(others => True);
begin
if Response = "n" or Response = "N" then
goto GEN_DIGITS;
end if;
if Response = "q" or Response = "Q" then
return;
end if;
-- check input
for I in Response'Range loop
declare
Ch : constant Character := Response (I);
Found : Boolean;
begin
if Ch in Digit then
if Prev_Ch in Digit then
Ada.Text_IO.Put_Line ("Illegal multi-digit number used.");
goto GET_EXP;
end if;
Found := False;
for J in Given_Digits'Range loop
if Unused_Digits (J) and then
Given_Digits (J) = Ch then
Unused_Digits (J) := False;
Found := True;
exit;
end if;
end loop;
if not Found then
Ada.Text_IO.Put_Line ("Illegal number used: " & Ch);
goto GET_EXP;
end if;
elsif Ch /= '(' and Ch /= ')' and Ch /= '+' and
Ch /= '-' and Ch /= '*' and Ch /= '/' then
Ada.Text_IO.Put_Line ("Illegal character used: " & Ch);
goto GET_EXP;
end if;
Prev_Ch := Ch;
end;
end loop;
-- check all digits used
for I in Given_Digits'Range loop
if Unused_Digits (I) then
Ada.Text_IO.Put_Line ("Digit not used: " & Given_Digits (I));
goto GET_EXP;
end if;
end loop;
-- check value
begin
Value := Eval_Exp (Response);
exception
when Exp_Error =>
goto GET_EXP; -- Message displayed by Eval_Exp;
end;
if abs (Value - 24.0) > 0.001 then
Ada.Text_IO.Put ("Value ");
Ada.Float_Text_IO.Put (Value, Fore => 0, Aft => 3, Exp => 0);
Ada.Text_IO.Put_Line (" is not 24!");
goto GET_EXP;
else
Ada.Text_IO.Put_Line ("You won!");
Ada.Text_IO.Put_Line ("Enter N for a new game, or try another solution.");
goto GET_EXP;
end if;
end;
end Game_24;

View file

@ -28,11 +28,10 @@ result: 0
while [result<>24][
got: input "Enter an expression to form 24: "
blo: to :block got
if? validExpression? blo [
switch validExpression? blo [
result: do blo
print ["The result is:" result]
]
else [
][
print "Invalid expression. Please try again!"
]
print ""

View file

@ -1,74 +0,0 @@
;AutoIt Script Example
;by Daniel Barnes
;spam me at djbarnes at orcon dot net dot en zed
;13/08/2012
;Choose four random digits (1-9) with repetitions allowed:
global $digits
FOR $i = 1 TO 4
$digits &= Random(1,9,1)
NEXT
While 1
main()
WEnd
Func main()
$text = "Enter an equation (using all of, and only, the single digits "&$digits &")"&@CRLF
$text &= "which evaluates to exactly 24. Only multiplication (*) division (/)"&@CRLF
$text &= "addition (+) and subtraction (-) operations and parentheses are allowed:"
$input = InputBox ("24 Game",$text,"","",400,150)
If @error Then exit
;remove any spaces in input
$input = StringReplace($input," ","")
;check correct characters were used
For $i = 1 To StringLen($input)
$chr = StringMid($input,$i,1)
If Not StringInStr("123456789*/+-()",$chr) Then
MsgBox (0, "ERROR","Invalid character used: '"&$chr&"'")
return
endif
Next
;validate the equation uses all of the 4 characters, and nothing else
$test = $input
$test = StringReplace($test,"(","")
$test = StringReplace($test,")","")
;validate the length of the input - if its not 7 characters long then the user has done something wrong
If StringLen ($test) <> 7 Then
MsgBox (0,"ERROR","The equation "&$test&" is invalid")
return
endif
$test = StringReplace($test,"/","")
$test = StringReplace($test,"*","")
$test = StringReplace($test,"-","")
$test = StringReplace($test,"+","")
For $i = 1 To StringLen($digits)
$digit = StringMid($digits,$i,1)
For $ii = 1 To StringLen($test)
If StringMid($test,$ii,1) = $digit Then
$test = StringLeft($test,$ii-1) & StringRight($test,StringLen($test)-$ii)
ExitLoop
endif
Next
Next
If $test <> "" Then
MsgBox (0, "ERROR", "The equation didn't use all 4 characters, and nothing else!")
return
endif
$try = Execute($input)
If $try = 24 Then
MsgBox (0, "24 Game","Well done. Your equation ("&$input&") = 24!")
Exit
Else
MsgBox (0, "24 Game","Fail. Your equation ("&$input&") = "&$try&"!")
return
endif
EndFunc

View file

@ -1,843 +0,0 @@
>>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCobol 2.0
identification division.
program-id. twentyfour.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01 p pic 999.
01 p1 pic 999.
01 p-max pic 999 value 38.
01 program-syntax pic x(494) value
*>statement = expression;
'001 001 000 n'
& '002 000 004 ='
& '003 005 000 n'
& '004 000 002 ;'
*>expression = term, {('+'|'-') term,};
& '005 005 000 n'
& '006 000 016 ='
& '007 017 000 n'
& '008 000 015 {'
& '009 011 013 ('
& '010 001 000 t'
& '011 013 000 |'
& '012 002 000 t'
& '013 000 009 )'
& '014 017 000 n'
& '015 000 008 }'
& '016 000 006 ;'
*>term = factor, {('*'|'/') factor,};
& '017 017 000 n'
& '018 000 028 ='
& '019 029 000 n'
& '020 000 027 {'
& '021 023 025 ('
& '022 003 000 t'
& '023 025 000 |'
& '024 004 000 t'
& '025 000 021 )'
& '026 029 000 n'
& '027 000 020 }'
& '028 000 018 ;'
*>factor = ('(' expression, ')' | digit,);
& '029 029 000 n'
& '030 000 038 ='
& '031 035 037 ('
& '032 005 000 t'
& '033 005 000 n'
& '034 006 000 t'
& '035 037 000 |'
& '036 000 000 n'
& '037 000 031 )'
& '038 000 030 ;'.
01 filler redefines program-syntax.
03 p-entry occurs 038.
05 p-address pic 999.
05 filler pic x.
05 p-definition pic 999.
05 p-alternate redefines p-definition pic 999.
05 filler pic x.
05 p-matching pic 999.
05 filler pic x.
05 p-symbol pic x.
01 t pic 999.
01 t-len pic 99 value 6.
01 terminal-symbols
pic x(210) value
'01 + '
& '01 - '
& '01 * '
& '01 / '
& '01 ( '
& '01 ) '.
01 filler redefines terminal-symbols.
03 terminal-symbol-entry occurs 6.
05 terminal-symbol-len pic 99.
05 filler pic x.
05 terminal-symbol pic x(32).
01 nt pic 999.
01 nt-lim pic 99 value 5.
01 nonterminal-statements pic x(294) value
"000 ....,....,....,....,....,....,....,....,....,"
& "001 statement = expression; "
& "005 expression = term, {('+'|'-') term,}; "
& "017 term = factor, {('*'|'/') factor,}; "
& "029 factor = ('(' expression, ')' | digit,); "
& "036 digit; ".
01 filler redefines nonterminal-statements.
03 nonterminal-statement-entry occurs 5.
05 nonterminal-statement-number pic 999.
05 filler pic x.
05 nonterminal-statement pic x(45).
01 indent pic x(64) value all '| '.
01 interpreter-stack.
03 r pic 99. *> previous top of stack
03 s pic 99. *> current top of stack
03 s-max pic 99 value 32.
03 s-entry occurs 32.
05 filler pic x(2) value 'p='.
05 s-p pic 999. *> callers return address
05 filler pic x(4) value ' sc='.
05 s-start-control pic 999. *> sequence start address
05 filler pic x(4) value ' ec='.
05 s-end-control pic 999. *> sequence end address
05 filler pic x(4) value ' al='.
05 s-alternate pic 999. *> the next alternate
05 filler pic x(3) value ' r='.
05 s-result pic x. *> S success, F failure, N no result
05 filler pic x(3) value ' c='.
05 s-count pic 99. *> successes in a sequence
05 filler pic x(3) value ' x='.
05 s-repeat pic 99. *> repeats in a {} sequence
05 filler pic x(4) value ' nt='.
05 s-nt pic 99. *> current nonterminal
01 language-area.
03 l pic 99.
03 l-lim pic 99.
03 l-len pic 99 value 1.
03 nd pic 9.
03 number-definitions.
05 n occurs 4 pic 9.
03 nu pic 9.
03 number-use.
05 u occurs 4 pic x.
03 statement.
05 c occurs 32.
07 c9 pic 9.
01 number-validation.
03 p4 pic 99.
03 p4-lim pic 99 value 24.
03 permutations-4 pic x(96) value
'1234'
& '1243'
& '1324'
& '1342'
& '1423'
& '1432'
& '2134'
& '2143'
& '2314'
& '2341'
& '2413'
& '2431'
& '3124'
& '3142'
& '3214'
& '3241'
& '3423'
& '3432'
& '4123'
& '4132'
& '4213'
& '4231'
& '4312'
& '4321'.
03 filler redefines permutations-4.
05 permutation-4 occurs 24 pic x(4).
03 current-permutation-4 pic x(4).
03 cpx pic 9.
03 od1 pic 9.
03 od2 pic 9.
03 odx pic 9.
03 od-lim pic 9 value 4.
03 operator-definitions pic x(4) value '+-*/'.
03 current-operators pic x(3).
03 co3 pic 9.
03 rpx pic 9.
03 rpx-lim pic 9 value 4.
03 valid-rpn-forms pic x(28) value
'nnonono'
& 'nnnonoo'
& 'nnnoono'
& 'nnnnooo'.
03 filler redefines valid-rpn-forms.
05 rpn-form occurs 4 pic x(7).
03 current-rpn-form pic x(7).
01 calculation-area.
03 osx pic 99.
03 operator-stack pic x(32).
03 oqx pic 99.
03 oqx1 pic 99.
03 output-queue pic x(32).
03 work-number pic s9999.
03 top-numerator pic s9999 sign leading separate.
03 top-denominator pic s9999 sign leading separate.
03 rsx pic 9.
03 result-stack occurs 8.
05 numerator pic s9999.
05 denominator pic s9999.
01 error-found pic x.
01 divide-by-zero-error pic x.
*> diagnostics
01 NL pic x value x'0A'.
01 NL-flag pic x value space.
01 display-level pic x value '0'.
01 loop-lim pic 9999 value 1500.
01 loop-count pic 9999 value 0.
01 message-area value spaces.
03 message-level pic x.
03 message-value pic x(128).
*> input and examples
01 instruction pic x(32) value spaces.
01 tsx pic 99.
01 tsx-lim pic 99 value 14.
01 test-statements.
03 filler pic x(32) value '1234;1 + 2 + 3 + 4'.
03 filler pic x(32) value '1234;1 * 2 * 3 * 4'.
03 filler pic x(32) value '1234;((1)) * (((2 * 3))) * 4'.
03 filler pic x(32) value '1234;((1)) * ((2 * 3))) * 4'.
03 filler pic x(32) value '1234;(1 + 2 + 3 + 4'.
03 filler pic x(32) value '1234;)1 + 2 + 3 + 4'.
03 filler pic x(32) value '1234;1 * * 2 * 3 * 4'.
03 filler pic x(32) value '5679;6 - (5 - 7) * 9'.
03 filler pic x(32) value '1268;((1 * (8 * 6) / 2))'.
03 filler pic x(32) value '4583;-5-3+(8*4)'.
03 filler pic x(32) value '4583;8 * 4 - 5 - 3'.
03 filler pic x(32) value '4583;8 * 4 - (5 + 3)'.
03 filler pic x(32) value '1223;1 * 3 / (2 - 2)'.
03 filler pic x(32) value '2468;(6 * 8) / 4 / 2'.
01 filler redefines test-statements.
03 filler occurs 14.
05 test-numbers pic x(4).
05 filler pic x.
05 test-statement pic x(27).
procedure division.
start-twentyfour.
display 'start twentyfour'
perform generate-numbers
display 'type h <enter> to see instructions'
accept instruction
perform until instruction = spaces or 'q'
evaluate true
when instruction = 'h'
perform display-instructions
when instruction = 'n'
perform generate-numbers
when instruction(1:1) = 'm'
move instruction(2:4) to number-definitions
perform validate-number
if divide-by-zero-error = space
and 24 * top-denominator = top-numerator
display number-definitions ' is solved by ' output-queue(1:oqx)
else
display number-definitions ' is not solvable'
end-if
when instruction = 'd0' or 'd1' or 'd2' or 'd3'
move instruction(2:1) to display-level
when instruction = 'e'
display 'examples:'
perform varying tsx from 1 by 1
until tsx > tsx-lim
move spaces to statement
move test-numbers(tsx) to number-definitions
move test-statement(tsx) to statement
perform evaluate-statement
perform show-result
end-perform
when other
move instruction to statement
perform evaluate-statement
perform show-result
end-evaluate
move spaces to instruction
display 'instruction? ' with no advancing
accept instruction
end-perform
display 'exit twentyfour'
stop run
.
generate-numbers.
perform with test after until divide-by-zero-error = space
and 24 * top-denominator = top-numerator
compute n(1) = random(seconds-past-midnight) * 10 *> seed
perform varying nd from 1 by 1 until nd > 4
compute n(nd) = random() * 10
perform until n(nd) <> 0
compute n(nd) = random() * 10
end-perform
end-perform
perform validate-number
end-perform
display NL 'numbers:' with no advancing
perform varying nd from 1 by 1 until nd > 4
display space n(nd) with no advancing
end-perform
display space
.
validate-number.
perform varying p4 from 1 by 1 until p4 > p4-lim
move permutation-4(p4) to current-permutation-4
perform varying od1 from 1 by 1 until od1 > od-lim
move operator-definitions(od1:1) to current-operators(1:1)
perform varying od2 from 1 by 1 until od2 > od-lim
move operator-definitions(od2:1) to current-operators(2:1)
perform varying odx from 1 by 1 until odx > od-lim
move operator-definitions(odx:1) to current-operators(3:1)
perform varying rpx from 1 by 1 until rpx > rpx-lim
move rpn-form(rpx) to current-rpn-form
move 0 to cpx co3
move spaces to output-queue
move 7 to oqx
perform varying oqx1 from 1 by 1 until oqx1 > oqx
if current-rpn-form(oqx1:1) = 'n'
add 1 to cpx
move current-permutation-4(cpx:1) to nd
move n(nd) to output-queue(oqx1:1)
else
add 1 to co3
move current-operators(co3:1) to output-queue(oqx1:1)
end-if
end-perform
end-perform
perform evaluate-rpn
if divide-by-zero-error = space
and 24 * top-denominator = top-numerator
exit paragraph
end-if
end-perform
end-perform
end-perform
end-perform
.
display-instructions.
display '1) Type h <enter> to repeat these instructions.'
display '2) The program will display four randomly-generated'
display ' single-digit numbers and will then prompt you to enter'
display ' an arithmetic expression followed by <enter> to sum'
display ' the given numbers to 24.'
display ' The four numbers may contain duplicates and the entered'
display ' expression must reference all the generated numbers and duplicates.'
display ' Warning: the program converts the entered infix expression'
display ' to a reverse polish notation (rpn) expression'
display ' which is then interpreted from RIGHT to LEFT.'
display ' So, for instance, 8*4 - 5 - 3 will not sum to 24.'
display '3) Type n <enter> to generate a new set of four numbers.'
display ' The program will ensure the generated numbers are solvable.'
display '4) Type m#### <enter> (e.g. m1234) to create a fixed set of numbers'
display ' for testing purposes.'
display ' The program will test the solvability of the entered numbers.'
display ' For example, m1234 is solvable and m9999 is not solvable.'
display '5) Type d0, d1, d2 or d3 followed by <enter> to display none or'
display ' increasingly detailed diagnostic information as the program evaluates'
display ' the entered expression.'
display '6) Type e <enter> to see a list of example expressions and results'
display '7) Type <enter> or q <enter> to exit the program'
.
show-result.
if error-found = 'y'
or divide-by-zero-error = 'y'
exit paragraph
end-if
display 'statement in RPN is' space output-queue
evaluate true
when top-numerator = 0
when top-denominator = 0
when 24 * top-denominator <> top-numerator
display 'result (' top-numerator '/' top-denominator ') is not 24'
when other
display 'result is 24'
end-evaluate
.
evaluate-statement.
compute l-lim = length(trim(statement))
display NL 'numbers:' space n(1) space n(2) space n(3) space n(4)
move number-definitions to number-use
display 'statement is' space statement
move 1 to l
move 0 to loop-count
move space to error-found
move 0 to osx oqx
move spaces to output-queue
move 1 to p
move 1 to nt
move 0 to s
perform increment-s
perform display-start-nonterminal
perform increment-p
*>===================================
*> interpret ebnf
*>===================================
perform until s = 0
or error-found = 'y'
evaluate true
when p-symbol(p) = 'n'
and p-definition(p) = 000 *> a variable
perform test-variable
if s-result(s) = 'S'
perform increment-l
end-if
perform increment-p
when p-symbol(p) = 'n'
and p-address(p) <> p-definition(p) *> nonterminal reference
move p to s-p(s)
move p-definition(p) to p
when p-symbol(p) = 'n'
and p-address(p) = p-definition(p) *> nonterminal definition
perform increment-s
perform display-start-nonterminal
perform increment-p
when p-symbol(p) = '=' *> nonterminal control
move p to s-start-control(s)
move p-matching(p) to s-end-control(s)
perform increment-p
when p-symbol(p) = ';' *> end nonterminal
perform display-end-control
perform display-end-nonterminal
perform decrement-s
if s > 0
evaluate true
when s-result(r) = 'S'
perform set-success
when s-result(r) = 'F'
perform set-failure
end-evaluate
move s-p(s) to p
perform increment-p
perform display-continue-nonterminal
end-if
when p-symbol(p) = '{' *> start repeat sequence
perform increment-s
perform display-start-control
move p to s-start-control(s)
move p-alternate(p) to s-alternate(s)
move p-matching(p) to s-end-control(s)
move 0 to s-count(s)
perform increment-p
when p-symbol(p) = '}' *> end repeat sequence
perform display-end-control
evaluate true
when s-result(s) = 'S' *> repeat the sequence
perform display-repeat-control
perform set-nothing
add 1 to s-repeat(s)
move s-start-control(s) to p
perform increment-p
when other
perform decrement-s
evaluate true
when s-result(r) = 'N'
and s-repeat(r) = 0 *> no result
perform increment-p
when s-result(r) = 'N'
and s-repeat(r) > 0 *> no result after success
perform set-success
perform increment-p
when other *> fail the sequence
perform increment-p
end-evaluate
end-evaluate
when p-symbol(p) = '(' *> start sequence
perform increment-s
perform display-start-control
move p to s-start-control(s)
move p-alternate(p) to s-alternate(s)
move p-matching(p) to s-end-control(s)
move 0 to s-count(s)
perform increment-p
when p-symbol(p) = ')' *> end sequence
perform display-end-control
perform decrement-s
evaluate true
when s-result(r) = 'S' *> success
perform set-success
perform increment-p
when s-result(r) = 'N' *> no result
perform set-failure
perform increment-p
when other *> fail the sequence
perform set-failure
perform increment-p
end-evaluate
when p-symbol(p) = '|' *> alternate
evaluate true
when s-result(s) = 'S' *> exit the sequence
perform display-skip-alternate
move s-end-control(s) to p
when other
perform display-take-alternate
move p-alternate(p) to s-alternate(s) *> the next alternate
perform increment-p
perform set-nothing
end-evaluate
when p-symbol(p) = 't' *> terminal
move p-definition(p) to t
move terminal-symbol-len(t) to t-len
perform display-terminal
evaluate true
when statement(l:t-len) = terminal-symbol(t)(1:t-len) *> successful match
perform set-success
perform display-recognize-terminal
perform process-token
move t-len to l-len
perform increment-l
perform increment-p
when s-alternate(s) <> 000 *> we are in an alternate sequence
move s-alternate(s) to p
when other *> fail the sequence
perform set-failure
move s-end-control(s) to p
end-evaluate
when other *> end control
perform display-control-failure *> shouldnt happen
end-evaluate
end-perform
evaluate true *> at end of evaluation
when error-found = 'y'
continue
when l <= l-lim *> not all tokens parsed
display 'error: invalid statement'
perform statement-error
when number-use <> spaces
display 'error: not all numbers were used: ' number-use
move 'y' to error-found
end-evaluate
.
increment-l.
evaluate true
when l > l-lim *> end of statement
continue
when other
add l-len to l
perform varying l from l by 1
until c(l) <> space
or l > l-lim
continue
end-perform
move 1 to l-len
if l > l-lim
perform end-tokens
end-if
end-evaluate
.
increment-p.
evaluate true
when p >= p-max
display 'at' space p ' parse overflow'
space 's=<' s space s-entry(s) '>'
move 'y' to error-found
when other
add 1 to p
perform display-statement
end-evaluate
.
increment-s.
evaluate true
when s >= s-max
display 'at' space p ' stack overflow '
space 's=<' s space s-entry(s) '>'
move 'y' to error-found
when other
move s to r
add 1 to s
initialize s-entry(s)
move 'N' to s-result(s)
move p to s-p(s)
move nt to s-nt(s)
end-evaluate
.
decrement-s.
if s > 0
move s to r
subtract 1 from s
if s > 0
move s-nt(s) to nt
end-if
end-if
.
set-failure.
move 'F' to s-result(s)
if s-count(s) > 0
display 'sequential parse failure'
perform statement-error
end-if
.
set-success.
move 'S' to s-result(s)
add 1 to s-count(s)
.
set-nothing.
move 'N' to s-result(s)
move 0 to s-count(s)
.
statement-error.
display statement
move spaces to statement
move '^ syntax error' to statement(l:)
display statement
move 'y' to error-found
.
*>=====================
*> twentyfour semantics
*>=====================
test-variable.
*> check validity
perform varying nd from 1 by 1 until nd > 4
or c(l) = n(nd)
continue
end-perform
*> check usage
perform varying nu from 1 by 1 until nu > 4
or c(l) = u(nu)
continue
end-perform
evaluate true
when l > l-lim
perform set-failure
when c9(l) not numeric
perform set-failure
when nd > 4
display 'invalid number'
perform statement-error
when nu > 4
display 'number already used'
perform statement-error
when other
move space to u(nu)
perform set-success
add 1 to oqx
move c(l) to output-queue(oqx:1)
end-evaluate
.
*> ==================================
*> Dijkstra Shunting-Yard Algorithm
*> to convert infix to rpn
*> ==================================
process-token.
evaluate true
when c(l) = '('
add 1 to osx
move c(l) to operator-stack(osx:1)
when c(l) = ')'
perform varying osx from osx by -1 until osx < 1
or operator-stack(osx:1) = '('
add 1 to oqx
move operator-stack(osx:1) to output-queue(oqx:1)
end-perform
if osx < 1
display 'parenthesis error'
perform statement-error
exit paragraph
end-if
subtract 1 from osx
when (c(l) = '+' or '-') and (operator-stack(osx:1) = '*' or '/')
*> lesser operator precedence
add 1 to oqx
move operator-stack(osx:1) to output-queue(oqx:1)
move c(l) to operator-stack(osx:1)
when other
*> greater operator precedence
add 1 to osx
move c(l) to operator-stack(osx:1)
end-evaluate
.
end-tokens.
*> 1) copy stacked operators to the output-queue
perform varying osx from osx by -1 until osx < 1
or operator-stack(osx:1) = '('
add 1 to oqx
move operator-stack(osx:1) to output-queue(oqx:1)
end-perform
if osx > 0
display 'parenthesis error'
perform statement-error
exit paragraph
end-if
*> 2) evaluate the rpn statement
perform evaluate-rpn
if divide-by-zero-error = 'y'
display 'divide by zero error'
end-if
.
evaluate-rpn.
move space to divide-by-zero-error
move 0 to rsx *> stack depth
perform varying oqx1 from 1 by 1 until oqx1 > oqx
if output-queue(oqx1:1) >= '1' and <= '9'
*> push current data onto the stack
add 1 to rsx
move top-numerator to numerator(rsx)
move top-denominator to denominator(rsx)
move output-queue(oqx1:1) to top-numerator
move 1 to top-denominator
else
*> apply the operation
evaluate true
when output-queue(oqx1:1) = '+'
compute top-numerator = top-numerator * denominator(rsx)
+ top-denominator * numerator(rsx)
compute top-denominator = top-denominator * denominator(rsx)
when output-queue(oqx1:1) = '-'
compute top-numerator = top-denominator * numerator(rsx)
- top-numerator * denominator(rsx)
compute top-denominator = top-denominator * denominator(rsx)
when output-queue(oqx1:1) = '*'
compute top-numerator = top-numerator * numerator(rsx)
compute top-denominator = top-denominator * denominator(rsx)
when output-queue(oqx1:1) = '/'
compute work-number = numerator(rsx) * top-denominator
compute top-denominator = denominator(rsx) * top-numerator
if top-denominator = 0
move 'y' to divide-by-zero-error
exit paragraph
end-if
move work-number to top-numerator
end-evaluate
*> pop the stack
subtract 1 from rsx
end-if
end-perform
.
*>====================
*> diagnostic displays
*>====================
display-start-nonterminal.
perform varying nt from nt-lim by -1 until nt < 1
or p-definition(p) = nonterminal-statement-number(nt)
continue
end-perform
if nt > 0
move '1' to NL-flag
string '1' indent(1:s + s) 'at ' s space p ' start ' trim(nonterminal-statement(nt))
into message-area perform display-message
move nt to s-nt(s)
end-if
.
display-continue-nonterminal.
move s-nt(s) to nt
string '1' indent(1:s + s) 'at ' s space p space p-symbol(p) ' continue ' trim(nonterminal-statement(nt)) ' with result ' s-result(s)
into message-area perform display-message
.
display-end-nonterminal.
move s-nt(s) to nt
move '2' to NL-flag
string '1' indent(1:s + s) 'at ' s space p ' end ' trim(nonterminal-statement(nt)) ' with result ' s-result(s)
into message-area perform display-message
.
display-start-control.
string '2' indent(1:s + s) 'at ' s space p ' start ' p-symbol(p) ' in ' trim(nonterminal-statement(nt))
into message-area perform display-message
.
display-repeat-control.
string '2' indent(1:s + s) 'at ' s space p ' repeat ' p-symbol(p) ' in ' trim(nonterminal-statement(nt)) ' with result ' s-result(s)
into message-area perform display-message
.
display-end-control.
string '2' indent(1:s + s) 'at ' s space p ' end ' p-symbol(p) ' in ' trim(nonterminal-statement(nt)) ' with result ' s-result(s)
into message-area perform display-message
.
display-take-alternate.
string '2' indent(1:s + s) 'at ' s space p ' take alternate' ' in ' trim(nonterminal-statement(nt))
into message-area perform display-message
.
display-skip-alternate.
string '2' indent(1:s + s) 'at ' s space p ' skip alternate' ' in ' trim(nonterminal-statement(nt))
into message-area perform display-message
.
display-terminal.
string '1' indent(1:s + s) 'at ' s space p
' compare ' statement(l:t-len) ' to ' terminal-symbol(t)(1:t-len)
' in ' trim(nonterminal-statement(nt))
into message-area perform display-message
.
display-recognize-terminal.
string '1' indent(1:s + s) 'at ' s space p ' recognize terminal: ' c(l) ' in ' trim(nonterminal-statement(nt))
into message-area perform display-message
.
display-recognize-variable.
string '1' indent(1:s + s) 'at ' s space p ' recognize digit: ' c(l) ' in ' trim(nonterminal-statement(nt))
into message-area perform display-message
.
display-statement.
compute p1 = p - s-start-control(s)
string '3' indent(1:s + s) 'at ' s space p
' statement: ' s-start-control(s) '/' p1
space p-symbol(p) space s-result(s)
' in ' trim(nonterminal-statement(nt))
into message-area perform display-message
.
display-control-failure.
display loop-count space indent(1:s + s) 'at' space p ' control failure' ' in ' trim(nonterminal-statement(nt))
display loop-count space indent(1:s + s) ' ' 'p=<' p p-entry(p) '>'
display loop-count space indent(1:s + s) ' ' 's=<' s space s-entry(s) '>'
display loop-count space indent(1:s + s) ' ' 'l=<' l space c(l)'>'
perform statement-error
.
display-message.
if display-level = 1
move space to NL-flag
end-if
evaluate true
when loop-count > loop-lim *> loop control
display 'display count exceeds ' loop-lim
stop run
when message-level <= display-level
evaluate true
when NL-flag = '1'
display NL loop-count space trim(message-value)
when NL-flag = '2'
display loop-count space trim(message-value) NL
when other
display loop-count space trim(message-value)
end-evaluate
end-evaluate
add 1 to loop-count
move spaces to message-area
move space to NL-flag
.
end program twentyfour.

View file

@ -3,6 +3,8 @@ import system'collections;
import system'dynamic;
import extensions;
// --- Expression ---
class ExpressionTree
{
object _tree;
@ -95,6 +97,8 @@ class ExpressionTree
<= readLeaves(list,_tree);
}
// --- Game ---
class TwentyFourGame
{
object theNumbers;
@ -108,10 +112,10 @@ class TwentyFourGame
{
theNumbers := new object[]
{
1 + randomGenerator.nextInt(9),
1 + randomGenerator.nextInt(9),
1 + randomGenerator.nextInt(9),
1 + randomGenerator.nextInt(9)
1 + Random.nextInt(9),
1 + Random.nextInt(9),
1 + Random.nextInt(9),
1 + Random.nextInt(9)
}
}
@ -184,7 +188,7 @@ extension gameOp
}
catch(Exception e)
{
Console.printLine:"An error occurred. Check your input and try again."
Console.printLine("An error occurred. Check your input and try again.")
}
};
@ -193,7 +197,9 @@ extension gameOp
}
}
public program()
// --- Program ---
public Program()
{
var game := new TwentyFourGame().help();

View file

@ -1,73 +0,0 @@
CLS
Function isNumeric ($x)
{
$x2 = 0
$isNum = [System.Int32]::TryParse($x,[ref]$x2)
Return $isNum
}
$NumberArray = @()
While( $NumberArray.Count -lt 4 ){
$NumberArray += Random -Minimum 1 -Maximum 10
}
Write-Host @"
Welcome to the 24 game!
Here are your numbers: $($NumberArray -join ",").
Use division, multiplication, subtraction and addition to get 24 as a result with these 4 numbers.
"@
Do
{
$Wrong = 0
$EndResult = $null
$TempChar = $null
$TempChar2 = $null
$Count = $null
$AllowableCharacters = $NumberArray + "+-*/()".ToCharArray()
$Result = Read-Host
Foreach($Char in $Result.ToCharArray())
{
If( $AllowableCharacters -notcontains $Char ){ $Wrong = 1 }
}
If($Wrong -eq 1)
{
Write-Warning "Wrong input! Please use only the given numbers."
}
Foreach($Char in $Result.ToCharArray())
{
If((IsNumeric $TempChar) -AND (IsNumeric $Char))
{
Write-Warning "Wrong input! Combining two or more numbers together is not allowed!"
}
$TempChar = $Char
}
Foreach($Char in $Result.ToCharArray())
{
If(IsNumeric $Char)
{
$Count++
}
}
If($Count -eq 4)
{
$EndResult = Invoke-Expression $Result
If($EndResult -eq 24)
{
Write-Host "`nYou've won the game!"
}
Else
{
Write-Host "`n$EndResult is not 24! Too bad."
}
}
Else
{
Write-Warning "Wrong input! You did not supply four numbers."
}
}
While($EndResult -ne 24)

View file

@ -1,68 +0,0 @@
with Ada.Text_IO;
procedure Puzzle_Square_4 is
procedure Four_Rings (Low, High : in Natural; Unique, Show : in Boolean) is
subtype Test_Range is Natural range Low .. High;
type Value_List is array (Positive range <>) of Natural;
function Is_Unique (Values : Value_List) return Boolean is
Count : array (Test_Range) of Natural := (others => 0);
begin
for Value of Values loop
Count (Value) := Count (Value) + 1;
if Count (Value) > 1 then
return False;
end if;
end loop;
return True;
end Is_Unique;
function Is_Valid (A,B,C,D,E,F,G : in Natural) return Boolean is
Ring_1 : constant Integer := A + B;
Ring_2 : constant Integer := B + C + D;
Ring_3 : constant Integer := D + E + F;
Ring_4 : constant Integer := F + G;
begin
return
Ring_1 = Ring_2 and
Ring_1 = Ring_3 and
Ring_1 = Ring_4;
end Is_Valid;
use Ada.Text_IO;
Count : Natural := 0;
begin
for A in Test_Range loop
for B in Test_Range loop
for C in Test_Range loop
for D in Test_Range loop
for E in Test_Range loop
for F in Test_Range loop
for G in Test_Range loop
if Is_Valid (A,B,C,D,E,F,G) then
if not Unique or (Unique and Is_Unique ((A,B,C,D,E,F,G))) then
Count := Count + 1;
if Show then
Put_Line (A'Image & B'Image & C'Image & D'Image & E'Image & F'Image & G'Image);
end if;
end if;
end if;
end loop;
end loop;
end loop;
end loop;
end loop;
end loop;
end loop;
Put_Line ("There are " & Count'Image &
(if Unique then " unique " else " non-unique ") &
"solutions in " & Low'Image & " .." & High'Image);
New_Line;
end Four_Rings;
begin
Four_Rings (Low => 1, High => 7, Unique => True, Show => True);
Four_Rings (Low => 3, High => 9, Unique => True, Show => True);
Four_Rings (Low => 0, High => 9, Unique => False, Show => False);
end Puzzle_Square_4;

View file

@ -1,142 +0,0 @@
with Ada.Text_IO;
with Ada.Numerics.Big_Numbers.Big_Integers;
procedure Names_Of_God is
NN : constant := 100_000;
Row_Count : constant := 25;
Max_Column : constant := 79;
package Triangle is
procedure Print;
end Triangle;
package Row_Summer is
procedure Calc (N : Integer);
procedure Put_Sums;
end Row_Summer;
package body Row_Summer is
use Ada.Text_IO;
use Ada.Numerics.Big_Numbers.Big_Integers;
P : array (0 .. NN + 1) of Big_Integer := (1, others => 0);
procedure Calc (N : Integer) is
begin
P (N) := 0;
for K in 1 .. N + 1 loop
declare
Add : constant Boolean := K mod 2 /= 0;
D_1 : constant Integer := N - K * (3 * K - 1) / 2;
D_2 : constant Integer := D_1 - K;
begin
exit when D_1 < 0;
if Add
then P (N) := P (N) + P (D_1);
else P (N) := P (N) - P (D_1);
end if;
exit when D_2 < 0;
if Add
then P (N) := P (N) + P (D_2);
else P (N) := P (N) - P (D_2);
end if;
end;
end loop;
end Calc;
procedure Put_Wrapped (Item : Big_Integer) is
Image : constant String := To_String (Item);
begin
Set_Col (11);
for I in Image'Range loop
if Ada.Text_IO.Col >= Max_Column then
Set_Col (12);
end if;
Put (Image (I));
end loop;
end Put_Wrapped;
procedure Put_Sums
is
package Integer_IO is new Ada.Text_IO.Integer_IO (Integer);
Printout : constant array (Natural range <>) of Integer :=
(23, 123, 1234, 12_345, 20_000, 30_000, 40_000, 50_000, NN);
Next : Natural := Printout'First;
begin
for A in 1 .. Printout (Printout'Last) loop
Calc (A);
if A = Printout (Next) then
Put ("G (");
Integer_IO.Put (A, Width => 0);
Put (")");
Put_Wrapped (P (A));
New_Line;
Next := Next + 1;
end if;
end loop;
end Put_Sums;
end Row_Summer;
package body Triangle is
Triangle : array (0 .. Row_Count,
0 .. Row_Count) of Integer := (others => (others => 0));
procedure Calculate is
begin
Triangle (1,1) := 1;
Triangle (2,1) := 1;
Triangle (2,2) := 1;
Triangle (3,1) := 1;
Triangle (3,2) := 1;
Triangle (3,3) := 1;
for Row in 4 .. Row_Count loop
for Col in 1 .. Row loop
if Col * 2 > Row then
Triangle (Row, Col) := Triangle (Row - 1, Col - 1);
else
Triangle (Row, Col) :=
Triangle (Row - 1, Col - 1) +
Triangle (Row - Col, Col);
end if;
end loop;
end loop;
end Calculate;
procedure Print
is
use Ada.Text_IO;
Width : array (1 .. Row_Count) of Natural := (others => 0);
begin
for Row in 1 .. Row_count loop
for Col in 1 .. Row loop
Width (Row) := Width (Row) + Triangle (Row, Col)'Image'Length;
end loop;
end loop;
for Row in 1 .. Row_Count loop
Set_Col (1 + Positive_Count (1 + Width (Width'Last)
- Width (Row)) / 2);
for Col in 1 .. Row loop
Put (Triangle (Row, Col)'Image);
end loop;
New_Line;
end loop;
end Print;
begin
Calculate;
end Triangle;
begin
Triangle.Print;
Row_Summer.Put_Sums;
end Names_Of_God;

View file

@ -1,4 +1,4 @@
def partitions(c)
static def partitions(c)
{
def p=[];

View file

@ -1,101 +0,0 @@
Rebol [
title: "Rosetta code: 9 billion names of God the integer"
file: %9_billion_names_of_God_the_integer.r3
url: https://rosettacode.org/wiki/9_billion_names_of_God_the_integer
needs: 3.0.0
note: {Based on Red language version}
]
names-of-god: function/with [
row [integer!] "row number (>= 1)"
/show "Display intermediate results"
/all "When showing, print all intermediate data"
][
;; Validate input - require row >= 1, otherwise trigger a runtime error
assert [row >= 1]
;; If /show refinement is used, display results for the given row
if show [
;; Ensure nums/:row is computed; if not, recursively compute it
unless nums/:row [names-of-god row]
;; Loop from 1 to row
repeat i row [
either all [ ;; If /all refinement is used, display extra details
probe reduce [i nums/:i sums/:i] ;; Show index, sequence, and sum
][
print nums/:i ;; Otherwise, just print the sequence
]
]
]
;; Compute a new row from scratch (if row not already computed)...
unless sum: sums/:row [
out: clear [] ;; Temporary storage for row's elements
half: to integer! row / 2 ;; Middle position of the row
;; Ensure all required previous rows exist; generate missing ones
if row - 1 > last: length? nums [
repeat i row - last - 1 [
names-of-god last + i
]
]
;; Build the `out` block for this row
repeat col row - 1 [
;; Special case: the middle element
either col = (half + 1) [
append out at nums/(row - 1) half ;; Insert from previous row's middle
break ;; Stop building here
][
;; General case: append sum-part of two earlier sequences
append out sum-part nums/(row - col) col
]
]
;; Compute the sum of the row
sum: 0.0
forall out [
sum: sum + out/1
]
;; Cache the computed row and its sum
sums/:row: sum
nums/:row: copy out
clear out
]
sums/:row ;; Return sum of the row
][
;; ===== WITH BLOCK (local helper definitions and persistent state) =====
;; Helper function: sum the first `count` elements from the given block `nums`
sum-part: function [nums [block!] count [integer!]][
out: 0.0
loop count [
out: out + nums/1
if empty? nums: next nums [break] ;; Stop if we've exhausted the block
]
;; If within integer range, convert to integer
if out <= 0#7fffffffffffffff [out: to integer! out]
out
]
;; Persistent storage for each computed row (map! with row → sequence)
;; Start with base cases:
;; row 1 = [1]
;; row 2 = [1 1]
nums: make map! [1 [1] 2 [1 1]]
;; Persistent storage for row sums (map! with row → sum)
;; Base sums: row 1 sum = 1, row 2 sum = 2
sums: make map! [1 1 2 2]
]
print "rows: ^/"
names-of-god/show 25
print "^/sums: ^/"
probe names-of-god 23
probe names-of-god 123
probe names-of-god 1234

View file

@ -1,12 +0,0 @@
with Ada.Text_Io; use Ada.Text_Io;
procedure Bottles is
begin
for X in reverse 1..99 loop
Put_Line(Integer'Image(X) & " bottles of beer on the wall");
Put_Line(Integer'Image(X) & " bottles of beer");
Put_Line("Take one down, pass it around");
Put_Line(Integer'Image(X - 1) & " bottles of beer on the wall");
New_Line;
end loop;
end Bottles;

View file

@ -1,39 +0,0 @@
with Ada.Text_Io; use Ada.Text_Io;
procedure Tasking_99_Bottles is
subtype Num_Bottles is Natural range 1..99;
task Print is
entry Set (Num_Bottles);
end Print;
task body Print is
Num : Natural;
begin
for I in reverse Num_Bottles'range loop
select
accept
Set(I) do -- Rendezvous with Counter task I
Num := I;
end Set;
Put_Line(Integer'Image(Num) & " bottles of beer on the wall");
Put_Line(Integer'Image(Num) & " bottles of beer");
Put_Line("Take one down, pass it around");
Put_Line(Integer'Image(Num - 1) & " bottles of beer on the wall");
New_Line;
or terminate; -- end when all Counter tasks have completed
end select;
end loop;
end Print;
task type Counter(I : Num_Bottles);
task body Counter is
begin
Print.Set(I);
end Counter;
type Task_Access is access Counter;
Task_List : array(Num_Bottles) of Task_Access;
begin
for I in Task_List'range loop -- Create 99 Counter tasks
Task_List(I) := new Counter(I);
end loop;
end Tasking_99_Bottles;

View file

@ -6,9 +6,8 @@ loop 99..1 'i [
print ~"Take one down, pass it around!"
if 1=i-1 -> s: ""
if? i>1 [
switch i>1 [
print ~"|i-1| bottle|s| of beer on the wall!"
print ""
]
else -> print "No more bottles of beer on the wall!"
] -> print "No more bottles of beer on the wall!"
]

View file

@ -1,104 +0,0 @@
identification division.
program-id. ninety-nine.
environment division.
data division.
working-storage section.
01 counter pic 99.
88 no-bottles-left value 0.
88 one-bottle-left value 1.
01 parts-of-counter redefines counter.
05 tens pic 9.
05 digits pic 9.
01 after-ten-words.
05 filler pic x(7) value spaces.
05 filler pic x(7) value "Twenty".
05 filler pic x(7) value "Thirty".
05 filler pic x(7) value "Forty".
05 filler pic x(7) value "Fifty".
05 filler pic x(7) value "Sixty".
05 filler pic x(7) value "Seventy".
05 filler pic x(7) value "Eighty".
05 filler pic x(7) value "Ninety".
05 filler pic x(7) value spaces.
01 after-ten-array redefines after-ten-words.
05 atens occurs 10 times pic x(7).
01 digit-words.
05 filler pic x(9) value "One".
05 filler pic x(9) value "Two".
05 filler pic x(9) value "Three".
05 filler pic x(9) value "Four".
05 filler pic x(9) value "Five".
05 filler pic x(9) value "Six".
05 filler pic x(9) value "Seven".
05 filler pic x(9) value "Eight".
05 filler pic x(9) value "Nine".
05 filler pic x(9) value "Ten".
05 filler pic x(9) value "Eleven".
05 filler pic x(9) value "Twelve".
05 filler pic x(9) value "Thirteen".
05 filler pic x(9) value "Fourteen".
05 filler pic x(9) value "Fifteen".
05 filler pic x(9) value "Sixteen".
05 filler pic x(9) value "Seventeen".
05 filler pic x(9) value "Eighteen".
05 filler pic x(9) value "Nineteen".
05 filler pic x(9) value spaces.
01 digit-array redefines digit-words.
05 adigits occurs 20 times pic x(9).
01 number-name pic x(15).
procedure division.
100-main section.
100-setup.
perform varying counter from 99 by -1 until no-bottles-left
perform 100-show-number
display " of beer on the wall"
perform 100-show-number
display " of beer"
display "Take " with no advancing
if one-bottle-left
display "it " with no advancing
else
display "one " with no advancing
end-if
display "down and pass it round"
subtract 1 from counter giving counter
perform 100-show-number
display " of beer on the wall"
add 1 to counter giving counter
display space
end-perform.
display "No more bottles of beer on the wall"
display "No more bottles of beer"
display "Go to the store and buy some more"
display "Ninety Nine bottles of beer on the wall"
stop run.
100-show-number.
if no-bottles-left
display "No more" with no advancing
else
if counter < 20
display function trim( adigits( counter ) ) with no advancing
else
if counter < 100
move spaces to number-name
string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name
display function trim( number-name) with no advancing
end-if
end-if
end-if.
if one-bottle-left
display " bottle" with no advancing
else
display " bottles" with no advancing
end-if.
100-end.
end-program.

View file

@ -1,122 +0,0 @@
identification division.
program-id. ninety-nine.
environment division.
data division.
working-storage section.
01 counter pic 99.
88 no-bottles-left value 0.
88 one-bottle-left value 1.
01 parts-of-counter redefines counter.
05 tens pic 9.
05 digits pic 9.
01 after-ten-words.
05 filler pic x(7) value spaces.
05 filler pic x(7) value "Twenty".
05 filler pic x(7) value "Thirty".
05 filler pic x(7) value "Forty".
05 filler pic x(7) value "Fifty".
05 filler pic x(7) value "Sixty".
05 filler pic x(7) value "Seventy".
05 filler pic x(7) value "Eighty".
05 filler pic x(7) value "Ninety".
05 filler pic x(7) value spaces.
01 after-ten-array redefines after-ten-words.
05 atens occurs 10 times pic x(7).
01 digit-words.
05 filler pic x(9) value "One".
05 filler pic x(9) value "Two".
05 filler pic x(9) value "Three".
05 filler pic x(9) value "Four".
05 filler pic x(9) value "Five".
05 filler pic x(9) value "Six".
05 filler pic x(9) value "Seven".
05 filler pic x(9) value "Eight".
05 filler pic x(9) value "Nine".
05 filler pic x(9) value "Ten".
05 filler pic x(9) value "Eleven".
05 filler pic x(9) value "Twelve".
05 filler pic x(9) value "Thirteen".
05 filler pic x(9) value "Fourteen".
05 filler pic x(9) value "Fifteen".
05 filler pic x(9) value "Sixteen".
05 filler pic x(9) value "Seventeen".
05 filler pic x(9) value "Eighteen".
05 filler pic x(9) value "Nineteen".
05 filler pic x(9) value spaces.
01 digit-array redefines digit-words.
05 adigits occurs 20 times pic x(9).
01 number-name pic x(15).
01 stringified pic x(30).
01 outline pic x(50).
01 other-numbers.
03 n pic 999.
03 r pic 999.
procedure division.
100-main section.
100-setup.
perform varying counter from 99 by -1 until no-bottles-left
move spaces to outline
perform 100-show-number
string stringified delimited by "|", space, "of beer on the wall" into outline end-string
display outline end-display
move spaces to outline
string stringified delimited by "|", space, "of beer" into outline end-string
display outline end-display
move spaces to outline
move "Take" to outline
if one-bottle-left
string outline delimited by space, space, "it" delimited by size, space, "|" into outline end-string
else
string outline delimited by space, space, "one" delimited by size, space, "|" into outline end-string
end-if
string outline delimited by "|", "down and pass it round" delimited by size into outline end-string
display outline end-display
move spaces to outline
subtract 1 from counter giving counter end-subtract
perform 100-show-number
string stringified delimited by "|", space, "of beer on the wall" into outline end-string
display outline end-display
add 1 to counter giving counter end-add
display space end-display
end-perform.
display "No more bottles of beer on the wall"
display "No more bottles of beer"
display "Go to the store and buy some more"
display "Ninety-Nine bottles of beer on the wall"
stop run.
100-show-number.
if no-bottles-left
move "No more|" to stringified
else
if counter < 20
string function trim( adigits( counter ) ), "|" into stringified
else
if counter < 100
move spaces to number-name
string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name end-string
move function trim( number-name) to stringified
divide counter by 10 giving n remainder r end-divide
if r not = zero
inspect stringified replacing first space by "-"
end-if
inspect stringified replacing first space by "|"
end-if
end-if
end-if.
if one-bottle-left
string stringified delimited by "|", space, "bottle|" delimited by size into stringified end-string
else
string stringified delimited by "|", space, "bottles|" delimited by size into stringified end-string
end-if.
100-end.
end-program.

View file

@ -1,16 +0,0 @@
program-id. ninety-nine.
data division.
working-storage section.
01 cnt pic 99.
procedure division.
perform varying cnt from 99 by -1 until cnt < 1
display cnt " bottles of beer on the wall"
display cnt " bottles of beer"
display "Take one down, pass it around"
subtract 1 from cnt
display cnt " bottles of beer on the wall"
add 1 to cnt
display space
end-perform.

View file

@ -1,68 +0,0 @@
/***********************************************************************
* Chapel implementation of "99 bottles of beer"
*
* by Brad Chamberlain and Steve Deitz
* 07/13/2006 in Knoxville airport while waiting for flight home from
* HPLS workshop
* compiles and runs with chpl compiler version 1.7.0
* for more information, contact: chapel_info@cray.com
*
*
* Notes:
* o as in all good parallel computations, boundary conditions
* constitute the vast bulk of complexity in this code (invite Brad to
* tell you about his zany boundary condition simplification scheme)
* o uses type inference for variables, arguments
* o relies on integer->string coercions
* o uses named argument passing (for documentation purposes only)
***********************************************************************/
// allow executable command-line specification of number of bottles
// (e.g., ./a.out -snumBottles=999999)
config const numBottles = 99;
const numVerses = numBottles+1;
// a domain to describe the space of lyrics
var LyricsSpace: domain(1) = {1..numVerses};
// array of lyrics
var Lyrics: [LyricsSpace] string;
// parallel computation of lyrics array
[verse in LyricsSpace] Lyrics(verse) = computeLyric(verse);
// as in any good parallel language, I/O to stdout is serialized.
// (Note that I/O to a file could be parallelized using a parallel
// prefix computation on the verse strings' lengths with file seeking)
writeln(Lyrics);
// HELPER FUNCTIONS:
proc computeLyric(verseNum) {
var bottleNum = numBottles - (verseNum - 1);
var nextBottle = (bottleNum + numVerses - 1)%numVerses;
return "\n" // disguise space used to separate elements in array I/O
+ describeBottles(bottleNum, startOfVerse=true) + " on the wall, "
+ describeBottles(bottleNum) + ".\n"
+ computeAction(bottleNum)
+ describeBottles(nextBottle) + " on the wall.\n";
}
proc describeBottles(bottleNum, startOfVerse:bool = false) {
// NOTE: bool should not be necessary here (^^^^); working around bug
var bottleDescription = if (bottleNum) then bottleNum:string
else (if startOfVerse then "N"
else "n")
+ "o more";
return bottleDescription
+ " bottle" + (if (bottleNum == 1) then "" else "s")
+ " of beer";
}
proc computeAction(bottleNum) {
return if (bottleNum == 0) then "Go to the store and buy some more, "
else "Take one down and pass it around, ";
}

View file

@ -1,18 +1,15 @@
func$ bottle num .
if num = 1
return "bottle"
.
return "bottles"
if num = 1 : return "1 bottle"
return num & " bottles"
.
#
i = 99
repeat
print i & " " & bottle i & " of beer on the wall"
print i & " " & bottle i & " of beer"
print bottle i & " of beer on the wall"
print bottle i & " of beer"
print "Take one down, pass it around"
i -= 1
until i = 0
print i & " " & bottle i & " of beer on the wall"
print bottle i & " of beer on the wall"
print ""
.
print "No more bottles of beer on the wall"

View file

@ -27,7 +27,7 @@ extension bottleOp
};
}
public program()
public Program()
{
var bottles := 99;

View file

@ -1,7 +0,0 @@
(let ((i 99))
(while (> i 0)
(message "%d bottles of beer on the wall" i)
(message "%d bottles of beer" i)
(message "Take one down, pass it around")
(message "%d bottles of beer on the wall" (1- i))
(setq i (1- i))))

View file

@ -1,28 +0,0 @@
constant
bottles = "bottles",
bottle = "bottle"
procedure beers (integer how_much)
sequence word1 = bottles, word2 = bottles
switch how_much do
case 2 then
word2 = bottle
case 1 then
word1 = bottle
word2 = bottle
end switch
printf (1,
"%d %s of beer on the wall \n" &
"%d %s of beer \n" &
"Take one down, and pass it around \n" &
"%d %s of beer on the wall \n\n",
{ how_much, word1,
how_much, word1,
how_much-1, word2 }
)
end procedure
for a = 99 to 1 by -1 do
beers (a)
end for

View file

@ -1,17 +0,0 @@
-- An alternate version
include std/console.e
sequence howmany = {"No more bottles","%d bottle","","s"}
for beer = 99 to 1 by -1 do
display(`
[1] bottles of beer on the wall,
[1] bottles of beer.
Take one down, drink it right down,
[2][3] of beer.
`,{beer,
sprintf(howmany[(beer>1)+1],beer-1),
howmany[(beer>2)+3]
})
end for

View file

@ -1,20 +0,0 @@
-- yet another version:
include std/console.e
object stanza = {
"[] bottles of beer on the wall,",
"[] bottles of beer,",
"take one down, and pass it around,"
}
object bottles = 99
loop do
display(stanza[1],bottles)
display(stanza[2],bottles)
display(stanza[3])
bottles -= 1
display(stanza[1]&"\n",{bottles})
until bottles = 0
end loop

View file

@ -1,33 +0,0 @@
class RosettaDemo
{
static public function main()
{
singBottlesOfBeer(100);
}
static function singBottlesOfBeer(bottles : Int)
{
var plural : String = 's';
while (bottles >= 1)
{
Sys.println(bottles + " bottle" + plural + " of beer on the wall,");
Sys.println(bottles + " bottle" + plural + " of beer!");
Sys.println("Take one down, pass it around,");
if (bottles - 1 == 1)
{
plural = '';
}
if (bottles > 1)
{
Sys.println(bottles-1 + " bottle" + plural + " of beer on the wall!\n");
}
else
{
Sys.println("No more bottles of beer on the wall!");
}
bottles--;
}
}
}

View file

@ -1,33 +0,0 @@
class Bottles {
static public function main () : Void {
singBottlesOfBeer(100);
}
macro static public function singBottlesOfBeer (bottles:Int) {
var lines = [];
var s : String = 's';
var song : String = '';
while( bottles >= 1 ){
song += '$bottles bottle$s of beer on the wall,\n';
song += '$bottles bottle$s of beer!\n';
song += 'Take one down, pass it around,\n';
bottles --;
if( bottles > 1 ){
song += '$bottles bottles of beer on the wall!\n\n';
}else if( bottles == 1 ){
s = '';
song += '$bottles bottle of beer on the wall!\n\n';
}else{
song += 'No more bottles of beer on the wall!\n';
}
}
return macro Sys.print($v{song});
}
}

View file

@ -1,19 +0,0 @@
rebol [
Title: "99 Bottles of Beer"
URL: http://rosettacode.org/wiki/99_Bottles_of_Beer
]
; The 'bottles' function maintains correct grammar.
bottles: func [n /local b][
b: either 1 = n ["bottle"]["bottles"]
if 0 = n [n: "no"]
reform [n b]
]
for n 99 1 -1 [print [
bottles n "of beer on the wall" crlf
bottles n "of beer" crlf
"Take one down, pass it around" crlf
bottles n - 1 "of beer on the wall" crlf
]]

View file

@ -1,9 +0,0 @@
for i 99 1 -1 [
x: rejoin [
i b: " bottles of beer" o: " on the wall. " i b
". Take one down, pass it around. " (i - 1) b o "^/"
]
r: :replace j: "bottles" k: "bottle"
switch i [1 [r x j k r at x 10 j k r x "0" "No"] 2 [r at x 40 j k]]
print x
] halt

View file

@ -1 +0,0 @@
for i 99 1 -1[print rejoin[i b:" bottles of beer"o:" on the wall. "i b". Take one down, pass it around. "(i - 1)b o"^/"]]

View file

@ -1,4 +1,4 @@
!YS-v0
!ys-0
defn main(number=99):
each num (number .. 1):

View file

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

View file

@ -1,10 +0,0 @@
-- Standard I/O Streams
with Ada.Integer_Text_Io;
procedure APlusB is
A, B : Integer;
begin
Ada.Integer_Text_Io.Get (Item => A);
Ada.Integer_Text_Io.Get (Item => B);
Ada.Integer_Text_Io.Put (A+B);
end APlusB;

View file

@ -1,12 +0,0 @@
with Ada.Text_IO;
procedure A_Plus_B is
type Small_Integers is range -2_000 .. +2_000;
subtype Input_Values is Small_Integers range -1_000 .. +1_000;
package IO is new Ada.Text_IO.Integer_IO (Num => Small_Integers);
A, B : Input_Values;
begin
IO.Get (A);
IO.Get (B);
IO.Put (A + B, Width => 4, Base => 10);
end A_Plus_B;

View file

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

View file

@ -1,22 +0,0 @@
ConsoleWrite("# A+B:" & @CRLF)
Func Sum($inp)
Local $num = StringSplit($inp, " "), $sum = 0
For $i = 1 To $num[0]
;~ ConsoleWrite("# num["&$i&"]:" & $num[$i] & @CRLF) ;;
$sum = $sum + $num[$i]
Next
Return $sum
EndFunc ;==>Sum
$inp = "17 4"
$res = Sum($inp)
ConsoleWrite($inp & " --> " & $res & @CRLF)
$inp = "999 42 -999"
ConsoleWrite($inp & " --> " & Sum($inp) & @CRLF)
; In calculations, text counts as 0,
; so the program works correctly even with this input:
Local $inp = "999x y 42 -999", $res = Sum($inp)
ConsoleWrite($inp & " --> " & $res & @CRLF)

View file

@ -1,6 +1 @@
::aplusb.cmd
@echo off
setlocal
set /a c=%~1
echo %c%
endlocal
doskey add=setlocal^& set a=$1^& set b=$2^& set /a res=a+b^& endlocal

Some files were not shown because too many files have changed in this diff Show more