Sync
This commit is contained in:
parent
6f050a029e
commit
776bba907c
3887 changed files with 59894 additions and 7280 deletions
|
|
@ -3,29 +3,30 @@
|
|||
|
||||
DATA DIVISION.
|
||||
WORKING-STORAGE SECTION.
|
||||
01 Current PIC 9(3) VALUE ZEROES.
|
||||
01 StepSize PIC 9(3) VALUE ZEROES.
|
||||
01 Current 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.
|
||||
MOVE 1 TO StepSize
|
||||
PERFORM 100 TIMES
|
||||
MOVE StepSize TO Current
|
||||
PERFORM UNTIL Current > 100
|
||||
SUBTRACT Doors(Current) FROM 1 GIVING Doors(Current)
|
||||
ADD StepSize TO Current GIVING Current
|
||||
PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100
|
||||
PERFORM VARYING Current FROM StepSize BY StepSize
|
||||
UNTIL Current > 100
|
||||
SUBTRACT Doors (Current) FROM 1 GIVING Doors (Current)
|
||||
END-PERFORM
|
||||
ADD 1 TO StepSize GIVING StepSize
|
||||
END-PERFORM
|
||||
|
||||
PERFORM VARYING Idx FROM 1 BY 1
|
||||
UNTIL Idx > 100
|
||||
IF Doors(Idx) = 0
|
||||
IF ClosedDoor (Idx)
|
||||
DISPLAY Idx " is closed."
|
||||
ELSE
|
||||
DISPLAY Idx " is open."
|
||||
END-IF
|
||||
END-PERFORM
|
||||
STOP RUN.
|
||||
|
||||
STOP RUN
|
||||
.
|
||||
|
|
|
|||
26
Task/100-doors/Component-Pascal/100-doors.component
Normal file
26
Task/100-doors/Component-Pascal/100-doors.component
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
MODULE Doors100;
|
||||
IMPORT StdLog;
|
||||
|
||||
PROCEDURE Do*;
|
||||
VAR
|
||||
i,j: INTEGER;
|
||||
closed: ARRAY 101 OF BOOLEAN;
|
||||
BEGIN
|
||||
(* initilization of close to true *)
|
||||
FOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END;
|
||||
(* process *)
|
||||
FOR i := 1 TO LEN(closed) DO;
|
||||
j := 1;
|
||||
WHILE j < LEN(closed) DO
|
||||
IF j MOD i = 0 THEN closed[j] := ~closed[j] END;INC(j)
|
||||
END
|
||||
END;
|
||||
(* print results *)
|
||||
i := 1;
|
||||
WHILE i < LEN(closed) DO
|
||||
IF (i - 1) MOD 10 = 0 THEN StdLog.Ln END;
|
||||
IF closed[i] THEN StdLog.String("C ") ELSE StdLog.String("O ") END;
|
||||
INC(i)
|
||||
END;
|
||||
END Do;
|
||||
END Doors100.
|
||||
31
Task/100-doors/D/100-doors-1.d
Normal file
31
Task/100-doors/D/100-doors-1.d
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import std.stdio, std.algorithm, std.range;
|
||||
|
||||
enum DoorState : bool { closed, open }
|
||||
alias Doors = DoorState[];
|
||||
|
||||
Doors flipUnoptimized(Doors doors) pure nothrow {
|
||||
doors[] = DoorState.closed;
|
||||
|
||||
foreach (immutable i; 0 .. doors.length)
|
||||
for (int j = i; j < doors.length; j += i + 1)
|
||||
if (doors[j] == DoorState.open)
|
||||
doors[j] = DoorState.closed;
|
||||
else
|
||||
doors[j] = DoorState.open;
|
||||
return doors;
|
||||
}
|
||||
|
||||
Doors flipOptimized(Doors doors) pure nothrow {
|
||||
doors[] = DoorState.closed;
|
||||
for (int i = 1; i ^^ 2 <= doors.length; i++)
|
||||
doors[i ^^ 2 - 1] = DoorState.open;
|
||||
return doors;
|
||||
}
|
||||
|
||||
void main() {
|
||||
auto doors = new Doors(100);
|
||||
|
||||
foreach (const open; [doors.dup.flipUnoptimized,
|
||||
doors.dup.flipOptimized])
|
||||
iota(1, open.length + 1).filter!(i => open[i - 1]).writeln;
|
||||
}
|
||||
23
Task/100-doors/D/100-doors-2.d
Normal file
23
Task/100-doors/D/100-doors-2.d
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import std.stdio;
|
||||
|
||||
void printAllDoors(bool[] doors)
|
||||
{
|
||||
// Prints the state of all the doors
|
||||
foreach(i, door; doors)
|
||||
{
|
||||
writeln("#: ", i + 1, (door) ? " open" : " closed");
|
||||
}
|
||||
}
|
||||
void main()
|
||||
{
|
||||
bool[100] doors = false; //Create 100 closed doors
|
||||
for(int a = 0; a < 100; ++a) {
|
||||
writefln("Pass #%s; visiting every %s door.", a + 1, a + 1); // Optional
|
||||
for(int i = a; i < 100; i += (a + 1)) {
|
||||
writefln("Visited door %s", i + 1); //Optional
|
||||
doors[i] = !doors[i];
|
||||
}
|
||||
writeln(); // Optional
|
||||
}
|
||||
printAllDoors(doors); // Prints the state of each door
|
||||
}
|
||||
16
Task/100-doors/DCL/100-doors.dcl
Normal file
16
Task/100-doors/DCL/100-doors.dcl
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
$! doors.com
|
||||
$! Excecute by running @doors at prompt.
|
||||
$ square = 1
|
||||
$ incr = 3
|
||||
$ count2 = 0
|
||||
$ d = 1
|
||||
$ LOOP2:
|
||||
$ count2 = count2 + 1
|
||||
$ IF (d .NE. square)
|
||||
$ THEN WRITE SYS$OUTPUT "door ''d' is closed"
|
||||
$ ELSE WRITE SYS$OUTPUT "door ''d' is open"
|
||||
$ square = incr + square
|
||||
$ incr = incr + 2
|
||||
$ ENDIF
|
||||
$ d = d + 1
|
||||
$ IF (count2 .LT. 100) THEN GOTO LOOP2
|
||||
26
Task/100-doors/Elixir/100-doors.elixir
Normal file
26
Task/100-doors/Elixir/100-doors.elixir
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
defmodule HundredDoors do
|
||||
|
||||
def doors() do
|
||||
Enum.to_list(Stream.take(Stream.cycle([false]), 100))
|
||||
end
|
||||
|
||||
def toggle(doors, n) do
|
||||
Enum.take(doors, n) ++ [not Enum.at(doors,n)] ++ Enum.drop(doors,n+1)
|
||||
end
|
||||
|
||||
def toggle_every(doors, n) do
|
||||
Enum.reduce( Enum.take_every((n-1)..99, n), doors, fn(n, acc) -> toggle(acc, n) end )
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
# unoptimized
|
||||
final_state = Enum.reduce(1..100, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle_every(acc, n) end)
|
||||
|
||||
# optimized
|
||||
final_state = Enum.reduce(1..10, HundredDoors.doors, fn(n, acc) -> HundredDoors.toggle(acc, n*n-1) end)
|
||||
|
||||
open_doors = Enum.map(Enum.filter( Enum.with_index(final_state), fn({door,_}) -> door end ),
|
||||
fn({_,index}) -> index+1 end)
|
||||
|
||||
IO.puts "All doors are closed except these: #{inspect open_doors}"
|
||||
16
Task/100-doors/Erlang/100-doors-1.erl
Normal file
16
Task/100-doors/Erlang/100-doors-1.erl
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
-module(hundoors).
|
||||
|
||||
-export([go/0]).
|
||||
|
||||
toggle(closed) -> open;
|
||||
toggle(open) -> closed.
|
||||
|
||||
go() -> go([closed || _ <- lists:seq(1, 100)],[], 1, 1).
|
||||
go([], L, N, _I) when N =:= 101 -> lists:reverse(L);
|
||||
go([], L, N, _I) -> go(lists:reverse(L), [], N + 1, 1);
|
||||
go([H|T], L, N, I) ->
|
||||
H2 = case I rem N of
|
||||
0 -> toggle(H);
|
||||
_ -> H
|
||||
end,
|
||||
go(T, [H2|L], N, I + 1).
|
||||
5
Task/100-doors/Erlang/100-doors-2.erl
Normal file
5
Task/100-doors/Erlang/100-doors-2.erl
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
doors() ->
|
||||
F = fun(X) -> Root = math:pow(X,0.5), Root == trunc(Root) end,
|
||||
Out = fun(X, true) -> io:format("Door ~p: open~n",[X]);
|
||||
(X, false)-> io:format("Door ~p: close~n",[X]) end,
|
||||
[Out(X,F(X)) || X <- lists:seq(1,100)].
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
var doors = [], n = 100, i, j;
|
||||
(function(){var doors = [], n = 100, i, j;
|
||||
|
||||
for (i = 1; i <= n; i++) {
|
||||
for (j = i; j <= n; j += i) {
|
||||
|
|
@ -8,4 +8,4 @@ for (i = 1; i <= n; i++) {
|
|||
|
||||
for (i = 1 ; i <= n ; i++) {
|
||||
if (doors[i]) console.log("Door " + i + " is open");
|
||||
}
|
||||
}}())
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
f[n_] = "Closed";
|
||||
Do[Do[If[f[n] == "Closed", f[n] = "Open", f[n] = "Closed"], {n, k, 100, k}], {k, 1, 100}];
|
||||
Table[f[n], {n, 1, 100}]
|
||||
n=100;
|
||||
tmp=ConstantArray[-1,n];
|
||||
Do[tmp[[i;;;;i]]*=-1;,{i,n}];
|
||||
Do[Print["door ",i," is ",If[tmp[[i]]==-1,"closed","open"]],{i,1,Length[tmp]}]
|
||||
|
|
|
|||
|
|
@ -1 +1,3 @@
|
|||
Do[Print["door ",i," is ",If[IntegerQ[Sqrt[i]],"open","closed"]],{i,100}]
|
||||
f[n_] = "Closed";
|
||||
Do[Do[If[f[n] == "Closed", f[n] = "Open", f[n] = "Closed"], {n, k, 100, k}], {k, 1, 100}];
|
||||
Table[f[n], {n, 1, 100}]
|
||||
|
|
|
|||
|
|
@ -1,3 +1 @@
|
|||
n=100;
|
||||
a=Range[1,Sqrt[n]]^2
|
||||
Do[Print["door ",i," is ",If[MemberQ[a,i],"open","closed"]],{i,100}]
|
||||
Do[Print["door ",i," is ",If[IntegerQ[Sqrt[i]],"open","closed"]],{i,100}]
|
||||
|
|
|
|||
|
|
@ -1,12 +1,3 @@
|
|||
n=100
|
||||
nn=1
|
||||
a=0
|
||||
For[i=1,i<=n,i++,
|
||||
If[i==nn,
|
||||
Print["door ",i," is open"];
|
||||
a++;
|
||||
nn+=2a+1;
|
||||
,
|
||||
Print["door ",i," is closed"];
|
||||
];
|
||||
]
|
||||
n=100;
|
||||
a=Range[1,Sqrt[n]]^2
|
||||
Do[Print["door ",i," is ",If[MemberQ[a,i],"open","closed"]],{i,100}]
|
||||
|
|
|
|||
|
|
@ -1 +1,12 @@
|
|||
Pick[Range[100], Xor@@@Array[Divisible[#1,#2]&, {100,100}]]
|
||||
n=100
|
||||
nn=1
|
||||
a=0
|
||||
For[i=1,i<=n,i++,
|
||||
If[i==nn,
|
||||
Print["door ",i," is open"];
|
||||
a++;
|
||||
nn+=2a+1;
|
||||
,
|
||||
Print["door ",i," is closed"];
|
||||
];
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
Range[Sqrt[100]]^2
|
||||
Pick[Range[100], Xor@@@Array[Divisible[#1,#2]&, {100,100}]]
|
||||
|
|
|
|||
1
Task/100-doors/Mathematica/100-doors-7.math
Normal file
1
Task/100-doors/Mathematica/100-doors-7.math
Normal file
|
|
@ -0,0 +1 @@
|
|||
Range[Sqrt[100]]^2
|
||||
|
|
@ -1,2 +1,37 @@
|
|||
$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" } }
|
||||
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}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,2 @@
|
|||
$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" } }
|
||||
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" } }
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
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"
|
||||
$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" } }
|
||||
|
|
|
|||
3
Task/100-doors/PowerShell/100-doors-5.psh
Normal file
3
Task/100-doors/PowerShell/100-doors-5.psh
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
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"
|
||||
|
|
@ -1,31 +1,40 @@
|
|||
class Door
|
||||
attr_reader :state
|
||||
|
||||
def initialize
|
||||
@state=:closed
|
||||
@state = :closed
|
||||
end
|
||||
|
||||
def close; @state=:closed; end
|
||||
def open; @state=:open; end
|
||||
def close
|
||||
@state = :closed
|
||||
end
|
||||
|
||||
def closed?; @state==:closed; end
|
||||
def open?; @state==:open; end
|
||||
def open
|
||||
@state = :open
|
||||
end
|
||||
|
||||
def closed?
|
||||
@state == :closed
|
||||
end
|
||||
|
||||
def open?
|
||||
@state == :open
|
||||
end
|
||||
|
||||
def toggle
|
||||
if closed?
|
||||
open
|
||||
else
|
||||
close
|
||||
end
|
||||
if closed? then open else close end
|
||||
end
|
||||
|
||||
def to_s; @state.to_s; end
|
||||
def to_s
|
||||
@state.to_s
|
||||
end
|
||||
end
|
||||
|
||||
doors=Array.new(100){Door.new}
|
||||
doors = Array.new(100) { Door.new }
|
||||
1.upto(100) do |multiplier|
|
||||
doors.each_with_index do |door, i|
|
||||
door.toggle if (i+1)%multiplier==0
|
||||
door.toggle if (i + 1) % multiplier == 0
|
||||
end
|
||||
end
|
||||
|
||||
doors.each_with_index{|door, i| puts "Door #{i+1} is #{door}."}
|
||||
doors.each_with_index { |door, i| puts "Door #{i+1} is #{door}." }
|
||||
|
|
|
|||
|
|
@ -7,12 +7,12 @@ end
|
|||
def Closed.toggle
|
||||
Open
|
||||
end
|
||||
doors = [Closed] * (n+1)
|
||||
doors = [Closed] * (n + 1)
|
||||
for mul in 1..n
|
||||
for x in 1..n/mul
|
||||
doors[mul*x] = doors[mul*x].toggle
|
||||
for x in 1..n / mul
|
||||
doors[mul * x] = doors[mul * x].toggle
|
||||
end
|
||||
end
|
||||
doors.each_with_index { |b, i|
|
||||
puts "Door #{i} is #{b}" if i>0
|
||||
puts "Door #{i} is #{b}" if i > 0
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
doors = [false] * 100
|
||||
100.times do |i|
|
||||
(i ... doors.length).step(i+1) do |j|
|
||||
(i ... doors.length).step(i + 1) do |j|
|
||||
doors[j] = !doors[j]
|
||||
end
|
||||
end
|
||||
puts doors.map.with_index{|d,i| "Door #{i+1} is #{d ? 'open' : 'closed'}."}
|
||||
puts doors.map.with_index{|d, i| "Door #{i+1} is #{d ? 'open' : 'closed'}."}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,17 @@
|
|||
// rust 0.8
|
||||
|
||||
fn main() {
|
||||
let mut door_open = [false, ..100];
|
||||
|
||||
for uint::range(1, 101) |pass| {
|
||||
for uint::range(1, 101) |door| {
|
||||
for pass in std::iter::range_inclusive(1, 100) {
|
||||
for door in std::iter::range_inclusive(1, 100) {
|
||||
if door % pass == 0 {
|
||||
door_open[door - 1] = !door_open[door - 1]
|
||||
door_open[door - 1] = !door_open[door - 1];
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
for door_open.eachi |i, state| {
|
||||
io::println(fmt!("Door %u is %s.", i + 1,
|
||||
if *state { "open" } else { "closed" }));
|
||||
for (i, state) in door_open.iter().enumerate() {
|
||||
println!("Door {} is {}.", i + 1,
|
||||
if *state {"open"} else {"closed"});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
// rust 0.8
|
||||
|
||||
fn main() {
|
||||
for int::range(1,101) |i| {
|
||||
let x = float::pow(i as f64, 0.5);
|
||||
let state = if x == float::round(x) {"open"} else {"closed"};
|
||||
io::println(fmt!("Door %i is %s", i, state));
|
||||
for i in std::iter::range_inclusive(1,100) {
|
||||
let x = (i as f64).pow(&0.5);
|
||||
let state = if x == x.round() {"open"} else {"closed"};
|
||||
println!("Door {} is {}", i, state);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,47 +1,47 @@
|
|||
(100doors)
|
||||
comment
|
||||
comment: returns the first 100 doors after making 100 passes
|
||||
(always)
|
||||
(pr) (first) 100 (passes) 1 (doors)
|
||||
|
||||
(doors)
|
||||
comment
|
||||
comment: start with an infinite list of closed doors
|
||||
(always)
|
||||
(c) "'closed" (doors)
|
||||
|
||||
(passes) count doors
|
||||
comment
|
||||
comment: count is greater than 100 -> make 100 passes
|
||||
(>) count 100
|
||||
doors
|
||||
|
||||
(passes) count doors
|
||||
comment
|
||||
comment: count is not greater than 100 -> make 100 passes
|
||||
(always)
|
||||
(passes) (add1) count
|
||||
(pass) count doors
|
||||
|
||||
(pass) n doors
|
||||
comment
|
||||
(pass) count doors
|
||||
comment: takes a count and a list of doors -> makes a pass over the doors
|
||||
(always)
|
||||
(pass1) n n doors
|
||||
(ZEDpass) count count doors
|
||||
|
||||
(pass1) n m doors
|
||||
comment
|
||||
(=) m 1
|
||||
(ZEDpass) count1 count2 doors
|
||||
comment: count2 is one -> completes a pass over the doors
|
||||
(=) count2 1
|
||||
(c) (toggle) (1) doors
|
||||
(pass) n (!) doors
|
||||
(pass) count1 (!) doors
|
||||
|
||||
(pass1) n m doors
|
||||
comment
|
||||
(>) m 1
|
||||
(ZEDpass) count1 count2 doors
|
||||
comment: count2 is greater than one -> completes a pass over the doors
|
||||
(>) count2 1
|
||||
(c) (1) doors
|
||||
(pass1) n (sub1) m (!) doors
|
||||
(ZEDpass) count1 (sub1) count2 (!) doors
|
||||
|
||||
(toggle) door
|
||||
comment
|
||||
comment: door is closed -> toggles it
|
||||
(=) door "'closed"
|
||||
"'open"
|
||||
|
||||
(toggle) door
|
||||
comment
|
||||
comment: door is open -> toggles it
|
||||
(=) door "'open"
|
||||
"'closed"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
require 'rational'
|
||||
|
||||
class TwentyFourGamePlayer
|
||||
EXPRESSIONS = [
|
||||
'((%d %s %d) %s %d) %s %d',
|
||||
|
|
@ -7,35 +5,28 @@ class TwentyFourGamePlayer
|
|||
'(%d %s %d) %s (%d %s %d)',
|
||||
'%d %s ((%d %s %d) %s %d)',
|
||||
'%d %s (%d %s (%d %s %d))',
|
||||
]
|
||||
OPERATORS = [:+, :-, :*, :/]
|
||||
].map{|expr| [expr, expr.gsub('%d', 'Rational(%d,1)')]}
|
||||
|
||||
@@objective = Rational(24,1)
|
||||
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3)
|
||||
|
||||
def initialize(digits)
|
||||
@digits = digits
|
||||
@solutions = []
|
||||
solve
|
||||
end
|
||||
OBJECTIVE = Rational(24,1)
|
||||
|
||||
attr_reader :digits, :solutions
|
||||
|
||||
def solve
|
||||
def self.solve(digits)
|
||||
solutions = []
|
||||
digits.permutation.to_a.uniq.each do |a,b,c,d|
|
||||
OPERATORS.each do |op1|
|
||||
OPERATORS.each do |op2|
|
||||
OPERATORS.each do |op3|
|
||||
EXPRESSIONS.each do |expr|
|
||||
# evaluate using rational arithmetic
|
||||
test = expr.gsub('%d', 'Rational(%d,1)') % [a, op1, b, op2, c, op3, d]
|
||||
value = eval(test) rescue -1 # catch division by zero
|
||||
if value == @@objective
|
||||
@solutions << expr % [a, op1, b, op2, c, op3, d]
|
||||
OPERATORS.each do |op1,op2,op3|
|
||||
EXPRESSIONS.each do |expr,expr_rat|
|
||||
# evaluate using rational arithmetic
|
||||
test = expr_rat % [a, op1, b, op2, c, op3, d]
|
||||
value = eval(test) rescue -1 # catch division by zero
|
||||
if value == OBJECTIVE
|
||||
solutions << expr % [a, op1, b, op2, c, op3, d]
|
||||
end
|
||||
end
|
||||
end;end;end;end
|
||||
end
|
||||
end
|
||||
solutions
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
# validate user input
|
||||
|
|
@ -48,10 +39,10 @@ digits = ARGV.map do |arg|
|
|||
end
|
||||
digits.size == 4 or raise "error: need 4 digits, only have #{digits.size}"
|
||||
|
||||
player = TwentyFourGamePlayer.new(digits)
|
||||
if player.solutions.empty?
|
||||
solutions = TwentyFourGamePlayer.solve(digits)
|
||||
if solutions.empty?
|
||||
puts "no solutions"
|
||||
else
|
||||
puts "found #{player.solutions.size} solutions, including #{player.solutions.first}"
|
||||
puts player.solutions.sort.join("\n")
|
||||
puts "found #{solutions.size} solutions, including #{solutions.first}"
|
||||
puts solutions.sort
|
||||
end
|
||||
|
|
|
|||
|
|
@ -23,7 +23,14 @@ function twentyfour()
|
|||
print("The 24 Game\nYou will be given any four digits in the range 1 to 9, which may have repetitions.\n
|
||||
Using just the +, -, *, and / operators show how to make an answer of 24.\n
|
||||
Use parentheses, (), to ensure proper order of evaulation.\n
|
||||
Enter 'n' for a new set of digits, and 'q' to quit. Good luck!\n
|
||||
Enter 'n' fDouble>()
|
||||
|
||||
while( scanner.hasNext() ) {
|
||||
if( scanner.hasNextInt() ) {
|
||||
var n = scanner.nextInt()
|
||||
|
||||
// Make sure they're allowed to use n
|
||||
if( n or a new set of digits, and 'q' to quit. Good luck!\n
|
||||
Here's your first 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n
|
||||
>")
|
||||
while true
|
||||
|
|
|
|||
|
|
@ -7,17 +7,17 @@ Function isNumeric ($x)
|
|||
Return $isNum
|
||||
}
|
||||
|
||||
$NumberOne = Random -Maximum 10 -Minimum 1
|
||||
$NumberTwo = Random -Maximum 10 -Minimum 1
|
||||
$NumberThree = Random -Maximum 10 -Minimum 1
|
||||
$NumberFour = Random -Maximum 10 -Minimum 1
|
||||
$NumberArray = @()
|
||||
$NumberArray += $NumberOne
|
||||
$NumberArray += $NumberTwo
|
||||
$NumberArray += $NumberThree
|
||||
$NumberArray += $NumberFour
|
||||
While( $NumberArray.Count -lt 4 ){
|
||||
$NumberArray += Random -Minimum 1 -Maximum 10
|
||||
}
|
||||
|
||||
Write-Host "Welcome to the 24 game!`n`nHere are your numbers: $NumberOne,$NumberTwo,$NumberThree and $NumberFour.`nUse division, multiplication, subtraction and addition to get 24 as a result with these 4 numbers.`n"
|
||||
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
|
||||
{
|
||||
|
|
@ -26,50 +26,14 @@ $EndResult = $null
|
|||
$TempChar = $null
|
||||
$TempChar2 = $null
|
||||
$Count = $null
|
||||
|
||||
$AllowableCharacters = $NumberArray + "+-*/()".ToCharArray()
|
||||
$Result = Read-Host
|
||||
Foreach($Char in $Result.ToCharArray())
|
||||
{
|
||||
Switch($Char)
|
||||
{
|
||||
$NumberOne
|
||||
{
|
||||
}
|
||||
$NumberTwo
|
||||
{
|
||||
}
|
||||
$NumberThree
|
||||
{
|
||||
}
|
||||
$NumberFour
|
||||
{
|
||||
}
|
||||
"+"
|
||||
{
|
||||
}
|
||||
"-"
|
||||
{
|
||||
}
|
||||
"*"
|
||||
{
|
||||
}
|
||||
"/"
|
||||
{
|
||||
}
|
||||
"("
|
||||
{
|
||||
}
|
||||
")"
|
||||
{
|
||||
}
|
||||
" "
|
||||
{
|
||||
}
|
||||
Default
|
||||
{
|
||||
$Wrong = 1
|
||||
}
|
||||
}
|
||||
If( $AllowableCharacters -notcontains $Char ){ $Wrong = 1 }
|
||||
}
|
||||
|
||||
If($Wrong -eq 1)
|
||||
{
|
||||
Write-Warning "Wrong input! Please use only the given numbers."
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
require "rational"
|
||||
|
||||
def play
|
||||
digits = Array.new(4) {1+rand(9)}
|
||||
digits = Array.new(4){rand(1..9)}
|
||||
loop do
|
||||
guess = get_guess(digits)
|
||||
result = evaluate(guess)
|
||||
|
|
@ -17,13 +17,13 @@ end
|
|||
|
||||
def get_guess(digits)
|
||||
loop do
|
||||
print "\nEnter your guess using #{digits.inspect}: "
|
||||
guess = $stdin.gets.chomp
|
||||
print "\nEnter your guess using #{digits}: "
|
||||
guess = gets.chomp
|
||||
|
||||
# ensure input is safe to eval
|
||||
invalid_chars = guess.scan(%r{[^\d\s()+*/-]})
|
||||
unless invalid_chars.empty?
|
||||
puts "invalid characters in input: #{invalid_chars.inspect}"
|
||||
puts "invalid characters in input: #{invalid_chars}"
|
||||
next
|
||||
end
|
||||
|
||||
|
|
|
|||
|
|
@ -18,10 +18,10 @@
|
|||
; APPLE II, +, E, C: $FDED, $80 ;
|
||||
; COMMODORE 64: $FFD2, $00 ;
|
||||
;-------------------------------------;
|
||||
ECHO = $FFEF EMIT A REG AS ASCII
|
||||
ORMASK = $80 ($00 FOR + ASCII)
|
||||
ECHO = $FFEF ;EMIT A REG AS ASCII
|
||||
ORMASK = $80 ;($00 FOR + ASCII)
|
||||
;
|
||||
MAXBEER = 99 INITIAL BEER COUNT
|
||||
MAXBEER = 99 ;INITIAL BEER COUNT
|
||||
;-------------------------------------;
|
||||
; X REG. IS THE BOTTLE COUNTER. ;
|
||||
; Y REG. IS THE STRING INDEX POINTER, ;
|
||||
|
|
@ -34,19 +34,19 @@ MAXBEER = 99 INITIAL BEER COUNT
|
|||
; EMIT COMPLETE CORRECT SONG ADJUSTED ;
|
||||
; FOR UPPER-CASE 40-COLUMN DISPLAY. ;
|
||||
;-------------------------------------;
|
||||
LDX #MAXBEER X=MAXBEER
|
||||
BNE PRSONG SING THE SONG & RTS
|
||||
LDX #MAXBEER ;X=MAXBEER
|
||||
BNE PRSONG ;SING THE SONG & RTS
|
||||
;-------------------------------------;
|
||||
; EMIT WHOLE SONG UP TO LAST SENTENCE.;
|
||||
;-------------------------------------;
|
||||
BEERME:
|
||||
LDY #TAKE1-TXT ? "TAKE ... AROUND,"
|
||||
JSR PRBOB ? X;" BOT ... WALL."
|
||||
PRSONG: ; ?
|
||||
LDY #CR-TXT ? X;" BOT ... WALL,"
|
||||
JSR PRBOB ? X;" BOT ... BEER."
|
||||
DEX X=X-1
|
||||
BPL BEERME IF X>=0 THEN BEERME
|
||||
LDY #TAKE1-TXT ;? "TAKE ... AROUND,"
|
||||
JSR PRBOB ;? X;" BOT ... WALL."
|
||||
PRSONG: ; ;?
|
||||
LDY #CR-TXT ;? X;" BOT ... WALL,"
|
||||
JSR PRBOB ;? X;" BOT ... BEER."
|
||||
DEX ;X=X-1
|
||||
BPL BEERME ;IF X>=0 THEN BEERME
|
||||
;-------------------------------------;
|
||||
; EMIT LAST SENTENCE AND FALL THROUGH.;
|
||||
;-------------------------------------;
|
||||
|
|
@ -58,58 +58,58 @@ PRSONG: ; ?
|
|||
;-------------------------------------;
|
||||
PRBOB:
|
||||
TYA
|
||||
PHA SAVE THE PRE$ PTR
|
||||
JSR PUTS ? PRE$;
|
||||
TXA IF X=0 THEN
|
||||
BEQ PRBOTT ? "NO MORE";
|
||||
LDY #"0"-1 ELSE
|
||||
SEC (
|
||||
PHA ;SAVE THE PRE$ PTR
|
||||
JSR PUTS ;? PRE$;
|
||||
TXA ;IF X=0 THEN
|
||||
BEQ PRBOTT ; ? "NO MORE";
|
||||
LDY #"0"-1 ;ELSE
|
||||
SEC ;(
|
||||
DIV10:
|
||||
SBC #10 Y=INT(X/10)
|
||||
SBC #10 ; Y=INT(X/10)
|
||||
INY
|
||||
BCS DIV10
|
||||
ADC #10+'0'
|
||||
CPY #"0"
|
||||
BEQ ONEDIG
|
||||
PHA IF Y>0 THEN
|
||||
PHA ; IF Y>0 THEN
|
||||
TYA ? Y;
|
||||
JSR PUTCH
|
||||
PLA ? X MOD 10;
|
||||
PLA ; ? X MOD 10;
|
||||
ONEDIG:
|
||||
LDY #BOTTL-TXT )
|
||||
LDY #BOTTL-TXT ;)
|
||||
PRBOTT:
|
||||
JSR PUTCH ? " BOTTLE";
|
||||
JSR PUTCH ;? " BOTTLE";
|
||||
CPX #1
|
||||
BNE PLURAL
|
||||
INY IF X<>1 THEN ? "S";
|
||||
INY ;IF X<>1 THEN ? "S";
|
||||
PLURAL:
|
||||
JSR PUTS ? " OF BEER";
|
||||
PLA RECALL THE PRE$ PTR
|
||||
JSR PUTS ;? " OF BEER";
|
||||
PLA ;RECALL THE PRE$ PTR
|
||||
CMP #COMCR-TXT
|
||||
BEQ PRDOT
|
||||
PHA IF APPROPRIATE THEN
|
||||
JSR PUTS ? " ON THE WALL";
|
||||
PHA ;IF APPROPRIATE THEN
|
||||
JSR PUTS ; ? " ON THE WALL";
|
||||
PLA
|
||||
LDY #COMCR-TXT IF APPROPRIATE THEN
|
||||
CMP #CR-TXT ? ",":
|
||||
BEQ PRBOB ? X;" ... BEER";
|
||||
LDY #COMCR-TXT ;IF APPROPRIATE THEN
|
||||
CMP #CR-TXT ; ? ",":
|
||||
BEQ PRBOB ; ? X;" ... BEER";
|
||||
PRDOT:
|
||||
LDY #DOTCR-TXT ? "."
|
||||
LDY #DOTCR-TXT ;? "."
|
||||
;-------------------------------------;
|
||||
; EMIT A HI-BIT-SET TERMINATED STRING ;
|
||||
; @ OFFSET Y AND EXIT WITH Y @ THE ;
|
||||
; BEGINNING OF THE NEXT STRING. ;
|
||||
;-------------------------------------;
|
||||
PUTS:
|
||||
LDA TXT,Y GRAB A STRING CHAR
|
||||
INY ADVANCE STRING PTR
|
||||
LDA TXT,Y ;GRAB A STRING CHAR
|
||||
INY ;ADVANCE STRING PTR
|
||||
PUTCH:
|
||||
PHA
|
||||
ORA #ORMASK
|
||||
AND #ORMASK+127 FORMAT CHAR FOR ECHO
|
||||
JSR ECHO SHOOT IT TO CONSOLE
|
||||
AND #ORMASK+127 ;FORMAT CHAR FOR ECHO
|
||||
JSR ECHO ;SHOOT IT TO CONSOLE
|
||||
PLA
|
||||
BPL PUTS LOOP IF APPROPRIATE
|
||||
BPL PUTS ;LOOP IF APPROPRIATE
|
||||
RTS
|
||||
;-------------------------------------;
|
||||
; OPTIMIZED SONG LYRIC STRINGS. ;
|
||||
|
|
|
|||
|
|
@ -37,90 +37,90 @@
|
|||
; reg a handles everything else (with a little help ;
|
||||
; from the system stack) ;
|
||||
;-----------------------------------------------------;
|
||||
outeee = $e1d1 ROM: console putchar routine
|
||||
stbeer = 99 Must be in the range [0..99]
|
||||
outeee = $e1d1 ;ROM: console putchar routine
|
||||
stbeer = 99 ;Must be in the range [0..99]
|
||||
.or $0f00
|
||||
;=====================================================;
|
||||
; Initialize, sing the song, and exit ;
|
||||
;-----------------------------------------------------;
|
||||
main ldab #stbeer Beer count = stbeer
|
||||
bsr prsong Sing the entire song
|
||||
swi Return to the monitor.
|
||||
main ldab #stbeer ;Beer count = stbeer
|
||||
bsr prsong ;Sing the entire song
|
||||
swi ;Return to the monitor.
|
||||
;=====================================================;
|
||||
; Emit the entire song up to the last sentence ;
|
||||
;-----------------------------------------------------;
|
||||
beerme bsr prbob2 Emit second sentence of verse
|
||||
prsong ldx #nline Blank line between verses
|
||||
ldaa #'N' First sentence type = 'N'
|
||||
bsr prbob Emit 1st sentence of verse
|
||||
decb Beer count -= 1
|
||||
bpl beerme If beer count >= 0 then beerme
|
||||
beerme bsr prbob2 ;Emit second sentence of verse
|
||||
prsong ldx #nline ;Blank line between verses
|
||||
ldaa #'N' ;First sentence type = 'N'
|
||||
bsr prbob ;Emit 1st sentence of verse
|
||||
decb ;Beer count -= 1
|
||||
bpl beerme ;If beer count >= 0 then beerme
|
||||
;=====================================================;
|
||||
; Set up the last sentence and fall through to prbob2 ;
|
||||
;-----------------------------------------------------;
|
||||
ldab #stbeer Beer count = stbeer
|
||||
ldx #store x$ = "Go to the store ..."
|
||||
ldab #stbeer ;Beer count = stbeer
|
||||
ldx #store ;x$ = "Go to the store ..."
|
||||
;=====================================================;
|
||||
; Emit a properly punctuated bottle-of-beer sentence, ;
|
||||
; using beer counter in reg b, pre-string pointer ;
|
||||
; in reg x, and the sentence type in reg a ('N' = ;
|
||||
; sentence 1, 'o' = sentence 1.5, 'n' = sentence 2) ;
|
||||
;-----------------------------------------------------;
|
||||
prbob2 ldaa #'n' Second sentence type = 'n'
|
||||
prbob psha Stack sentence type for later
|
||||
bsr puts Emit pre-string
|
||||
pula Check sentence type and use
|
||||
psha it to prepare the upper- or
|
||||
anda #'n' lower-case of "no more"
|
||||
ldx #omore x$ = "o more bottle"
|
||||
tstb If beer count = 0 then
|
||||
beq prbott skip over the i-to-a
|
||||
ldx #bottl x$ = " bottle"
|
||||
prbob2 ldaa #'n' ;Second sentence type = 'n'
|
||||
prbob psha ;Stack sentence type for later
|
||||
bsr puts ;Emit pre-string
|
||||
pula ;Check sentence type and use
|
||||
psha ; it to prepare the upper- or
|
||||
anda #'n' ; lower-case of "no more"
|
||||
ldx #omore ;x$ = "o more bottle"
|
||||
tstb ;If beer count = 0 then
|
||||
beq prbott ; skip over the i-to-a
|
||||
ldx #bottl ;x$ = " bottle"
|
||||
;=====================================================;
|
||||
; I-to-A (inline): convert int in b to ascii and emit ;
|
||||
; with leading zero suppression (0 <= # <= 99)! ;
|
||||
;-----------------------------------------------------;
|
||||
pshb Stack beer count
|
||||
ldaa #-1 (divten trashes it)
|
||||
divten subb #10 b = ones digit - 10
|
||||
inca a = tens digit
|
||||
bcc divten If a = 0 then
|
||||
beq onedig suppress leading zero
|
||||
adda #"0" else translate tens digit to
|
||||
bsr putch shifted ascii and emit
|
||||
onedig addb #'0'+10 Translate ones digit to ascii
|
||||
tba and leave it in a for putch
|
||||
pulb Restore beer count
|
||||
pshb ;Stack beer count
|
||||
ldaa #-1 ; (divten trashes it)
|
||||
divten subb #10 ;b = ones digit - 10
|
||||
inca ;a = tens digit
|
||||
bcc divten ;If a = 0 then
|
||||
beq onedig ; suppress leading zero
|
||||
adda #"0" ;else translate tens digit to
|
||||
bsr putch ; shifted ascii and emit
|
||||
onedig addb #'0'+10 ;Translate ones digit to ascii
|
||||
tba ; and leave it in a for putch
|
||||
pulb ;Restore beer count
|
||||
;-----------------------------------------------------;
|
||||
prbott bsr putch Emit a;x$;
|
||||
cmpb #1 If beer count = 1
|
||||
bne plural then
|
||||
inx skip over the "s"
|
||||
plural bsr puts Emit " ... beer";
|
||||
pula Restore sentence type
|
||||
cmpa #'o' If type <> 'o'
|
||||
beq putdot then
|
||||
psha emit " on the wall";
|
||||
bsr puts if type = 'N' then loop
|
||||
pula back to finish the
|
||||
adda #33 first sentence with
|
||||
bpl prbob type = 'o', x$ = ", "
|
||||
putdot ldx #dotnl x$ = ".\n"
|
||||
prbott bsr putch ;Emit a;x$;
|
||||
cmpb #1 ;If beer count = 1
|
||||
bne plural ;then
|
||||
inx ; skip over the "s"
|
||||
plural bsr puts ;Emit " ... beer";
|
||||
pula ;Restore sentence type
|
||||
cmpa #'o' ;If type <> 'o'
|
||||
beq putdot ;then
|
||||
psha ; emit " on the wall";
|
||||
bsr puts ; if type = 'N' then loop
|
||||
pula ; back to finish the
|
||||
adda #33 ; first sentence with
|
||||
bpl prbob ; type = 'o', x$ = ", "
|
||||
putdot ldx #dotnl ;x$ = ".\n"
|
||||
;=====================================================;
|
||||
; Emit string @ x and leave x @ start of next string ;
|
||||
;-----------------------------------------------------;
|
||||
puts ldaa 0,x a = raw character removed
|
||||
inx from the beginning of x$
|
||||
puts ldaa 0,x ;a = raw character removed
|
||||
inx ; from the beginning of x$
|
||||
;=====================================================;
|
||||
; Emit a as ascii and loop into x$ if hi-bit is clear ;
|
||||
;-----------------------------------------------------;
|
||||
putch psha Stack raw char
|
||||
anda #$7f Mask off the hi-bit
|
||||
jsr outeee Emit a as 7-bit ascii
|
||||
pula Restore raw char
|
||||
tsta If hi-bit is clear then
|
||||
bpl puts loop back into x$
|
||||
rts All 8 'bsr's use this 'rts'!
|
||||
putch psha ;Stack raw char
|
||||
anda #$7f ;Mask off the hi-bit
|
||||
jsr outeee ;Emit a as 7-bit ascii
|
||||
pula ;Restore raw char
|
||||
tsta ;If hi-bit is clear then
|
||||
bpl puts ; loop back into x$
|
||||
rts ;All 8 'bsr's use this 'rts'!
|
||||
;=====================================================;
|
||||
; Optimized song lyric strings, carefully arranged to ;
|
||||
; allow the prbob subroutine to take full advantage ;
|
||||
|
|
|
|||
21
Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit
Normal file
21
Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-1.autoit
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
local $bottleNo=99
|
||||
local $lyrics=" "
|
||||
|
||||
While $bottleNo<>0
|
||||
If $bottleNo=1 Then
|
||||
$lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF
|
||||
$lyrics&=$bottleNo & " bottles of beer" & @CRLF
|
||||
$lyrics&="Take one down, pass it around" & @CRLF
|
||||
Else
|
||||
$lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF
|
||||
$lyrics&=$bottleNo & " bottles of beer" & @CRLF
|
||||
$lyrics&="Take one down, pass it around" & @CRLF
|
||||
EndIf
|
||||
If $bottleNo=1 Then
|
||||
$lyrics&=$bottleNo-1 & " bottle of beer" & @CRLF
|
||||
Else
|
||||
$lyrics&=$bottleNo-1 & " bottles of beer" & @CRLF
|
||||
EndIf
|
||||
$bottleNo-=1
|
||||
WEnd
|
||||
MsgBox(1,"99",$lyrics)
|
||||
15
Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit
Normal file
15
Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer-2.autoit
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
$bottles = 99
|
||||
$lyrics1 = " bottles of beer on the wall. "
|
||||
$lyrics2 = " bottles of beer. Take one down and pass it around. "
|
||||
|
||||
For $i = $bottles To 1 Step -1
|
||||
If $i = 1 Then
|
||||
$lyrics1 = " bottle of beer on the wall. "
|
||||
$lyrics2 = " bottle of beer. Take one down and pass it around. "
|
||||
$lyrics3 = " Go to the store and get some more! No bottles of beer on the wall!"
|
||||
ConsoleWrite($bottles & $lyrics1 & $bottles & $lyrics2 & $lyrics3 & @CRLF)
|
||||
Else
|
||||
ConsoleWrite($bottles & $lyrics1 & $bottles & $lyrics2 & $bottles - 1 & $lyrics1 & @CRLF)
|
||||
$bottles -= 1
|
||||
EndIf
|
||||
Next
|
||||
|
|
@ -47,75 +47,57 @@ working-storage section.
|
|||
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
|
||||
display " of beer on the wall"
|
||||
perform 100-show-number
|
||||
display " of beer"
|
||||
display "Take " with no advancing
|
||||
if one-bottle-left
|
||||
string outline delimited by space, space, "it" delimited by size, space, "|" into outline end-string
|
||||
display "it " with no advancing
|
||||
else
|
||||
string outline delimited by space, space, "one" delimited by size, space, "|" into outline end-string
|
||||
display "one " with no advancing
|
||||
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
|
||||
display "down and pass it round"
|
||||
subtract 1 from counter giving counter
|
||||
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
|
||||
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"
|
||||
display "Ninety Nine bottles of beer on the wall"
|
||||
stop run.
|
||||
|
||||
|
||||
100-show-number.
|
||||
if no-bottles-left
|
||||
move "No more|" to stringified
|
||||
display "No more" with no advancing
|
||||
else
|
||||
if counter < 20
|
||||
string function trim( adigits( counter ) ), "|" into stringified
|
||||
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 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 "|"
|
||||
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
|
||||
string stringified delimited by "|", space, "bottle|" delimited by size into stringified end-string
|
||||
display " bottle" with no advancing
|
||||
else
|
||||
string stringified delimited by "|", space, "bottles|" delimited by size into stringified end-string
|
||||
display " bottles" with no advancing
|
||||
end-if.
|
||||
|
||||
100-end.
|
||||
|
|
|
|||
|
|
@ -47,57 +47,75 @@ working-storage section.
|
|||
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
|
||||
display " of beer on the wall"
|
||||
perform 100-show-number
|
||||
display " of beer"
|
||||
display "Take " with no advancing
|
||||
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
|
||||
display "it " with no advancing
|
||||
string outline delimited by space, space, "it" delimited by size, space, "|" into outline end-string
|
||||
else
|
||||
display "one " with no advancing
|
||||
string outline delimited by space, space, "one" delimited by size, space, "|" into outline end-string
|
||||
end-if
|
||||
display "down and pass it round"
|
||||
subtract 1 from counter giving counter
|
||||
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
|
||||
display " of beer on the wall"
|
||||
add 1 to counter giving counter
|
||||
display space
|
||||
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"
|
||||
display "Ninety-Nine bottles of beer on the wall"
|
||||
stop run.
|
||||
|
||||
|
||||
100-show-number.
|
||||
if no-bottles-left
|
||||
display "No more" with no advancing
|
||||
move "No more|" to stringified
|
||||
else
|
||||
if counter < 20
|
||||
display function trim( adigits( counter ) ) with no advancing
|
||||
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
|
||||
display function trim( number-name) with no advancing
|
||||
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
|
||||
display " bottle" with no advancing
|
||||
string stringified delimited by "|", space, "bottle|" delimited by size into stringified end-string
|
||||
else
|
||||
display " bottles" with no advancing
|
||||
string stringified delimited by "|", space, "bottles|" delimited by size into stringified end-string
|
||||
end-if.
|
||||
|
||||
100-end.
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
* 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 0.3.3211
|
||||
* compiles and runs with chpl compiler version 1.7.0
|
||||
* for more information, contact: chapel_info@cray.com
|
||||
*
|
||||
*
|
||||
|
|
@ -23,7 +23,7 @@ config const numBottles = 99;
|
|||
const numVerses = numBottles+1;
|
||||
|
||||
// a domain to describe the space of lyrics
|
||||
var LyricsSpace: domain(1) = [1..numVerses];
|
||||
var LyricsSpace: domain(1) = {1..numVerses};
|
||||
|
||||
// array of lyrics
|
||||
var Lyrics: [LyricsSpace] string;
|
||||
|
|
@ -39,7 +39,7 @@ writeln(Lyrics);
|
|||
|
||||
// HELPER FUNCTIONS:
|
||||
|
||||
fun computeLyric(verseNum) {
|
||||
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
|
||||
|
|
@ -50,7 +50,7 @@ fun computeLyric(verseNum) {
|
|||
}
|
||||
|
||||
|
||||
fun describeBottles(bottleNum, startOfVerse:bool = false) {
|
||||
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"
|
||||
|
|
@ -62,7 +62,7 @@ fun describeBottles(bottleNum, startOfVerse:bool = false) {
|
|||
}
|
||||
|
||||
|
||||
fun computeAction(bottleNum) {
|
||||
proc computeAction(bottleNum) {
|
||||
return if (bottleNum == 0) then "Go to the store and buy some more, "
|
||||
else "Take one down and pass it around, ";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,3 +12,5 @@ Take one down, pass it around,
|
|||
[start]
|
||||
(doseq [n (range start 0 -1)]
|
||||
(verse n)))
|
||||
|
||||
(sing 99)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,22 @@
|
|||
MODULE BottlesOfBeer;
|
||||
IMPORT StdLog;
|
||||
CONST bottles = 99;
|
||||
|
||||
PROCEDURE Part(i: INTEGER);
|
||||
BEGIN
|
||||
StdLog.Int(i);StdLog.String(" bottles of beer on the wall");StdLog.Ln;
|
||||
StdLog.Int(i);StdLog.String(" bottles of beer");StdLog.Ln;
|
||||
StdLog.String("Take one down, pass it around");StdLog.Ln;
|
||||
StdLog.Int(i - 1);StdLog.String(" bottles of beer on the wall.");StdLog.Ln;
|
||||
StdLog.Ln
|
||||
END Part;
|
||||
|
||||
PROCEDURE Sing*;
|
||||
VAR
|
||||
i: INTEGER;
|
||||
BEGIN
|
||||
FOR i := bottles TO 1 BY -1 DO
|
||||
Part(i)
|
||||
END
|
||||
END Sing;
|
||||
END BottlesOfBeer.
|
||||
40
Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer.e
Normal file
40
Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer.e
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
class
|
||||
APPLICATION
|
||||
|
||||
create
|
||||
make
|
||||
|
||||
feature {NONE} -- Initialization
|
||||
|
||||
make
|
||||
local
|
||||
bottles: INTEGER
|
||||
do
|
||||
from
|
||||
bottles := 99
|
||||
invariant
|
||||
bottles <= 99 and bottles >= 1
|
||||
until
|
||||
bottles = 1
|
||||
loop
|
||||
print (bottles)
|
||||
print (" bottles of beer on the wall,%N")
|
||||
print (bottles)
|
||||
print (" bottles of beer.%N")
|
||||
print ("Take one down, pass it around,%N")
|
||||
bottles := bottles - 1
|
||||
if bottles > 1 then
|
||||
print (bottles)
|
||||
print (" bottles of beer on the wall.%N%N")
|
||||
end
|
||||
variant
|
||||
bottles
|
||||
end
|
||||
print ("1 bottle of beer on the wall.%N%N");
|
||||
print ("No more bottles of beer on the wall,%N");
|
||||
print ("no more bottles of beer.%N");
|
||||
print ("Go to the store and buy some more,%N");
|
||||
print ("99 bottles of beer on the wall.%N");
|
||||
end
|
||||
|
||||
end
|
||||
16
Task/99-Bottles-of-Beer/Elixir/99-bottles-of-beer.elixir
Normal file
16
Task/99-Bottles-of-Beer/Elixir/99-bottles-of-beer.elixir
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
defmodule Bottles do
|
||||
def run do
|
||||
Enum.each 99..1, fn idx ->
|
||||
IO.puts "#{idx} bottle#{plural(idx)} of beer on the wall"
|
||||
IO.puts "#{idx} bottle#{plural(idx)} of beer"
|
||||
IO.puts "Take one down, pass it around"
|
||||
IO.puts "#{idx - 1} bottle#{plural(idx-1)} of beer on the wall"
|
||||
IO.puts ""
|
||||
end
|
||||
end
|
||||
|
||||
def plural(1), do: ""
|
||||
def plural(num), do: "s"
|
||||
end
|
||||
|
||||
Bottles.run
|
||||
|
|
@ -6,5 +6,3 @@ for i=1,99 do begin
|
|||
99-i, " bottles of beer on the wall."
|
||||
endfor
|
||||
End
|
||||
|
||||
}
|
||||
|
|
|
|||
12
Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js
Normal file
12
Task/99-Bottles-of-Beer/JavaScript/99-bottles-of-beer-5.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
(function(){var beer = 99,string='';
|
||||
while (beer > 0)
|
||||
{
|
||||
string+=beer+"bottles of beer on the wall\n"+ //inline line appending shouldn't be as expensive.
|
||||
beer +
|
||||
"bottles of beer\nTake one down, pass it around\n"+
|
||||
(--beer)+
|
||||
" bottles of beer on the wall\n" ;
|
||||
|
||||
}
|
||||
console.log(string);
|
||||
})()
|
||||
33
Task/99-Bottles-of-Beer/Lhogho/99-bottles-of-beer.lhogho
Normal file
33
Task/99-Bottles-of-Beer/Lhogho/99-bottles-of-beer.lhogho
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
to bottle :i
|
||||
if :i = 0 [output "|No more bottles of beer|]
|
||||
if :i = 1 [output "|One bottle of beer|]
|
||||
output word :i "| bottles of beer|
|
||||
end
|
||||
|
||||
to it_one :n
|
||||
if :n = 1 [output "it][output "one]
|
||||
end
|
||||
|
||||
to verse :i
|
||||
(print bottle :i "| on the wall,|)
|
||||
(print word bottle :i ".)
|
||||
(print "Take it_one :i "|down, pass it round|)
|
||||
(print bottle :i - 1 "| on the wall.|)
|
||||
print
|
||||
end
|
||||
|
||||
to sing :i
|
||||
if :i = 0
|
||||
[
|
||||
print "|No more bottles of beer on the wall,
|
||||
No more bottles of beer.
|
||||
Go to the store and buy some more.
|
||||
99 bottles of beer on the wall.|
|
||||
stop
|
||||
]
|
||||
verse :i
|
||||
sing :i - 1
|
||||
end
|
||||
|
||||
;Using it:
|
||||
sing 99
|
||||
19
Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l
Normal file
19
Task/99-Bottles-of-Beer/Lisp/99-bottles-of-beer.l
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
(defun beer-verse (count)
|
||||
"Recurses the verses"
|
||||
(format t "~A bottle~A of beer on the wall~%"
|
||||
count
|
||||
(if (/= count 1) "s" ""))
|
||||
(format t "~A bottle~A of beer~%"
|
||||
count
|
||||
(if (/= count 1) "s" ""))
|
||||
(format t "Take one down, pass it round~%")
|
||||
(format t "~A bottle~A of beer on the wall~%~%"
|
||||
(if (= count 1)
|
||||
"No"
|
||||
(- count 1))
|
||||
(if (/= count 2)
|
||||
"s"
|
||||
""))
|
||||
(if (> count 1)
|
||||
(beer-verse (- count 1))))
|
||||
(beer-verse 99)
|
||||
37
Task/99-Bottles-of-Beer/PostScript/99-bottles-of-beer.ps
Normal file
37
Task/99-Bottles-of-Beer/PostScript/99-bottles-of-beer.ps
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
%!PS
|
||||
/Helvetica findfont 9 scalefont setfont
|
||||
|
||||
/printBeer {
|
||||
dup
|
||||
20 string cvs show
|
||||
( bottle) show
|
||||
1 ne
|
||||
{ (s) show } if
|
||||
( of beer) show
|
||||
} def
|
||||
|
||||
/printVerse {
|
||||
dup
|
||||
dup
|
||||
dup
|
||||
7 mul
|
||||
50 add
|
||||
/yPos exch def
|
||||
15 yPos moveto
|
||||
printBeer
|
||||
( on the wall, ) show
|
||||
printBeer
|
||||
(. ) show
|
||||
(Take one down, pass it around, ) show
|
||||
1 sub
|
||||
printBeer
|
||||
( on the wall. ) show
|
||||
} def
|
||||
|
||||
/song {
|
||||
100 -1 1 { printVerse } for
|
||||
} def
|
||||
|
||||
song
|
||||
showpage
|
||||
%%EOF
|
||||
29
Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql
Normal file
29
Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
DELIMITER $$
|
||||
DROP PROCEDURE IF EXISTS bottles_$$
|
||||
CREATE pROCEDURE `bottles_`(inout bottle_count int, inout song text)
|
||||
BEGIN
|
||||
declare bottles_text varchar(30);
|
||||
|
||||
|
||||
IF bottle_count > 0 THEN
|
||||
|
||||
|
||||
if bottle_count != 1 then
|
||||
set bottles_text := ' bottles of beer ';
|
||||
else set bottles_text = ' bottle of beer ';
|
||||
end if;
|
||||
|
||||
SELECT concat(song, bottle_count, bottles_text, ' \n') INTO song;
|
||||
SELECT concat(song, bottle_count, bottles_text, 'on the wall\n') INTO song;
|
||||
SELECT concat(song, 'Take one down, pass it around\n') into song;
|
||||
SELECT concat(song, bottle_count -1 , bottles_text, 'on the wall\n\n') INTO song;
|
||||
set bottle_count := bottle_count -1;
|
||||
CALL bottles_( bottle_count, song);
|
||||
END IF;
|
||||
END$$
|
||||
|
||||
set @bottles=99;
|
||||
set max_sp_recursion_depth=@bottles;
|
||||
set @song='';
|
||||
call bottles_( @bottles, @song);
|
||||
select @song;
|
||||
46
Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-2.sql
Normal file
46
Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-2.sql
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
CREATE PROCEDURE bottles
|
||||
@bottle_count int,
|
||||
@song varchar(MAX)
|
||||
|
||||
AS
|
||||
BEGIN
|
||||
|
||||
declare @bottles_text VARCHAR(MAX);
|
||||
|
||||
|
||||
IF @bottle_count > 0
|
||||
BEGIN
|
||||
IF @bottle_count != 1
|
||||
BEGIN
|
||||
SET @bottles_text = ' bottles of beer ';
|
||||
END
|
||||
ELSE
|
||||
BEGIN
|
||||
SET @bottles_text = ' bottle of beer ';
|
||||
END
|
||||
|
||||
|
||||
|
||||
SET @song = @song + CAST(@bottle_count AS VARCHAR) + @bottles_text + '\n';
|
||||
|
||||
SET @song = @song + CAST(@bottle_count AS VARCHAR) + @bottles_text + 'on the wall\n'
|
||||
SET @song = @song + 'Take one down, pass it around\n'
|
||||
SET @song = @song + CAST((@bottle_count - 1) AS VARCHAR) + @bottles_text + 'on the wall\n'
|
||||
|
||||
|
||||
SET @bottle_count = (@bottle_count - 1);
|
||||
|
||||
|
||||
|
||||
|
||||
EXEC bottles @bottle_count, @song
|
||||
|
||||
END
|
||||
ELSE
|
||||
select @song AS 'RESULT'
|
||||
END
|
||||
|
||||
/*****
|
||||
AND IN ORDER TO CALL PROCEDURE:
|
||||
****/
|
||||
EXECUTE bottles 31, '';
|
||||
19
Task/99-Bottles-of-Beer/Vala/99-bottles-of-beer.vala
Normal file
19
Task/99-Bottles-of-Beer/Vala/99-bottles-of-beer.vala
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
void main() {
|
||||
uint bottles = 99;
|
||||
do {
|
||||
print("%u bottles of beer on the wall.\n", bottles);
|
||||
print("%u bottles of beer!\n", bottles);
|
||||
print("Take one down, pass it around!\n");
|
||||
--bottles;
|
||||
if (bottles == 0) {
|
||||
print("No bottles");
|
||||
}
|
||||
else if (bottles == 1) {
|
||||
print("1 bottle");
|
||||
}
|
||||
else {
|
||||
print("%u bottles", bottles);
|
||||
}
|
||||
print(" of beer on the wall!\n\n");
|
||||
} while (bottles != 0);
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
'''A+B''' - in programming contests, classic problem, which is given so contestants can gain familiarity with online judging system being used.
|
||||
'''A+B''' - in programming contests, classic problem, which is given so contestants can gain familiarity with the online judging system being used.
|
||||
|
||||
'''Problem statement'''<br>
|
||||
Given 2 integer numbers, A and B. One needs to find their sum.
|
||||
|
|
|
|||
2
Task/A+B/ARM-Assembly/a+b-1.arm
Normal file
2
Task/A+B/ARM-Assembly/a+b-1.arm
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
as -o ab.o ab.S
|
||||
ld -o a.out ab.o
|
||||
513
Task/A+B/ARM-Assembly/a+b-2.arm
Normal file
513
Task/A+B/ARM-Assembly/a+b-2.arm
Normal file
|
|
@ -0,0 +1,513 @@
|
|||
.data
|
||||
.align 2
|
||||
.code 32
|
||||
|
||||
.section .rodata
|
||||
.align 2
|
||||
.code 32
|
||||
|
||||
overflow_msg: .ascii "Invalid number. Overflow.\n"
|
||||
overflow_msglen = . - overflow_msg
|
||||
bad_input_msg: .ascii "Invalid input. NaN.\n"
|
||||
bad_input_msglen = . - bad_input_msg
|
||||
range_err_msg: .ascii "Value out of range.\n"
|
||||
range_err_msglen = . - range_err_msg
|
||||
io_error_msg: .ascii "I/O error.\n"
|
||||
io_error_msglen = . - range_err_msg
|
||||
|
||||
sys_exit = 1
|
||||
sys_read = 3
|
||||
sys_write = 4
|
||||
max_rd_buf = 14
|
||||
lf = 10
|
||||
m10_9 = 0x3b9aca00
|
||||
maxval = 1000
|
||||
minval = -1000
|
||||
|
||||
.text
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@ void main()
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type _start STT_FUNC
|
||||
.global _start
|
||||
_start:
|
||||
stmfd sp!, {r4,r5,lr}
|
||||
|
||||
.read_lhs:
|
||||
ldr r0, =max_rd_buf
|
||||
bl readint
|
||||
mov r4, r0
|
||||
bl printint
|
||||
mov r0, r4
|
||||
bl range_check
|
||||
|
||||
.read_rhs:
|
||||
ldr r0, =max_rd_buf
|
||||
bl readint
|
||||
mov r5, r0
|
||||
bl printint
|
||||
mov r0, r5
|
||||
bl range_check
|
||||
|
||||
.sum_and_print:
|
||||
adds r0, r4, r5
|
||||
bvs overflow
|
||||
bl printint
|
||||
|
||||
.main_exit:
|
||||
mov r0, #0
|
||||
bl exit
|
||||
ldmfd sp!, {r4,r5,pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@ Read from stdin until we encounter a non-digit, or we have read bytes2rd digits.
|
||||
@@ Ignore leading spaces.
|
||||
@@ Return value to the caller converted to a signed int.
|
||||
@@ We read positive values, but if we read a leading '-' sign, we convert the
|
||||
@@ return value to two's complement.
|
||||
@@ The argument is max number of bytes to read from stdin.
|
||||
@@ int readint(int bytes2rd)
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type readint STT_FUNC
|
||||
.global readint
|
||||
readint:
|
||||
stmfd sp!, {r4,r5,r6,r7,lr}
|
||||
@@@@@@@@@@@@@@@
|
||||
@@ r0 : #0 for stdin arg to read.
|
||||
@@ r1 : ptr to current pos in local buffer.
|
||||
@@ r2 : #1 to read one byte at a time.
|
||||
@@ r3,r7 : tmp.
|
||||
@@ r4 : number of bytes read.
|
||||
@@ r5 : value of current byte.
|
||||
@@ r6 : 0 while we are reading leading spaces.
|
||||
@@@@@@@@@@@@@@@
|
||||
sub sp, sp, r0
|
||||
mov r1, sp
|
||||
mov r3, #0
|
||||
push {r3} @ sp,#4: local var @isnegative. return in r1. Default value is 0/false. Positive number.
|
||||
push {r0} @ sp,#0: local var @maxbytes. const.
|
||||
mov r2, #1
|
||||
mov r4, #0
|
||||
|
||||
mov r6, #0
|
||||
b .rd
|
||||
@ we get here if r6 is 0.
|
||||
@ if space, goto .rd.
|
||||
@ else set r6 to 1 and goto .noleading.
|
||||
.leadchk:
|
||||
mov r0, r5
|
||||
bl isspace
|
||||
cmp r0, #1
|
||||
beq .rd
|
||||
|
||||
.sign_chk:
|
||||
mov r0, r5
|
||||
push {r1}
|
||||
bl issign
|
||||
cmp r0, #1
|
||||
streq r0, [sp,#8] @ sp,#4 + 4 for the pushed r1.
|
||||
movhi r1, #0
|
||||
strhi r1, [sp,#8] @ sp,#4 + 4 for the pushed r1.
|
||||
pop {r1}
|
||||
bhs .rd
|
||||
|
||||
mov r6, #1
|
||||
b .noleading
|
||||
|
||||
.rd:
|
||||
mov r0, #0
|
||||
bl read
|
||||
cmp r0, #1
|
||||
bne .sum_digits_eof @ eof
|
||||
mov r5, #0
|
||||
ldrb r5, [r1]
|
||||
cmp r6, #0
|
||||
beq .leadchk
|
||||
|
||||
.noleading:
|
||||
mov r0, r5
|
||||
bl isdigit
|
||||
cmp r0, #1
|
||||
bne .sum_digits_nan @ r5 is non-digit
|
||||
|
||||
add r4, r4, #1
|
||||
add r1, r1, #1
|
||||
@ max chars to read is received in arg[0], stored in local var at sp.
|
||||
@ Only 10 can be valid, so the default of 12 leaves space for separator.
|
||||
ldr r3, [sp]
|
||||
cmp r4, r3
|
||||
beq .sum_digits_maxrd @ max bytes read.
|
||||
b .rd
|
||||
|
||||
|
||||
@@@@@@@@@@@@@@@
|
||||
@ We have read r4 (0..arg[0](default 12)) digits when we get here. Go through them
|
||||
@ and add/mul them together to calculate a number.
|
||||
@ We multiply and add the digits in reverse order to simplify the multiplication.
|
||||
@@@@@@@@@@@@@@@
|
||||
@ r0: return value.
|
||||
@ r1: local variable for read buffer.
|
||||
@ r2: tmp for conversion.
|
||||
@ r3,r6,r7: tmp
|
||||
@ r4: number of chars we have read.
|
||||
@ r5: multiplier 1,10,100.
|
||||
@@@@@@@@@@@@@@@
|
||||
.sum_digits_nan:
|
||||
mov r0, r5
|
||||
bl isspace
|
||||
cmp r0, #1
|
||||
bne bad_input
|
||||
.sum_digits_maxrd:
|
||||
.sum_digits_eof:
|
||||
mov r0, #0
|
||||
mov r5, #1
|
||||
.count:
|
||||
cmp r4, #0
|
||||
beq .readint_ret
|
||||
sub r4, r4, #1
|
||||
sub r1, #1
|
||||
ldrb r2, [r1]
|
||||
sub r2, r2, #48
|
||||
mov r3, r2
|
||||
|
||||
@ multiply r3 (char value of digit) with r5 (multiplier).
|
||||
@ possible overflow.
|
||||
@ MI means negative.
|
||||
@ smulls multiples two signed 32 bit vals and returns a 64 bit result.
|
||||
@ If we get anything in r7, the value has overflowed.
|
||||
@ having r2[31] set is overflow too.
|
||||
smulls r2, r7, r3, r5
|
||||
cmp r7, #0
|
||||
bne overflow
|
||||
cmp r2, #0
|
||||
bmi overflow
|
||||
|
||||
@@ possible overflow.
|
||||
adds r0, r0, r2
|
||||
bvs overflow
|
||||
bmi overflow
|
||||
|
||||
@@ end of array check.
|
||||
@@ check is needed here too, for large numbers, since 10 billion is not a valid 32 bit val.
|
||||
cmp r4, #0
|
||||
beq .readint_ret
|
||||
|
||||
@@ multiple multiplier by 10.
|
||||
@@ possible overflow.
|
||||
@@ too many digits is input. happens if input is more than 10 digits.
|
||||
mov r3, #10
|
||||
mov r6, r5
|
||||
smulls r5, r7, r3, r6
|
||||
cmp r7, #0
|
||||
bne overflow
|
||||
cmp r5, #0
|
||||
bmi overflow
|
||||
b .count
|
||||
|
||||
.readint_ret:
|
||||
ldr r1, [sp,#4] @ read isnegative value.
|
||||
cmp r1, #0
|
||||
rsbne r0, r0, #0
|
||||
pop {r2}
|
||||
add sp, sp, #4
|
||||
add sp, sp, r2
|
||||
ldmfd sp!, {r4,r5,r6,r7,pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@ int isdigit(int)
|
||||
@@ #48..#57 ascii range for '0'..'9'.
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type isdigit STT_FUNC
|
||||
.global isdigit
|
||||
isdigit:
|
||||
stmfd sp!, {r1,lr}
|
||||
cmp r0, #48
|
||||
blo .o_range
|
||||
cmp r0, #57
|
||||
bhi .o_range
|
||||
mov r0, #1
|
||||
ldmfd sp!, {r1,pc}
|
||||
.o_range:
|
||||
mov r0, #0
|
||||
ldmfd sp!, {r1,pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@ int isspace(int)
|
||||
@@ ascii space = 32, tab = 9, newline 10, cr = 13.
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type isspace STT_FUNC
|
||||
.global isspace
|
||||
isspace:
|
||||
stmfd sp!, {lr}
|
||||
cmp r0, #32
|
||||
cmpne r0, #9
|
||||
cmpne r0, #10
|
||||
cmpne r0, #13
|
||||
beq .is_space
|
||||
mov r0, #0
|
||||
ldmfd sp!, {pc}
|
||||
.is_space:
|
||||
mov r0, #1
|
||||
ldmfd sp!, {pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@ Return value is 1 for '-' 2 for '+'.
|
||||
@@ int isspace(int)
|
||||
@@ '+' = 43 and '-' = 45.
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type issign STT_FUNC
|
||||
.global issign
|
||||
issign:
|
||||
stmfd sp!, {lr}
|
||||
cmp r0, #43
|
||||
beq .plus_sign
|
||||
cmp r0, #45
|
||||
beq .minus_sign
|
||||
mov r0, #0
|
||||
ldmfd sp!, {pc}
|
||||
.plus_sign:
|
||||
mov r0, #2
|
||||
ldmfd sp!, {pc}
|
||||
.minus_sign:
|
||||
mov r0, #1
|
||||
ldmfd sp!, {pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@ ARGS:
|
||||
@@ r0 : in out arg (current int value)
|
||||
@@ r1 : in out arg (ptr to current pos in buffer)
|
||||
@@ r2 : in arg (const increment. 1000_000_000, 100_000_000, 10_000_000, 1000_000, 100_000, 10_000, 1000, 100, 10, 1.)
|
||||
@@
|
||||
@@ r4 : tmp local. Outer scope must init to #10 and count down to #0.
|
||||
@@ Special case is INTMAX. Must init to 5 if r4 >= 1000_000_000 (0x3b9aca00 = m10_9).
|
||||
@@ r5: tmp
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type get_digit STT_FUNC
|
||||
.global get_digit
|
||||
get_digit:
|
||||
stmfd sp!, {r2,r4,r5,lr}
|
||||
ldr r5, =m10_9
|
||||
cmp r2, r5
|
||||
movlo r4, #10
|
||||
movhs r4, #5
|
||||
.get_digit_loop:
|
||||
sub r4, #1
|
||||
mul r5, r4, r2
|
||||
cmp r0, r5
|
||||
blo .get_digit_loop
|
||||
sub r0, r5
|
||||
add r4, r4, #48
|
||||
strb r4, [r1], #1
|
||||
ldmfd sp!, {r2,r4,r5,pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@ A quick way to divide (numbers evenly divisible by 10) by 10.
|
||||
@@ Most ARM cpus don't have a divide instruction,
|
||||
@@ so this will always work.
|
||||
@@ A generic div function is long and not needed here.
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.div_r2_10:
|
||||
stmfd sp!, {r0,r1,r3,lr}
|
||||
mov r0, #1
|
||||
mov r1, #10
|
||||
.find_x:
|
||||
mul r3, r0, r1;
|
||||
cmp r3, r2
|
||||
movlo r0, r3
|
||||
blo .find_x
|
||||
mov r2, r0
|
||||
ldmfd sp!, {r0,r1,r3,pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.print_neg_sign:
|
||||
stmfd sp!, {r0,r1,r2,lr}
|
||||
@ 45 = '-'
|
||||
mov r1, #45
|
||||
push {r1}
|
||||
mov r2, #1
|
||||
@ r1 is ptr to our local variable (holding '-').
|
||||
mov r1, sp
|
||||
mov r0, #1
|
||||
bl write
|
||||
cmp r0, #0
|
||||
blne io_error
|
||||
pop {r1}
|
||||
ldmfd sp!, {r0,r1,r2,pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@ void printint(int val)
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type printint STT_FUNC
|
||||
.global printint
|
||||
printint:
|
||||
stmfd sp!, {r4,r5,r6,lr}
|
||||
mov r1, #1
|
||||
ands r1, r1, r0, LSR #31
|
||||
rsbne r0, r0, #0
|
||||
blne .print_neg_sign
|
||||
sub sp, sp, #20
|
||||
mov r1, sp
|
||||
mov r3, sp
|
||||
|
||||
ldr r2, =m10_9
|
||||
.getc_loop:
|
||||
bl get_digit
|
||||
cmp r2, #1
|
||||
beq .exit_getc_loop
|
||||
bl .div_r2_10
|
||||
b .getc_loop
|
||||
.exit_getc_loop:
|
||||
ldr r0, =lf
|
||||
strb r0, [r1], #1
|
||||
|
||||
sub r2, r1, r3
|
||||
mov r1, r3
|
||||
mov r0, #1
|
||||
bl write
|
||||
cmp r0, #0
|
||||
blne io_error
|
||||
add sp, sp, #20
|
||||
ldmfd sp!, {r4,r5,r6,pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
range_check:
|
||||
stmfd sp!, {r4,r5,lr}
|
||||
ldr r4, =minval
|
||||
ldr r5, =maxval
|
||||
cmp r4, #0
|
||||
cmpeq r5, #0
|
||||
beq .skip_range_check
|
||||
cmp r0, r4
|
||||
bllt range_err
|
||||
cmp r0, r5
|
||||
blgt range_err
|
||||
.skip_range_check:
|
||||
ldmfd sp!, {r4,r5,pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@ void range_err()
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
range_err:
|
||||
stmfd sp!, {lr}
|
||||
ldr r2, =range_err_msglen
|
||||
ldr r1, =range_err_msg
|
||||
mov r0, #2
|
||||
bl write
|
||||
mov r0, #-1
|
||||
bl exit
|
||||
ldmfd sp!, {pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@ void overflow()
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
overflow:
|
||||
stmfd sp!, {lr}
|
||||
ldr r2, =overflow_msglen
|
||||
ldr r1, =overflow_msg
|
||||
mov r0, #2
|
||||
bl write
|
||||
mov r0, #-1
|
||||
bl exit
|
||||
ldmfd sp!, { pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@ void bad_input()
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
bad_input:
|
||||
stmfd sp!, {lr}
|
||||
ldr r2, =bad_input_msglen
|
||||
ldr r1, =bad_input_msg
|
||||
mov r0, #2
|
||||
bl write
|
||||
mov r0, #-1
|
||||
bl exit
|
||||
ldmfd sp!, {pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@ void io_error()
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
io_error:
|
||||
stmfd sp!, {lr}
|
||||
ldr r2, =io_error_msglen
|
||||
ldr r1, =io_error_msg
|
||||
mov r0, #2
|
||||
bl write
|
||||
mov r0, #-1
|
||||
bl exit
|
||||
ldmfd sp!, {pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@ void exit(int)
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type _start STT_FUNC
|
||||
.global exit
|
||||
exit:
|
||||
stmfd sp!, {r7, lr}
|
||||
ldr r7, =sys_exit
|
||||
svc #0
|
||||
ldmfd sp!, {r7, pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@ int write(int fd,char*buf,int len)
|
||||
@ Return 0 if we successfully write all bytes. Otherwise return the error code.
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type _start STT_FUNC
|
||||
.global write
|
||||
write:
|
||||
stmfd sp!, {r4,r7, lr}
|
||||
mov r4, r2
|
||||
.wr_loop:
|
||||
ldr r7, =sys_write
|
||||
svc #0
|
||||
@ If r0 is negative, it is more than r4 with LO (unsigned <).
|
||||
cmp r0, r4
|
||||
sublo r4, r0
|
||||
blo .wr_loop
|
||||
moveq r0, #0
|
||||
ldmfd sp!, {r4,r7, pc}
|
||||
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@ int read(int fd,char*buf,int len)
|
||||
@ Return number of bytes successfully read. Ignore errors.
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
.align 2
|
||||
.code 32
|
||||
.type _start STT_FUNC
|
||||
.global read
|
||||
read:
|
||||
stmfd sp!, {r7, lr}
|
||||
ldr r7, =sys_read
|
||||
svc #0
|
||||
cmp r0, #0
|
||||
movlt r0, #0
|
||||
ldmfd sp!, {r7, pc}
|
||||
7
Task/A+B/Aime/a+b.aime
Normal file
7
Task/A+B/Aime/a+b.aime
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
file f;
|
||||
list l;
|
||||
|
||||
f_affix(f, "/dev/stdin");
|
||||
f_list(f, l, 0);
|
||||
o_integer(atoi(l_q_text(l, 0)) + atoi(l_q_text(l, 1)));
|
||||
o_newline();
|
||||
|
|
@ -1,6 +1,24 @@
|
|||
, Read first number
|
||||
>,, Eat separator and read second number
|
||||
[<+>-] Add ASCII values
|
||||
,++ Use newline to get a 12
|
||||
[<---->-] Subtract 48 to get back to ASCII
|
||||
<. and print
|
||||
INPUT AND SUMMATION
|
||||
TODO if first symbol is a minus sign print Qgo awayQ
|
||||
+> initialize sum to one
|
||||
++[ loop for each input ie twice
|
||||
[>>,----------[----------------------[-<+>]]<] eat digits until space or newline
|
||||
<[<]>>>
|
||||
>[< until no next digit
|
||||
---------------- subtract ascii zero minus what we subtracted above
|
||||
[->++++++++++<] add ten timess that to the next digit
|
||||
<[->+<]<[->+<]>> shift sum and loop counter
|
||||
>>
|
||||
]
|
||||
<---------------- subtract as above from last digit as well
|
||||
[-<<+>>] add to sum
|
||||
<-
|
||||
]
|
||||
<- subtract original one from sum
|
||||
|
||||
OUTPUT
|
||||
[ while a number divided by ten is bigger than zero
|
||||
[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->--------->+<<[->>>+<<<]]]]]]]]]]>>>[-<<<+>>>]<<<] divide by ten
|
||||
>++++++++++++++++++++++++++++++++++++++++++++++++> convert remainder to ascii digit
|
||||
]
|
||||
<[.<<] print ascii digits
|
||||
|
|
|
|||
14
Task/A+B/CoffeeScript/a+b-1.coffee
Normal file
14
Task/A+B/CoffeeScript/a+b-1.coffee
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
<html>
|
||||
<script type="text/javascript" src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
|
||||
<script type="text/coffeescript">
|
||||
a = window.prompt 'enter A number', ''
|
||||
b = window.prompt 'enter B number', ''
|
||||
document.getElementById('input').innerHTML = a + ' ' + b
|
||||
sum = parseInt(a) + parseInt(b)
|
||||
document.getElementById('output').innerHTML = sum
|
||||
</script>
|
||||
<body>
|
||||
<div id='input'></div>
|
||||
<div id='output'></div>
|
||||
</body>
|
||||
</html>
|
||||
30
Task/A+B/CoffeeScript/a+b-2.coffee
Normal file
30
Task/A+B/CoffeeScript/a+b-2.coffee
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
{ stdin } = process
|
||||
sum = ( a, b ) -> a + b
|
||||
|
||||
display = ( messages... ) -> console.log messages...
|
||||
|
||||
parse = ( input ) ->
|
||||
parseInt x for x in ( x.trim() for x in input.split ' ' ) when x?.length
|
||||
|
||||
check = ( numbers... ) ->
|
||||
return no for x in numbers when isNaN x
|
||||
return no for x in numbers when not ( -1000 < x < 1000 )
|
||||
yes
|
||||
|
||||
prompt = ->
|
||||
display 'Please enter two integers between -1000 and 1000, separated by a space:'
|
||||
stdin.once 'data', ( data ) ->
|
||||
[ a, b ] = parse data
|
||||
if check a, b
|
||||
display "#{ a } + #{ b } = #{ sum a, b }"
|
||||
else
|
||||
display "Invalid input: #{ a }, #{ b }"
|
||||
do prompt
|
||||
return
|
||||
|
||||
# Resume input and set the incoming encoding.
|
||||
stdin.resume()
|
||||
stdin.setEncoding 'utf8'
|
||||
|
||||
# Start the main loop.
|
||||
do prompt
|
||||
29
Task/A+B/Component-Pascal/a+b.component
Normal file
29
Task/A+B/Component-Pascal/a+b.component
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
MODULE AB;
|
||||
IMPORT StdLog, DevCommanders,TextMappers;
|
||||
|
||||
PROCEDURE DoAB(x,y: INTEGER);
|
||||
BEGIN
|
||||
StdLog.Int(x);StdLog.Int(y);StdLog.Int(x + y);StdLog.Ln;
|
||||
END DoAB;
|
||||
|
||||
PROCEDURE Go*;
|
||||
VAR
|
||||
params: DevCommanders.Par;
|
||||
s: TextMappers.Scanner;
|
||||
p : ARRAY 2 OF INTEGER;
|
||||
current: INTEGER;
|
||||
BEGIN
|
||||
current := 0;
|
||||
params := DevCommanders.par;
|
||||
s.ConnectTo(params.text);
|
||||
s.SetPos(params.beg);
|
||||
s.Scan;
|
||||
WHILE(~s.rider.eot) DO
|
||||
IF (s.type = TextMappers.int) THEN
|
||||
p[current] := s.int; INC(current);
|
||||
END;
|
||||
s.Scan;
|
||||
END;
|
||||
IF current = 2 THEN DoAB(p[0],p[1]) END;
|
||||
END Go;
|
||||
END AB.
|
||||
|
|
@ -1,11 +1,10 @@
|
|||
#define std'basic'*.
|
||||
#define ext'io'*.
|
||||
#define system.
|
||||
#define extensions'io.
|
||||
|
||||
#symbol Console =>
|
||||
#symbol program =
|
||||
[
|
||||
#var anOutput := __wrap(ELineInput, 'program'input).
|
||||
#var A := anOutput >> Integer.
|
||||
#var B := anOutput >> Integer.
|
||||
#var A := consoleEx >> Integer new.
|
||||
#var B := consoleEx >> Integer new.
|
||||
|
||||
'program'output << A + B.
|
||||
consoleEx << A + B.
|
||||
].
|
||||
|
|
|
|||
1
Task/A+B/Excel/a+b-1.excel
Normal file
1
Task/A+B/Excel/a+b-1.excel
Normal file
|
|
@ -0,0 +1 @@
|
|||
=A1+B1
|
||||
1
Task/A+B/Excel/a+b-2.excel
Normal file
1
Task/A+B/Excel/a+b-2.excel
Normal file
|
|
@ -0,0 +1 @@
|
|||
1 2 3
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
macro add(a,b)
|
||||
return a + b
|
||||
#A+B
|
||||
function AB()
|
||||
input = sum(map(int,split(readline(STDIN)," ")))
|
||||
println(input)
|
||||
end
|
||||
|
||||
julia> @add 1 2
|
||||
3
|
||||
AB()
|
||||
|
|
|
|||
|
|
@ -1,6 +1,3 @@
|
|||
#aplusb.jl contents
|
||||
x = sum(ARGS)
|
||||
print(x)
|
||||
#run at command prompt
|
||||
$ julia aplusb.jl 1 2
|
||||
$ 3
|
||||
julia> int(readuntil(STDIN, ' ')) + int(readuntil(STDIN, '\n'))
|
||||
1 2
|
||||
3
|
||||
|
|
|
|||
6
Task/A+B/Maxima/a+b.maxima
Normal file
6
Task/A+B/Maxima/a+b.maxima
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
in_stream: openr("/dev/stdin");
|
||||
unless (line: readline(in_stream), line=false) do (
|
||||
q: map('parse_string, split(line, " ")),
|
||||
print(q[1]+q[2])
|
||||
);
|
||||
close(in_stream);
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
(A+B)
|
||||
comment
|
||||
comment: returns the sum of two values taken from standard input
|
||||
(always)
|
||||
(+) (read) (default-input-port)
|
||||
(read) (default-input-port)
|
||||
|
|
|
|||
58
Task/Abstract-type/COBOL/abstract-type.cobol
Normal file
58
Task/Abstract-type/COBOL/abstract-type.cobol
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
INTERFACE-ID. Shape.
|
||||
|
||||
PROCEDURE DIVISION.
|
||||
|
||||
METHOD-ID. perimeter.
|
||||
DATA DIVISION.
|
||||
LINKAGE SECTION.
|
||||
01 ret USAGE FLOAT-LONG.
|
||||
PROCEDURE DIVISION RETURNING ret.
|
||||
END METHOD perimeter.
|
||||
|
||||
METHOD-ID. shape-area.
|
||||
DATA DIVISION.
|
||||
LINKAGE SECTION.
|
||||
01 ret USAGE FLOAT-LONG.
|
||||
PROCEDURE DIVISION RETURNING ret.
|
||||
END METHOD shape-area.
|
||||
|
||||
END INTERFACE Shape.
|
||||
|
||||
|
||||
CLASS-ID. Rectangle.
|
||||
|
||||
ENVIRONMENT DIVISION.
|
||||
CONFIGURATION SECTION.
|
||||
REPOSITORY.
|
||||
INTERFACE Shape.
|
||||
|
||||
OBJECT IMPLEMENTS Shape.
|
||||
DATA DIVISION.
|
||||
WORKING-STORAGE SECTION.
|
||||
01 width USAGE FLOAT-LONG PROPERTY.
|
||||
01 height USAGE FLOAT-LONG PROPERTY.
|
||||
|
||||
PROCEDURE DIVISION.
|
||||
|
||||
METHOD-ID. perimeter.
|
||||
DATA DIVISION.
|
||||
LINKAGE SECTION.
|
||||
01 ret USAGE FLOAT-LONG.
|
||||
PROCEDURE DIVISION RETURNING ret.
|
||||
COMPUTE ret = width * 2.0 + height * 2.0
|
||||
GOBACK
|
||||
.
|
||||
END METHOD perimeter.
|
||||
|
||||
METHOD-ID. shape-area.
|
||||
DATA DIVISION.
|
||||
LINKAGE SECTION.
|
||||
01 ret USAGE FLOAT-LONG.
|
||||
PROCEDURE DIVISION RETURNING ret.
|
||||
COMPUTE ret = width * height
|
||||
GOBACK
|
||||
.
|
||||
END METHOD shape-area.
|
||||
END OBJECT.
|
||||
|
||||
END CLASS Rectangle.
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
(* Abstract type *)
|
||||
Object = POINTER TO ABSTRACT RECORD END;
|
||||
|
||||
(* Integer inherits Object *)
|
||||
Integer = POINTER TO RECORD (Object)
|
||||
i: INTEGER
|
||||
END;
|
||||
(* Point inherits Object *)
|
||||
Point = POINTER TO RECORD (Object)
|
||||
x,y: REAL
|
||||
END;
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
(* Abstract method of Object *)
|
||||
PROCEDURE (dn: Object) Show*, NEW, ABSTRACT;
|
||||
|
||||
(* Implementation of the abstract method Show() in class Integer *)
|
||||
PROCEDURE (i: Integer) Show*;
|
||||
BEGIN
|
||||
StdLog.String("Integer(");StdLog.Int(i.i);StdLog.String(");");StdLog.Ln
|
||||
END Show;
|
||||
|
||||
(* Implementation of the abstract method Show() in class Point *)
|
||||
PROCEDURE (p: Point) Show*;
|
||||
BEGIN
|
||||
StdLog.String("Point(");StdLog.Real(p.x);StdLog.Char(',');
|
||||
StdLog.Real(p.y);StdLog.String(");");StdLog.Ln
|
||||
END Show;
|
||||
38
Task/Abstract-type/Nemerle/abstract-type.nemerle
Normal file
38
Task/Abstract-type/Nemerle/abstract-type.nemerle
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
using System.Console;
|
||||
|
||||
namespace RosettaCode
|
||||
{
|
||||
abstract class Fruit
|
||||
{
|
||||
abstract public Eat() : void;
|
||||
abstract public Peel() : void;
|
||||
|
||||
virtual public Cut() : void // an abstract class con contain a mixture of abstract and implemented methods
|
||||
{ // the virtual keyword allows the method to be overridden by derivative classes
|
||||
WriteLine("Being cut.");
|
||||
}
|
||||
}
|
||||
|
||||
interface IJuiceable
|
||||
{
|
||||
Juice() : void; // interfaces contain only the signatures of methods
|
||||
}
|
||||
|
||||
class Orange : Fruit, IJuiceable
|
||||
{
|
||||
public override Eat() : void // implementations of abstract methods need to be marked override
|
||||
{
|
||||
WriteLine("Being eaten.");
|
||||
}
|
||||
|
||||
public override Peel() : void
|
||||
{
|
||||
WriteLine("Being peeled.");
|
||||
}
|
||||
|
||||
public Juice() : void
|
||||
{
|
||||
WriteLine("Being juiced.");
|
||||
}
|
||||
}
|
||||
}
|
||||
15
Task/Accumulator-factory/Bracmat/accumulator-factory.bracmat
Normal file
15
Task/Accumulator-factory/Bracmat/accumulator-factory.bracmat
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
( ( accumulator
|
||||
=
|
||||
.
|
||||
' ( add sum object
|
||||
. (object=add=$arg+!arg)
|
||||
& !(object.add):?sum
|
||||
& '($($sum)+!arg):(=?(object.add))
|
||||
& !sum
|
||||
)
|
||||
)
|
||||
& accumulator$1:(=?x)
|
||||
& x$5
|
||||
& accumulator$3
|
||||
& out$(x$23/10)
|
||||
)
|
||||
9
Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv
Normal file
9
Task/Accumulator-factory/Deja-Vu/accumulator-factory.djv
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
accum n:
|
||||
labda i:
|
||||
set :n + n i
|
||||
n
|
||||
|
||||
local :x accum 1
|
||||
drop x 5
|
||||
drop accum 3
|
||||
print x 2.3
|
||||
|
|
@ -1,17 +1,19 @@
|
|||
#define std'dictionary'*.
|
||||
#define std'basic'*.
|
||||
#define sys'dynamics'*.
|
||||
#define system.
|
||||
#define system'dynamic.
|
||||
|
||||
#symbol NewAccumulator : aValue =
|
||||
#join (Variable::aValue) { eval : aValue [ $self content'set:($self + aValue). ] }.
|
||||
#symbol Function =
|
||||
&&:x [ self append:x ].
|
||||
|
||||
#symbol Accumulator = &&:anInitialValue
|
||||
[ Wrap(Function, Variable new:anInitialValue) ].
|
||||
|
||||
#symbol Program =
|
||||
[
|
||||
#var x := NewAccumulator::1.
|
||||
#var x := Accumulator:1.
|
||||
|
||||
x::5.
|
||||
x:5.
|
||||
|
||||
NewAccumulator::3.
|
||||
#var y := Accumulator:3.
|
||||
|
||||
'program'Output << x::2.3r.
|
||||
console write:(x:2.3r).
|
||||
].
|
||||
|
|
|
|||
22
Task/Accumulator-factory/Nemerle/accumulator-factory.nemerle
Normal file
22
Task/Accumulator-factory/Nemerle/accumulator-factory.nemerle
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
def Foo(n) {
|
||||
mutable value : object = n;
|
||||
fun (i : object) {
|
||||
match(i) {
|
||||
|x is int => match(value) {
|
||||
|y is int => value = x + y;
|
||||
|y is double => value = x + y;
|
||||
}
|
||||
|x is double => match(value) {
|
||||
|y is int => value = x + (y :> double);
|
||||
|y is double => value = x + y;
|
||||
}
|
||||
}
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
def x = Foo(1);
|
||||
def y = Foo(2.2);
|
||||
x(5);
|
||||
System.Console.WriteLine(x(2.3));
|
||||
System.Console.WriteLine(y(3));
|
||||
11
Task/Ackermann-function/AutoIt/ackermann-function-1.autoit
Normal file
11
Task/Ackermann-function/AutoIt/ackermann-function-1.autoit
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
Func Ackermann($m, $n)
|
||||
If ($m = 0) Then
|
||||
Return $n+1
|
||||
Else
|
||||
If ($n = 0) Then
|
||||
Return Ackermann($m-1, 1)
|
||||
Else
|
||||
return Ackermann($m-1, Ackermann($m, $n-1))
|
||||
EndIf
|
||||
EndIf
|
||||
EndFunc
|
||||
18
Task/Ackermann-function/AutoIt/ackermann-function-2.autoit
Normal file
18
Task/Ackermann-function/AutoIt/ackermann-function-2.autoit
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
Global $ackermann[2047][2047] ; Set the size to whatever you want
|
||||
Func Ackermann($m, $n)
|
||||
If ($ackermann[$m][$n] <> 0) Then
|
||||
Return $ackermann[$m][$n]
|
||||
Else
|
||||
If ($m = 0) Then
|
||||
$return = $n + 1
|
||||
Else
|
||||
If ($n = 0) Then
|
||||
$return = Ackermann($m - 1, 1)
|
||||
Else
|
||||
$return = Ackermann($m - 1, Ackermann($m, $n - 1))
|
||||
EndIf
|
||||
EndIf
|
||||
$ackermann[$m][$n] = $return
|
||||
Return $return
|
||||
EndIf
|
||||
EndFunc ;==>Ackermann
|
||||
32
Task/Ackermann-function/COBOL/ackermann-function.cobol
Normal file
32
Task/Ackermann-function/COBOL/ackermann-function.cobol
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
IDENTIFICATION DIVISION.
|
||||
PROGRAM-ID. Ackermann.
|
||||
|
||||
DATA DIVISION.
|
||||
LINKAGE SECTION.
|
||||
01 M USAGE UNSIGNED-LONG.
|
||||
01 N USAGE UNSIGNED-LONG.
|
||||
|
||||
01 Return-Val USAGE UNSIGNED-LONG.
|
||||
|
||||
PROCEDURE DIVISION USING M N Return-Val.
|
||||
EVALUATE M ALSO N
|
||||
WHEN 0 ALSO ANY
|
||||
ADD 1 TO N GIVING Return-Val
|
||||
|
||||
WHEN NOT 0 ALSO 0
|
||||
SUBTRACT 1 FROM M
|
||||
CALL "Ackermann" USING BY CONTENT M BY CONTENT 1
|
||||
BY REFERENCE Return-Val
|
||||
|
||||
WHEN NOT 0 ALSO NOT 0
|
||||
SUBTRACT 1 FROM N
|
||||
CALL "Ackermann" USING BY CONTENT M BY CONTENT N
|
||||
BY REFERENCE Return-Val
|
||||
|
||||
SUBTRACT 1 FROM M
|
||||
CALL "Ackermann" USING BY CONTENT M
|
||||
BY CONTENT Return-Val BY REFERENCE Return-Val
|
||||
END-EVALUATE
|
||||
|
||||
GOBACK
|
||||
.
|
||||
8
Task/Ackermann-function/Chapel/ackermann-function.chapel
Normal file
8
Task/Ackermann-function/Chapel/ackermann-function.chapel
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
proc A(m:int, n:int):int {
|
||||
if m == 0 then
|
||||
return n + 1;
|
||||
else if n == 0 then
|
||||
return A(m - 1, 1);
|
||||
else
|
||||
return A(m - 1, A(m, n - 1));
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
MODULE NpctAckerman;
|
||||
|
||||
IMPORT StdLog;
|
||||
|
||||
VAR
|
||||
m,n: INTEGER;
|
||||
|
||||
PROCEDURE Ackerman (x,y: INTEGER):INTEGER;
|
||||
|
||||
BEGIN
|
||||
IF x = 0 THEN RETURN y + 1
|
||||
ELSIF y = 0 THEN RETURN Ackerman (x - 1 , 1)
|
||||
ELSE
|
||||
RETURN Ackerman (x - 1 , Ackerman (x , y - 1))
|
||||
END
|
||||
END Ackerman;
|
||||
|
||||
PROCEDURE Do*;
|
||||
BEGIN
|
||||
FOR m := 0 TO 3 DO
|
||||
FOR n := 0 TO 6 DO
|
||||
StdLog.Int (Ackerman (m, n));StdLog.Char (' ')
|
||||
END;
|
||||
StdLog.Ln
|
||||
END;
|
||||
StdLog.Ln
|
||||
END Do;
|
||||
|
||||
END NpctAckerman.
|
||||
|
|
@ -19,7 +19,7 @@ in {
|
|||
assert(m >= 0 && n >= 0);
|
||||
} out(result) {
|
||||
//assert(result >= 0);
|
||||
assert(cast()result >= 0);
|
||||
//assert(cast()result >= 0);
|
||||
} body {
|
||||
/*pure nothrow*/ static BigInt ack(in int m, /*in*/ BigInt n) {
|
||||
switch (m) {
|
||||
|
|
|
|||
|
|
@ -1,33 +1,30 @@
|
|||
#define std'dictionary'*.
|
||||
#define std'patterns'*.
|
||||
|
||||
#subject m, n.
|
||||
#define system.
|
||||
|
||||
// --- Ackermann function ---
|
||||
|
||||
#symbol Ackermann &m:anM &n:anN =
|
||||
#symbol ackermann = &&:m:n
|
||||
[
|
||||
#if anM
|
||||
ifequal:0 [ ^ anN + 1. ]
|
||||
| greater:0 ?
|
||||
[
|
||||
#if anN
|
||||
ifequal:0 [ ^ Ackermann &&m:(anM - 1) &n:1. ]
|
||||
| greater:0 ? [ ^ Ackermann &&m:(anM - 1) &n:(Ackermann &&m:anM &n:(anN - 1)). ].
|
||||
].
|
||||
|
||||
control fail.
|
||||
m =>
|
||||
0 ? [ n + 1 ]
|
||||
> 0 ? [
|
||||
n => 0 ? [ $self:(m - 1):1 ]
|
||||
> 0 ? [ $self:(m - 1):($self:m:(n-1)) ]
|
||||
]
|
||||
].
|
||||
|
||||
#symbol Program =
|
||||
#symbol program =
|
||||
[
|
||||
loop &&from:0 &to:3 run: anM =
|
||||
#var n := ackermann:3:5.
|
||||
|
||||
control from:0 &to:3 &do: &&:i
|
||||
[
|
||||
loop &&from:0 &to:5 run: anN =
|
||||
control from:0 &to:5 &do: &&:j
|
||||
[
|
||||
'program'output << "A(" << anM << "," << anN << ")=" << (Ackermann &&m:anM &n:anN) << "%n".
|
||||
console << "A(" << i << "," << j << ")=" << (ackermann:i:j).
|
||||
|
||||
console writeLine.
|
||||
].
|
||||
].
|
||||
|
||||
'program'Input get.
|
||||
console readChar.
|
||||
].
|
||||
|
|
|
|||
8
Task/Ackermann-function/Java/ackermann-function-1.java
Normal file
8
Task/Ackermann-function/Java/ackermann-function-1.java
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import java.math.BigInteger;
|
||||
|
||||
public static BigInteger ack(BigInteger m, BigInteger n) {
|
||||
return m.equals(BigInteger.ZERO)
|
||||
? n.add(BigInteger.ONE)
|
||||
: ack(m.subtract(BigInteger.ONE),
|
||||
n.equals(BigInteger.ZERO) ? BigInteger.ONE : ack(m, n.subtract(BigInteger.ONE)));
|
||||
}
|
||||
9
Task/Ackermann-function/Java/ackermann-function-2.java
Normal file
9
Task/Ackermann-function/Java/ackermann-function-2.java
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
@FunctionalInterface
|
||||
public interface FunctionalField<FIELD extends Enum<?>> {
|
||||
public Object untypedField(FIELD field);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public default <VALUE> VALUE field(FIELD field) {
|
||||
return (VALUE) untypedField(field);
|
||||
}
|
||||
}
|
||||
46
Task/Ackermann-function/Java/ackermann-function-3.java
Normal file
46
Task/Ackermann-function/Java/ackermann-function-3.java
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public interface TailRecursive {
|
||||
public static <INPUT, INTERMEDIARY, OUTPUT> Function<INPUT, OUTPUT> new_(Function<INPUT, INTERMEDIARY> toIntermediary, UnaryOperator<INTERMEDIARY> unaryOperator, Predicate<INTERMEDIARY> predicate, Function<INTERMEDIARY, OUTPUT> toOutput) {
|
||||
return input ->
|
||||
$.new_(
|
||||
Stream.iterate(
|
||||
toIntermediary.apply(input),
|
||||
unaryOperator
|
||||
),
|
||||
predicate,
|
||||
toOutput
|
||||
)
|
||||
;
|
||||
}
|
||||
|
||||
public static <INPUT1, INPUT2, INTERMEDIARY, OUTPUT> BiFunction<INPUT1, INPUT2, OUTPUT> new_(BiFunction<INPUT1, INPUT2, INTERMEDIARY> toIntermediary, UnaryOperator<INTERMEDIARY> unaryOperator, Predicate<INTERMEDIARY> predicate, Function<INTERMEDIARY, OUTPUT> toOutput) {
|
||||
return (input1, input2) ->
|
||||
$.new_(
|
||||
Stream.iterate(
|
||||
toIntermediary.apply(input1, input2),
|
||||
unaryOperator
|
||||
),
|
||||
predicate,
|
||||
toOutput
|
||||
)
|
||||
;
|
||||
}
|
||||
|
||||
public enum $ {
|
||||
$$;
|
||||
|
||||
private static <INTERMEDIARY, OUTPUT> OUTPUT new_(Stream<INTERMEDIARY> stream, Predicate<INTERMEDIARY> predicate, Function<INTERMEDIARY, OUTPUT> function) {
|
||||
return stream
|
||||
.filter(predicate)
|
||||
.map(function)
|
||||
.findAny()
|
||||
.orElseThrow(RuntimeException::new)
|
||||
;
|
||||
}
|
||||
}
|
||||
}
|
||||
145
Task/Ackermann-function/Java/ackermann-function-4.java
Normal file
145
Task/Ackermann-function/Java/ackermann-function-4.java
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import java.math.BigInteger;
|
||||
import java.util.Stack;
|
||||
import java.util.function.BinaryOperator;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public interface Ackermann {
|
||||
public static Ackermann new_(BigInteger number1, BigInteger number2, Stack<BigInteger> stack, boolean flag) {
|
||||
return $.new_(number1, number2, stack, flag);
|
||||
}
|
||||
public static void main(String... arguments) {
|
||||
$.main(arguments);
|
||||
}
|
||||
public BigInteger number1();
|
||||
public BigInteger number2();
|
||||
|
||||
public Stack<BigInteger> stack();
|
||||
|
||||
public boolean flag();
|
||||
|
||||
public enum $ {
|
||||
$$;
|
||||
|
||||
private static final BigInteger ZERO = BigInteger.ZERO;
|
||||
private static final BigInteger ONE = BigInteger.ONE;
|
||||
private static final BigInteger TWO = BigInteger.valueOf(2);
|
||||
private static final BigInteger THREE = BigInteger.valueOf(3);
|
||||
private static final BigInteger FOUR = BigInteger.valueOf(4);
|
||||
|
||||
private static Ackermann new_(BigInteger number1, BigInteger number2, Stack<BigInteger> stack, boolean flag) {
|
||||
return (FunctionalAckermann) field -> {
|
||||
switch (field) {
|
||||
case number1: return number1;
|
||||
case number2: return number2;
|
||||
case stack: return stack;
|
||||
case flag: return flag;
|
||||
default: throw new UnsupportedOperationException(
|
||||
field instanceof Field
|
||||
? "Field checker has not been updated properly."
|
||||
: "Field is not of the correct type."
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static final BinaryOperator<BigInteger> ACKERMANN =
|
||||
TailRecursive.new_(
|
||||
(BigInteger number1, BigInteger number2) ->
|
||||
new_(
|
||||
number1,
|
||||
number2,
|
||||
Stream.of(number1).collect(
|
||||
Collectors.toCollection(Stack::new)
|
||||
),
|
||||
false
|
||||
)
|
||||
,
|
||||
ackermann -> {
|
||||
BigInteger number1 = ackermann.number1();
|
||||
BigInteger number2 = ackermann.number2();
|
||||
Stack<BigInteger> stack = ackermann.stack();
|
||||
if (!stack.empty() && !ackermann.flag()) {
|
||||
number1 = stack.pop();
|
||||
}
|
||||
switch (number1.intValue()) {
|
||||
case 0:
|
||||
return new_(
|
||||
number1,
|
||||
number2.add(ONE),
|
||||
stack,
|
||||
false
|
||||
);
|
||||
case 1:
|
||||
return new_(
|
||||
number1,
|
||||
number2.add(TWO),
|
||||
stack,
|
||||
false
|
||||
);
|
||||
case 2:
|
||||
return new_(
|
||||
number1,
|
||||
number2.multiply(TWO).add(THREE),
|
||||
stack,
|
||||
false
|
||||
);
|
||||
default:
|
||||
if (ZERO.equals(number2)) {
|
||||
return new_(
|
||||
number1.subtract(ONE),
|
||||
ONE,
|
||||
stack,
|
||||
true
|
||||
);
|
||||
} else {
|
||||
stack.push(number1.subtract(ONE));
|
||||
return new_(
|
||||
number1,
|
||||
number2.subtract(ONE),
|
||||
stack,
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
ackermann -> ackermann.stack().empty(),
|
||||
Ackermann::number2
|
||||
)::apply
|
||||
;
|
||||
|
||||
private static void main(String... arguments) {
|
||||
System.out.println(ACKERMANN.apply(FOUR, TWO));
|
||||
}
|
||||
|
||||
private enum Field {
|
||||
number1,
|
||||
number2,
|
||||
stack,
|
||||
flag
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface FunctionalAckermann extends FunctionalField<Field>, Ackermann {
|
||||
@Override
|
||||
public default BigInteger number1() {
|
||||
return field(Field.number1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public default BigInteger number2() {
|
||||
return field(Field.number2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public default Stack<BigInteger> stack() {
|
||||
return field(Field.stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public default boolean flag() {
|
||||
return field(Field.flag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
(0..3).each do |m|
|
||||
(0..6).each { |n| print ack(m, n), ' ' }
|
||||
puts
|
||||
puts (0..6).map { |n| ack(m, n) }.join(' ')
|
||||
end
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
(ackermann) m n
|
||||
0 3
|
||||
(zero?) m
|
||||
(add1) n
|
||||
(ackermann) integer1 integer2
|
||||
comment: takes two integers -> returns the result
|
||||
(zero?) integer1
|
||||
(add1) integer2
|
||||
|
||||
(ackermann) m n
|
||||
2 0
|
||||
(and) (positive?) m (zero?) n
|
||||
(ackermann) (sub1) m 1
|
||||
(ackermann) integer1 integer2
|
||||
comment: takes two integers -> returns the result
|
||||
(and) (positive?) integer1 (zero?) integer2
|
||||
(ackermann) (sub1) integer1 1
|
||||
|
||||
(ackermann) m n
|
||||
2 3
|
||||
(and) (positive?) m (positive?) n
|
||||
(ackermann) (sub1) m (ackermann) m (sub1) n
|
||||
(ackermann) integer1 integer2
|
||||
comment: takes two integers -> returns the result
|
||||
(and) (positive?) integer1 (positive?) integer2
|
||||
(ackermann) (sub1) integer1 (ackermann) integer1 (sub1) integer2
|
||||
|
|
|
|||
|
|
@ -1,27 +1,35 @@
|
|||
#subject foo.
|
||||
#define system.
|
||||
|
||||
#class FieldContainer
|
||||
#class Extender
|
||||
{
|
||||
#field theValue.
|
||||
#field theObject.
|
||||
#field theField.
|
||||
|
||||
#method foo'set : anObject
|
||||
#constructor new : anObject
|
||||
[
|
||||
theValue := anObject.
|
||||
theObject := anObject.
|
||||
]
|
||||
|
||||
#method foo'get = theValue.
|
||||
#method foo = theField.
|
||||
|
||||
#method set &foo : aValue
|
||||
[
|
||||
theField := aValue.
|
||||
]
|
||||
|
||||
#method => theObject.
|
||||
}
|
||||
|
||||
#symbol Program =
|
||||
#symbol program =
|
||||
[
|
||||
#var anObject := 234.
|
||||
|
||||
// adding a field
|
||||
anObject := anObject &= FieldContainer.
|
||||
anObject := Extender new:anObject.
|
||||
|
||||
anObject foo'set:"bar".
|
||||
anObject set &foo:"bar".
|
||||
|
||||
'program'Output << anObject << ".foo=" << anObject foo.
|
||||
console << anObject << ".foo=" << anObject foo.
|
||||
|
||||
'program'input get.
|
||||
console readChar.
|
||||
].
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
% we start by defining an empty object
|
||||
:- object(foo).
|
||||
|
||||
% ensure that complementing categories are allowed
|
||||
:- set_logtalk_flag(complements, allow).
|
||||
|
||||
:- end_object.
|
||||
|
||||
% define a complementing category, adding a new predicate
|
||||
:- category(bar,
|
||||
complements(foo)).
|
||||
|
||||
:- public(bar/1).
|
||||
bar(1).
|
||||
bar(2).
|
||||
bar(3).
|
||||
|
||||
:- end_category.
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
| ?- foo::bar(X).
|
||||
X = 1 ;
|
||||
X = 2 ;
|
||||
X = 3
|
||||
true
|
||||
2
Task/Address-of-a-variable/C/address-of-a-variable-1.c
Normal file
2
Task/Address-of-a-variable/C/address-of-a-variable-1.c
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
int i;
|
||||
void* address_of_i = &i;
|
||||
1
Task/Address-of-a-variable/C/address-of-a-variable-2.c
Normal file
1
Task/Address-of-a-variable/C/address-of-a-variable-2.c
Normal file
|
|
@ -0,0 +1 @@
|
|||
int& i = *(int*)0xA100;
|
||||
5
Task/Address-of-a-variable/C/address-of-a-variable-3.c
Normal file
5
Task/Address-of-a-variable/C/address-of-a-variable-3.c
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
static union
|
||||
{
|
||||
int i;
|
||||
int j;
|
||||
};
|
||||
2
Task/Address-of-a-variable/C/address-of-a-variable-4.c
Normal file
2
Task/Address-of-a-variable/C/address-of-a-variable-4.c
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
int i;
|
||||
int& j = i;
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
MODULE AddressVar;
|
||||
IMPORT SYSTEM,StdLog;
|
||||
|
||||
VAR
|
||||
x: INTEGER;
|
||||
|
||||
PROCEDURE Do*;
|
||||
BEGIN
|
||||
StdLog.String("ADR(x):> ");StdLog.IntForm(SYSTEM.ADR(x),StdLog.hexadecimal,8,'0',TRUE);StdLog.Ln
|
||||
END Do;
|
||||
|
||||
BEGIN
|
||||
x := 10;
|
||||
END AddressVar.
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import std.stdio, std.string, std.algorithm, std.range;
|
||||
import std.stdio, std.string, std.algorithm, std.range, std.typetuple;
|
||||
|
||||
void main() {
|
||||
auto data =
|
||||
|
|
@ -11,13 +11,12 @@ justified,$right$justified,$or$center$justified$within$its$column."
|
|||
.splitLines.map!q{ a.chomp("$").split("$") };
|
||||
|
||||
int[int] maxWidths;
|
||||
foreach (line; data)
|
||||
foreach (const line; data)
|
||||
foreach (i, word; line)
|
||||
maxWidths[i] = max(maxWidths.get(i, 0), word.length);
|
||||
|
||||
foreach (just; [&leftJustify!string, ¢er!string,
|
||||
&rightJustify!string])
|
||||
foreach (line; data)
|
||||
writefln("%-(%s %)", iota(line.length)
|
||||
foreach (const just; TypeTuple!(leftJustify, center, rightJustify))
|
||||
foreach (const line; data)
|
||||
writefln("%-(%s %)", line.length.iota
|
||||
.map!(i => just(line[i], maxWidths[i], ' ')));
|
||||
}
|
||||
|
|
|
|||
144
Task/Align-columns/Java/align-columns.java
Normal file
144
Task/Align-columns/Java/align-columns.java
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
/**
|
||||
* Aligns fields into columns, separated by "|"
|
||||
*/
|
||||
public class ColumnAligner {
|
||||
private List<String[]> words = new ArrayList<>();
|
||||
private int columns = 0;
|
||||
private List<Integer> columnWidths = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Initialize columns aligner from lines in a single string
|
||||
*
|
||||
* @param s
|
||||
* lines in a single string. Empty string does form a column.
|
||||
*/
|
||||
public ColumnAligner(String s) {
|
||||
String[] lines = s.split("\\n");
|
||||
for (String line : lines) {
|
||||
processInputLine(line);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize columns aligner from lines in a list of strings
|
||||
*
|
||||
* @param lines
|
||||
* lines in a single string. Empty string does form a column.
|
||||
*/
|
||||
public ColumnAligner(List<String> lines) {
|
||||
for (String line : lines) {
|
||||
processInputLine(line);
|
||||
}
|
||||
}
|
||||
|
||||
private void processInputLine(String line) {
|
||||
String[] lineWords = line.split("\\$");
|
||||
words.add(lineWords);
|
||||
columns = Math.max(columns, lineWords.length);
|
||||
for (int i = 0; i < lineWords.length; i++) {
|
||||
String word = lineWords[i];
|
||||
if (i >= columnWidths.size()) {
|
||||
columnWidths.add(word.length());
|
||||
} else {
|
||||
columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface AlignFunction {
|
||||
String align(String s, int length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Left-align all columns
|
||||
*
|
||||
* @return Lines, terminated by "\n" of columns, separated by "|"
|
||||
*/
|
||||
public String alignLeft() {
|
||||
return align(new AlignFunction() {
|
||||
@Override
|
||||
public String align(String s, int length) {
|
||||
return StringUtils.rightPad(s, length);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Right-align all columns
|
||||
*
|
||||
* @return Lines, terminated by "\n" of columns, separated by "|"
|
||||
*/
|
||||
public String alignRight() {
|
||||
return align(new AlignFunction() {
|
||||
@Override
|
||||
public String align(String s, int length) {
|
||||
return StringUtils.leftPad(s, length);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Center-align all columns
|
||||
*
|
||||
* @return Lines, terminated by "\n" of columns, separated by "|"
|
||||
*/
|
||||
public String alignCenter() {
|
||||
return align(new AlignFunction() {
|
||||
@Override
|
||||
public String align(String s, int length) {
|
||||
return StringUtils.center(s, length);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private String align(AlignFunction a) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (String[] lineWords : words) {
|
||||
for (int i = 0; i < lineWords.length; i++) {
|
||||
String word = lineWords[i];
|
||||
if (i == 0) {
|
||||
result.append("|");
|
||||
}
|
||||
result.append(a.align(word, columnWidths.get(i)) + "|");
|
||||
}
|
||||
result.append("\n");
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static void main(String args[]) throws IOException {
|
||||
if (args.length < 1) {
|
||||
System.out.println("Usage: ColumnAligner file [left|right|center]");
|
||||
return;
|
||||
}
|
||||
String filePath = args[0];
|
||||
String alignment = "left";
|
||||
if (args.length >= 2) {
|
||||
alignment = args[1];
|
||||
}
|
||||
ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));
|
||||
switch (alignment) {
|
||||
case "left":
|
||||
System.out.print(ca.alignLeft());
|
||||
break;
|
||||
case "right":
|
||||
System.out.print(ca.alignRight());
|
||||
break;
|
||||
case "center":
|
||||
System.out.print(ca.alignCenter());
|
||||
break;
|
||||
default:
|
||||
System.err.println(String.format("Error! Unknown alignment: '%s'", alignment));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +1,19 @@
|
|||
import std.stdio, std.file, std.algorithm, std.string,
|
||||
std.typecons, std.range, std.functional;
|
||||
import std.stdio, std.file, std.algorithm, std.string, std.range,
|
||||
std.functional, std.exception;
|
||||
|
||||
auto findDeranged(in string[] words) pure /*nothrow*/ {
|
||||
string[2][] findDeranged(string[] words) pure /*nothrow*/ {
|
||||
//return words.pairwise.filter!(ww=> ww[].zip.all!q{a[0] != a[1]});
|
||||
Tuple!(string, string)[] result;
|
||||
foreach (immutable i, const w1; words)
|
||||
foreach (const w2; words[i + 1 .. $])
|
||||
typeof(return) result;
|
||||
foreach (immutable i, w1; words)
|
||||
foreach (w2; words[i + 1 .. $])
|
||||
if (zip(w1, w2).all!q{ a[0] != a[1] })
|
||||
result ~= tuple(w1, w2);
|
||||
result ~= [w1, w2];
|
||||
return result;
|
||||
}
|
||||
|
||||
void main() {
|
||||
Appender!(string[])[30] wClasses;
|
||||
//foreach (word; "unixdict.txt".readText.splitter)
|
||||
foreach (word; std.algorithm.splitter("unixdict.txt".readText))
|
||||
wClasses[$ - word.length] ~= word;
|
||||
|
||||
|
|
@ -20,9 +21,9 @@ void main() {
|
|||
foreach (words; wClasses[].map!q{ a.data }.filter!(not!empty)) {
|
||||
string[][const ubyte[]] anags; // Assume ASCII input.
|
||||
foreach (w; words)
|
||||
anags[w.dup.representation.sort().release.idup] ~= w;
|
||||
auto pairs = anags.byValue.map!findDeranged.join;
|
||||
anags[w.dup.representation.sort().release.assumeUnique]~= w;
|
||||
auto pairs = anags.byValue.map!findDeranged.joiner;
|
||||
if (!pairs.empty)
|
||||
return writefln(" %s, %s", pairs.front[]);
|
||||
return writefln(" %-(%s %)", pairs.front);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
-module( deranged_anagrams ).
|
||||
-export( [task/0] ).
|
||||
-module( anagrams_deranged ).
|
||||
-export( [task/0, words_from_url/1] ).
|
||||
|
||||
task() ->
|
||||
httpc_start(),
|
||||
Words = words( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ),
|
||||
find_unimplemented_tasks:init_http(),
|
||||
Words = words_from_url( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ),
|
||||
Anagram_dict = anagrams:fetch( Words, dict:new() ),
|
||||
Deranged_anagrams = deranged_anagrams( Anagram_dict ),
|
||||
{_Length, Longest_anagrams} = dict:fold( fun keep_longest/3, {0, []}, Deranged_anagrams ),
|
||||
Longest_anagrams.
|
||||
|
||||
words_from_url( URL ) ->
|
||||
{ok, {{_HTTP, 200, "OK"}, _Headers, Body}} = httpc:request( URL ),
|
||||
string:tokens( Body, "\n" ).
|
||||
|
||||
|
||||
|
||||
deranged_anagrams( Dict ) ->
|
||||
|
|
@ -18,10 +22,6 @@ deranged_anagrams( Dict ) ->
|
|||
deranged_words( _Key, [H | T] ) ->
|
||||
[{H, X} || X <- T, is_deranged_word(H, X)].
|
||||
|
||||
httpc_start() ->
|
||||
inets:start(),
|
||||
inets:start( httpc, [] ).
|
||||
|
||||
keep_longest( _Key, [{One, _} | _]=New, {Length, Acc} ) ->
|
||||
keep_longest_new( erlang:length(One), Length, New, Acc ).
|
||||
|
||||
|
|
@ -39,7 +39,3 @@ is_deranged_word( Word1, Word2 ) ->
|
|||
lists:all( fun is_deranged_char/1, lists:zip(Word1, Word2) ).
|
||||
|
||||
is_deranged_char( {One, Two} ) -> One =/= Two.
|
||||
|
||||
words( URL ) ->
|
||||
{ok, {{_HTTP, 200, "OK"}, _Headers, Body}} = httpc:request( URL ),
|
||||
string:tokens( Body, "\n" ).
|
||||
|
|
|
|||
|
|
@ -1,46 +1,27 @@
|
|||
require 'open-uri'
|
||||
anagram = nil
|
||||
open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f|
|
||||
anagram = f.read.split.group_by {|s| s.each_char.sort}
|
||||
anagram = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f|
|
||||
f.read.split.group_by {|s| s.each_char.sort}
|
||||
end
|
||||
|
||||
def deranged?(a, b)
|
||||
a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b}
|
||||
end
|
||||
|
||||
def remove_non_derangements(val)
|
||||
list = val.dup
|
||||
for i in 0 ... list.length
|
||||
j = i + 1
|
||||
while j < list.length
|
||||
if deranged?(list[i], list[j])
|
||||
j += 1
|
||||
else
|
||||
list.delete_at(j)
|
||||
end
|
||||
def find_derangements(list)
|
||||
for i in 0 ... list.size-1
|
||||
for j in i ... list.size
|
||||
return list[i], list[j] if deranged?(list[i], list[j])
|
||||
end
|
||||
end
|
||||
list
|
||||
nil
|
||||
end
|
||||
|
||||
max_word_length = anagram.each_value .
|
||||
select {|list| list.length > 1} .
|
||||
map {|list| list[0].length} .
|
||||
max
|
||||
anagram = anagram.select{|k,list| list.size>1}.sort_by{|k,list| -k.size}
|
||||
|
||||
derangements = []
|
||||
|
||||
until derangements.length > 1
|
||||
puts "looking for deranged anagrams with word length #{max_word_length}"
|
||||
|
||||
anagram.each_value .
|
||||
select {|list| list.length > 1 and list[0].length == max_word_length} .
|
||||
each do |list|
|
||||
derangements = remove_non_derangements(list)
|
||||
break if derangements.length > 1
|
||||
end
|
||||
|
||||
max_word_length -= 1
|
||||
anagram.each do |k,list|
|
||||
derangements = find_derangements(list)
|
||||
if derangements
|
||||
puts "derangement with longest word size: #{derangements}"
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
puts "derangement with longest word length: #{derangements}"
|
||||
|
|
|
|||
175
Task/Anagrams/Component-Pascal/anagrams-1.component
Normal file
175
Task/Anagrams/Component-Pascal/anagrams-1.component
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
MODULE BbtAnagrams;
|
||||
IMPORT StdLog,Files,Strings,Args;
|
||||
CONST
|
||||
MAXPOOLSZ = 1024;
|
||||
|
||||
TYPE
|
||||
Node = POINTER TO LIMITED RECORD;
|
||||
count: INTEGER;
|
||||
word: Args.String;
|
||||
desc: Node;
|
||||
next: Node;
|
||||
END;
|
||||
|
||||
Pool = POINTER TO LIMITED RECORD
|
||||
capacity,max: INTEGER;
|
||||
words: POINTER TO ARRAY OF Node;
|
||||
END;
|
||||
|
||||
PROCEDURE NewNode(word: ARRAY OF CHAR): Node;
|
||||
VAR
|
||||
n: Node;
|
||||
BEGIN
|
||||
NEW(n);n.count := 0;n.word := word$;
|
||||
n.desc := NIL;n.next := NIL;
|
||||
RETURN n
|
||||
END NewNode;
|
||||
|
||||
PROCEDURE Index(s: ARRAY OF CHAR;cap: INTEGER): INTEGER;
|
||||
VAR
|
||||
i,sum: INTEGER;
|
||||
BEGIN
|
||||
sum := 0;
|
||||
FOR i := 0 TO LEN(s$) DO
|
||||
INC(sum,ORD(s[i]))
|
||||
END;
|
||||
RETURN sum MOD cap
|
||||
END Index;
|
||||
|
||||
PROCEDURE ISort(VAR s: ARRAY OF CHAR);
|
||||
VAR
|
||||
i, j: INTEGER;
|
||||
t: CHAR;
|
||||
BEGIN
|
||||
FOR i := 0 TO LEN(s$) - 1 DO
|
||||
j := i;
|
||||
t := s[j];
|
||||
WHILE (j > 0) & (s[j -1] > t) DO
|
||||
s[j] := s[j - 1];
|
||||
DEC(j)
|
||||
END;
|
||||
s[j] := t
|
||||
END
|
||||
END ISort;
|
||||
|
||||
PROCEDURE SameLetters(x,y: ARRAY OF CHAR): BOOLEAN;
|
||||
BEGIN
|
||||
ISort(x);ISort(y);
|
||||
RETURN x = y
|
||||
END SameLetters;
|
||||
|
||||
PROCEDURE NewPoolWith(cap: INTEGER): Pool;
|
||||
VAR
|
||||
i: INTEGER;
|
||||
p: Pool;
|
||||
BEGIN
|
||||
NEW(p);
|
||||
p.capacity := cap;
|
||||
p.max := 0;
|
||||
NEW(p.words,cap);
|
||||
i := 0;
|
||||
WHILE i < p.capacity DO
|
||||
p.words[i] := NIL;
|
||||
INC(i);
|
||||
END;
|
||||
RETURN p
|
||||
END NewPoolWith;
|
||||
|
||||
PROCEDURE NewPool(): Pool;
|
||||
BEGIN
|
||||
RETURN NewPoolWith(MAXPOOLSZ);
|
||||
END NewPool;
|
||||
|
||||
PROCEDURE (p: Pool) Add(w: ARRAY OF CHAR), NEW;
|
||||
VAR
|
||||
idx: INTEGER;
|
||||
iter,n: Node;
|
||||
BEGIN
|
||||
idx := Index(w,p.capacity);
|
||||
iter := p.words[idx];
|
||||
n := NewNode(w);
|
||||
WHILE(iter # NIL) DO
|
||||
IF SameLetters(w,iter.word) THEN
|
||||
INC(iter.count);
|
||||
IF iter.count > p.max THEN p.max := iter.count END;
|
||||
n.desc := iter.desc;
|
||||
iter.desc := n;
|
||||
RETURN
|
||||
END;
|
||||
iter := iter.next
|
||||
END;
|
||||
ASSERT(iter = NIL);
|
||||
n.next := p.words[idx];p.words[idx] := n
|
||||
END Add;
|
||||
|
||||
PROCEDURE ShowAnagrams(l: Node);
|
||||
VAR
|
||||
iter: Node;
|
||||
BEGIN
|
||||
iter := l;
|
||||
WHILE iter # NIL DO
|
||||
StdLog.String(iter.word);StdLog.String(" ");
|
||||
iter := iter.desc
|
||||
END;
|
||||
StdLog.Ln
|
||||
END ShowAnagrams;
|
||||
|
||||
PROCEDURE (p: Pool) ShowMax(),NEW;
|
||||
VAR
|
||||
i: INTEGER;
|
||||
iter: Node;
|
||||
BEGIN
|
||||
FOR i := 0 TO LEN(p.words) - 1 DO
|
||||
IF p.words[i] # NIL THEN
|
||||
iter := p.words^[i];
|
||||
WHILE iter # NIL DO
|
||||
IF iter.count = p.max THEN
|
||||
ShowAnagrams(iter);
|
||||
END;
|
||||
iter := iter.next
|
||||
END
|
||||
END
|
||||
END
|
||||
END ShowMax;
|
||||
|
||||
PROCEDURE GetLine(rd: Files.Reader; OUT str: ARRAY OF CHAR);
|
||||
VAR
|
||||
i: INTEGER;
|
||||
b: BYTE;
|
||||
BEGIN
|
||||
rd.ReadByte(b);i := 0;
|
||||
WHILE (~rd.eof) & (i < LEN(str)) DO
|
||||
IF (b = ORD(0DX)) OR (b = ORD(0AX)) THEN str[i] := 0X; RETURN END;
|
||||
str[i] := CHR(b);
|
||||
rd.ReadByte(b);INC(i)
|
||||
END;
|
||||
str[LEN(str) - 1] := 0X
|
||||
END GetLine;
|
||||
|
||||
PROCEDURE DoProcess*;
|
||||
VAR
|
||||
params : Args.Params;
|
||||
loc: Files.Locator;
|
||||
fd: Files.File;
|
||||
rd: Files.Reader;
|
||||
line: ARRAY 81 OF CHAR;
|
||||
p: Pool;
|
||||
BEGIN
|
||||
Args.Get(params);
|
||||
IF params.argc = 1 THEN
|
||||
loc := Files.dir.This("Bbt");
|
||||
fd := Files.dir.Old(loc,params.args[0]$,FALSE);
|
||||
StdLog.String("Processing: " + params.args[0]);StdLog.Ln;StdLog.Ln;
|
||||
rd := fd.NewReader(NIL);
|
||||
p := NewPool();
|
||||
REPEAT
|
||||
GetLine(rd,line);
|
||||
p.Add(line);
|
||||
UNTIL rd.eof;
|
||||
p.ShowMax()
|
||||
ELSE
|
||||
StdLog.String("Error: Missing file to process");StdLog.Ln
|
||||
END;
|
||||
END DoProcess;
|
||||
|
||||
END BbtAnagrams.
|
||||
9
Task/Anagrams/Component-Pascal/anagrams-2.component
Normal file
9
Task/Anagrams/Component-Pascal/anagrams-2.component
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import std.stdio, std.algorithm, std.range, std.string, std.exception;
|
||||
|
||||
void main() {
|
||||
string[][const ubyte[]] an;
|
||||
foreach (w; "unixdict.txt".File.byLine(KeepTerminator.no))
|
||||
an[w.dup.representation.sort().release.assumeUnique] ~= w.idup;
|
||||
immutable m = an.byValue.map!q{ a.length }.reduce!max;
|
||||
writefln("%(%s\n%)", an.byValue.filter!(ws => ws.length == m));
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue