Data update

This commit is contained in:
Ingy döt Net 2023-12-16 21:33:55 -08:00
parent 35bcdeebf8
commit 74c69a0df6
2427 changed files with 31826 additions and 3468 deletions

View file

@ -1,31 +0,0 @@
begin
comment - 100 doors problem in ALGOL-60;
boolean array doors[1:100];
integer i, j;
boolean open, closed;
open := true;
closed := not true;
outstring(1,"100 Doors Problem\n");
comment - all doors are initially closed;
for i := 1 step 1 until 100 do
doors[i] := closed;
comment
cycle through at increasing intervals
and flip each door encountered;
for i := 1 step 1 until 100 do
for j := i step i until 100 do
doors[j] := not doors[j];
comment - show which doors are open;
outstring(1,"The open doors are:");
for i := 1 step 1 until 100 do
if doors[i] then
outinteger(1,i);
end

View file

@ -1,32 +0,0 @@
begin
% -- find the first few squares via the unoptimised door flipping method %
integer doorMax;
doorMax := 100;
begin
% -- need to start a new block so the array can have variable bounds %
% -- array of doors - door( i ) is true if open, false if closed %
logical array door( 1 :: doorMax );
% -- set all doors to closed %
for i := 1 until doorMax do door( i ) := false;
% -- repeatedly flip the doors %
for i := 1 until doorMax
do begin
for j := i step i until doorMax
do begin
door( j ) := not door( j )
end
end;
% -- display the results %
i_w := 1; % -- set integer field width %
s_w := 1; % -- and separator width %
for i := 1 until doorMax do if door( i ) then writeon( i )
end
end.

View file

@ -5,27 +5,20 @@ model
int id
Door:State state
new by int =id, Door:State =state do end
fun toggle = void by block
me.state = when(me.state == Door:State.CLOSED, Door:State.OPEN, Door:State.CLOSED)
end
fun asText = text by block
return "Door #" + me.id + " is " + when(me.state == Door:State.CLOSED, "closed", "open")
end
fun toggle ← <|me.state ← when(me.state æ Door:State.CLOSED, Door:State.OPEN, Door:State.CLOSED)
fun asText ← <|"Door #" + me.id + " is " + when(me.state æ Door:State.CLOSED, "closed", "open")
end
type Main
^|There are 100 doors in a row that are all initially closed.|^
List doors = Door[].with(100)
for int i = 0; i < 100; ++i
doors[i] = Door(i + 1, Door:State.CLOSED)
end
List doors ← Door[].with(100, <int i|Door(i + 1, Door:State.CLOSED))
^|You make 100 passes by the doors.|^
for int pass = 0; pass < 100; ++pass
for int i = pass; i < 100; i += pass + 1
for int pass ← 0; pass < 100; ++pass
for int i ← pass; i < 100; i += pass + 1
doors[i].toggle()
end
end
^|Which are open, which are closed?|^
for each Door door in doors
if door.state == Door:State.CLOSED do continue end
if door.state æ Door:State.CLOSED do continue end
writeLine(door)
end

View file

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

View file

@ -4,6 +4,6 @@
var sqrt = Math.sqrt(door);
if (sqrt === (sqrt | 0)) {
console.log("Door %d is open", door);
console.log("Door " + door + " is open");
}
});

View file

@ -1,30 +1,28 @@
(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">play<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">prisoners<span style="color: #0000FF;">,</span> <span style="color: #000000;">iterations<span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">optimal<span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">drawers</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle<span style="color: #0000FF;">(<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">prisoners<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">pardoned</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">iterations</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">drawers</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle<span style="color: #0000FF;">(<span style="color: #000000;">drawers<span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">prisoner<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">prisoners</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">drawer</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff<span style="color: #0000FF;">(<span style="color: #000000;">optimal<span style="color: #0000FF;">?<span style="color: #000000;">prisoner<span style="color: #0000FF;">:<span style="color: #7060A8;">rand<span style="color: #0000FF;">(<span style="color: #000000;">prisoners<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">prisoners<span style="color: #0000FF;">/<span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">drawer</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">drawers<span style="color: #0000FF;">[<span style="color: #000000;">drawer<span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">drawer<span style="color: #0000FF;">==<span style="color: #000000;">prisoner</span> <span style="color: #008080;">then</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">optimal</span> <span style="color: #008080;">then</span> <span style="color: #000000;">drawer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand<span style="color: #0000FF;">(<span style="color: #000000;">prisoners<span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">found</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">pardoned</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">found</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">100<span style="color: #0000FF;">*<span style="color: #000000;">pardoned<span style="color: #0000FF;">/<span style="color: #000000;">iterations</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function play(integer prisoners, iterations, bool optimal)
sequence drawers = shuffle(tagset(prisoners))
integer pardoned = 0
bool found = false
for i=1 to iterations do
drawers = shuffle(drawers)
for prisoner=1 to prisoners do
found = false
integer drawer = iff(optimal?prisoner:rand(prisoners))
for j=1 to prisoners/2 do
drawer = drawers[drawer]
if drawer==prisoner then found = true exit end if
if not optimal then drawer = rand(prisoners) end if
end for
if not found then exit end if
end for
pardoned += found
end for
return 100*pardoned/iterations
end function
<span style="color: #008080;">constant</span> <span style="color: #000000;">iterations</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100<span style="color: #000000;">_000</span>
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"Simulation count: %d\n"<span style="color: #0000FF;">,<span style="color: #000000;">iterations<span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">prisoners<span style="color: #0000FF;">=<span style="color: #000000;">10</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">by</span> <span style="color: #000000;">90</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">random</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">play<span style="color: #0000FF;">(<span style="color: #000000;">prisoners<span style="color: #0000FF;">,<span style="color: #000000;">iterations<span style="color: #0000FF;">,<span style="color: #004600;">false<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
<span style="color: #000000;">optimal</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">play<span style="color: #0000FF;">(<span style="color: #000000;">prisoners<span style="color: #0000FF;">,<span style="color: #000000;">iterations<span style="color: #0000FF;">,<span style="color: #004600;">true<span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"Prisoners:%d, random:%g, optimal:%g\n"<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">prisoners<span style="color: #0000FF;">,<span style="color: #000000;">random<span style="color: #0000FF;">,<span style="color: #000000;">optimal<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for
<!--
constant iterations = 100_000
printf(1,"Simulation count: %d\n",iterations)
for prisoners in {10,100} do
atom random = play(prisoners,iterations,false),
optimal = play(prisoners,iterations,true)
printf(1,"Prisoners:%d, random:%g, optimal:%g\n",{prisoners,random,optimal})
end for

View file

@ -0,0 +1,59 @@
program prisoners;
setrandom(0);
strategies := {
["Optimal", routine optimal_strategy],
["Random", routine random_strategy]
};
runs := 10000;
loop for strategy = strategies(name) do
successes := run_simulations(strategy, runs);
print(rpad(name + ":", 10), successes * 100 / runs, "%");
end loop;
proc run_simulations(strategy, amount);
loop for i in [1..amount] do
successes +:= if simulate(strategy) then 1 else 0 end;
end loop;
return successes;
end proc;
proc simulate(strategy);
drawers := [1..100];
shuffle(drawers);
loop for prisoner in [1..100] do
if not call(strategy, drawers, prisoner) then
return false;
end if;
end loop;
return true;
end proc;
proc optimal_strategy(drawers, prisoner);
d := prisoner;
loop for s in [1..50] do
if (d := drawers(d)) = prisoner then
return true;
end if;
end loop;
return false;
end proc;
proc random_strategy(drawers, prisoner);
loop for s in [1..50] do
if drawers(1+random(#drawers-1)) = prisoner then
return true;
end if;
end loop;
return false;
end proc;
proc shuffle(rw drawers);
loop for i in [1..#drawers] do
j := i+random(#drawers-i);
[drawers(i), drawers(j)] := [drawers(j), drawers(i)];
end loop;
end proc;
end program;

View file

@ -1,5 +1,5 @@
import "random" for Random
import "/fmt" for Fmt
import "./fmt" for Fmt
var rand = Random.new()
@ -40,8 +40,8 @@ var doTrials = Fn.new{ |trials, np, strategy|
}
}
if (!nextPrisoner) {
nextTrial = true
break
nextTrial = true
break
}
}
if (!nextTrial) pardoned = pardoned + 1

View file

@ -0,0 +1,128 @@
const std = @import("std");
pub const Cupboard = struct {
comptime {
std.debug.assert(u7 == std.math.IntFittingRange(0, 100));
}
pub const Drawer = packed struct(u8) {
already_visited: bool,
card: u7,
};
drawers: [100]Drawer,
randomizer: std.rand.Random,
/// Cupboard is not shuffled after initialization,
/// it is shuffled during `play` execution.
pub fn init(random: std.rand.Random) Cupboard {
var drawers: [100]Drawer = undefined;
for (&drawers, 0..) |*drawer, i| {
drawer.* = .{
.already_visited = false,
.card = @intCast(i),
};
}
return .{
.drawers = drawers,
.randomizer = random,
};
}
pub const Decision = enum {
pardoned,
sentenced,
};
pub const Strategy = enum {
follow_card,
random,
pub fn decisionOfPrisoner(strategy: Strategy, cupboard: *Cupboard, prisoner_id: u7) Decision {
switch (strategy) {
.random => {
return for (0..50) |_| {
// If randomly chosen drawer was already opened,
// throw dice again.
const drawer = try_throw_random: while (true) {
const random_i = cupboard.randomizer.uintLessThan(u7, 100);
const drawer = &cupboard.drawers[random_i];
if (!drawer.already_visited)
break :try_throw_random drawer;
};
std.debug.assert(!drawer.already_visited);
defer drawer.already_visited = true;
if (drawer.card == prisoner_id)
break .pardoned;
} else .sentenced;
},
.follow_card => {
var drawer_i = prisoner_id;
return for (0..50) |_| {
const drawer = &cupboard.drawers[drawer_i];
std.debug.assert(!drawer.already_visited);
defer drawer.already_visited = true;
if (drawer.card == prisoner_id)
break .pardoned
else
drawer_i = drawer.card;
} else .sentenced;
},
}
}
};
pub fn play(cupboard: *Cupboard, strategy: Strategy) Decision {
cupboard.randomizer.shuffleWithIndex(Drawer, &cupboard.drawers, u7);
// Decisions for all 100 prisoners.
var all_decisions: [100]Decision = undefined;
for (&all_decisions, 0..) |*current_decision, prisoner_id| {
// Make decision for current prisoner
current_decision.* = strategy.decisionOfPrisoner(cupboard, @intCast(prisoner_id));
// Close all drawers after one step.
for (&cupboard.drawers) |*drawer|
drawer.already_visited = false;
}
// If there is at least one sentenced person, everyone are sentenced.
return for (all_decisions) |decision| {
if (decision == .sentenced)
break .sentenced;
} else .pardoned;
}
pub fn runSimulation(cupboard: *Cupboard, strategy: Cupboard.Strategy, total: u32) void {
var success: u32 = 0;
for (0..total) |_| {
const result = cupboard.play(strategy);
if (result == .pardoned) success += 1;
}
const ratio = @as(f32, @floatFromInt(success)) / @as(f32, @floatFromInt(total));
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
stdout_w.print(
\\
\\Strategy: {s}
\\Total runs: {d}
\\Successful runs: {d}
\\Failed runs: {d}
\\Success rate: {d:.4}%.
\\
, .{
@tagName(strategy),
total,
success,
total - success,
ratio * 100.0,
}) catch {}; // Do nothing on error
}
};

View file

@ -0,0 +1,15 @@
const std = @import("std");
pub fn main() std.os.GetRandomError!void {
var prnd = std.rand.DefaultPrng.init(seed: {
var init_seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&init_seed));
break :seed init_seed;
});
const random = prnd.random();
var cupboard = Cupboard.init(random);
cupboard.runSimulation(.follow_card, 10_000);
cupboard.runSimulation(.random, 10_000);
}

View file

@ -0,0 +1,89 @@
// 15 Puzzle // 26 september 2023 //
begin globals
CFMutableStringRef board : board = fn MutableStringNew
end globals
void local fn buildUI
Long i, j, k = 1 // k is button number
window 1, @"15 Puzzle", ( 0, 0, 200, 200 ), 3
for j = 3 to 0 step -1 : for i = 0 to 3 // Top to bottom, left to right
button k, Yes, 1, @"", ( 20 + 40 * i, 20 + 40 * j , 40, 40 ), , NSBezelStyleShadowlessSquare
ControlSetFont(k, fn FontSystemFontOfSize( 21 ) )
ControlSetAlignment( k, NSTextAlignmentCenter )
k ++
next : next
menu 1, , 1, @"File": menu 1, 1, , @"Close", @"w" : MenuItemSetAction( 1, 1, @"performClose:" )
editmenu 2 : menu 2, 0, No : menu 3, , , @"Level"
for i = 1 to 8 : menu 3, i, , str( i ) : next
MenuSetOneItemOnState( 3, 3 )
end fn
void local fn newGame
CFStringRef s
Long i, m, n = 16, p = 0 // n is empty starting tile, p holds previous move
Bool ok
MutableStringSetString (board, @" 123456789ABCDEF " )
for i = 1 to fn MenuSelectedItem( 3 )^2 // Number of shuffles is square of level
do : ok = Yes
m = n + int( 2.6 * rnd( 4 ) - 6.5 ) // Choose a random move, but
if m < 1 or m > 16 or m == p then ok = No // not of bounds or previous,
if n mod 4 = 0 and m = n + 1 then ok = No // and don't exchange eg tile 4 and 5
if n mod 4 = 1 and m = n - 1 then ok = No // or 9 and 8
until ok = Yes // Found a move, swap in board string
s = mid( board, m, 1 ) : mid( board, m, 1 ) = @" " : mid( board, n, 1 ) = s
p = n : n = m
next
for i = 1 to 16 // Stamp the buttons, p is unicode of board char, s is button title
p = (Long) fn StringCharacterAtIndex( board, i )
if p > 64 then s = fn StringWithFormat ( @"%d", p - 55 ) else s = mid( board, i, 1 )
button i, Yes, 1, s
if fn StringIsEqual( s, @" ") == Yes then button i, No
next
end fn
void local fn move ( n as Long )
CFStringRef s
Long i, m, x = -1 // x is empty plot
Bool ok
for i = 1 to 4 // see if clicked button is next to empty plot
m = n + int( 2.6 * i - 6.5 ) // -4. -1, +1, +4
ok = Yes
if m < 1 or m > 16 then ok = No // Not out of bounds etc
if n mod 4 = 0 and m = n + 1 then ok = No
if n mod 4 = 1 and m = n - 1 then ok = No
if ok == Yes
if fn StringIsEqual( mid( board, m, 1 ), @" " ) then x = m
end if
next
if x > -1 // Swap places in board string and button titles
s = mid( board, n, 1 ) : mid( board, n, 1 ) = @" " : mid( board, x, 1 ) = s
button x, Yes, 1 , fn ButtonTitle( n ) : button n, No, 1, @" "
end if
if fn StringIsEqual( board, @" 123456789ABCDEF " )
alert 112, , @"Well done.", @"Another game?", @"Yes;No", Yes
end if
end fn
void local fn doMenu( mnu as Long, itm as Long )
if mnu == 3 then MenuSetOneItemOnState( 3, itm ) : fn newGame
end fn
void local fn DoDialog( evt as Long, tag as Long )
select evt
case _btnClick : fn move( tag )
case _alertDidEnd : if tag == NSAlertFirstButtonReturn then fn newGame else end
end select
end fn
fn buildUI
fn newGame
on dialog fn doDialog
on menu fn doMenu
handleevents

View file

@ -0,0 +1,114 @@
isMiniMicro = version.hostName == "Mini Micro"
// These coordinates are [row,col] not [x,y]
Directions = {"up": [-1,0], "right": [0,1], "down": [1, 0], "left": [0,-1]}
TileNum = range(1, 15)
Puzzle15 = {"grid":[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],
"blankPos": [3,3]}
Puzzle15.__setTile = function(position, value)
row = position[0]; col = position[1]
self.grid[row][col] = value
end function
Puzzle15.__getTile = function(position)
row = position[0]; col = position[1]
return self.grid[row][col]
end function
Puzzle15.__getOppositeDirection = function(direction)
directions = Directions.indexes
oppix = (directions.indexOf(direction) + 2) % 4
return directions[oppix]
end function
Puzzle15.getState = function
return self.grid
end function
Puzzle15.getBlankPos = function
return self.blankPos
end function
Puzzle15.hasWon = function
count = 1
for r in range(0, 3)
for c in range(0, 3)
if self.grid[r][c] != count then return false
count += 1
end for
end for
return true
end function
Puzzle15.move = function(direction)
if not Directions.hasIndex(direction) then return false
move = Directions[direction]
curPos = self.blankPos[:]
newPos = [curPos[0] + move[0], curPos[1] + move[1]]
if (-1 < newPos[0] < 4) and (-1 < newPos[1] < 4) then
value = self.__getTile(newPos)
self.__setTile(curPos, value)
self.__setTile(newPos, 16) // 16 is the blank tile
self.blankPos = newPos
return true
else
return false
end if
end function
Puzzle15.shuffle = function(n)
lastMove = ""
directions = Directions.indexes
for i in range(1, 50)
while true
moveTo = directions[floor(rnd * 4)]
oppMove = self.__getOppositeDirection(moveTo)
if self.__getOppositeDirection(moveTo) != lastMove and self.move(moveTo) then
lastMove = moveTo
if isMiniMicro then
self.displayBoard
wait 1/33
end if
break
end if
end while
end for
end function
Puzzle15.displayBoard = function
if isMiniMicro then clear
for r in range(0, 3)
for c in range(0, 3)
grid = self.getState
if grid[r][c] == 16 then
s = " "
else
s = (" " + grid[r][c])[-3:]
end if
print s, ""
end for
print
end for
end function
Puzzle15.shuffle
while not Puzzle15.hasWon
if isMiniMicro then
clear
else
print
end if
Puzzle15.displayBoard
while true
print
move = input("Enter the direction to move the blank in (up, down, left, right): ")
move = move.lower
if Directions.hasIndex(move) and Puzzle15.move(move) then break
print "Please enter a valid move."
end while
end while
print "Congratulations! You solved the puzzle!"

View file

@ -0,0 +1,218 @@
woodSound = file.loadSound("small_wooden_bricks_movement.mp3")
puzzleTiles = function
gfx.scale = 2
woodImg = file.loadImage("/sys/pics/textures/Wood.png")
gfx.drawImage woodImg,0,0
gfx.color = color.black
gfx.drawRect 6,6, 244,244
bgBoard = new Sprite
bgBoard.image = gfx.getImage(0, 0, 256, 256)
bgBoard.scale = 1.6
bgBoard.x = (960 - 1.6 * 256) / 2 + 128 * 1.6
bgBoard.y = (640 - 1.6 * 256) / 2 + 128 * 1.6
bgBoard.tint = color.rgb(102,51,0)
sprites = [bgBoard]
gfx.clear
gfx.drawImage woodImg,0,0
positions = range(1,15)
positions.shuffle
spriteScale = 1.5
spriteSize = 64
tileXOffset = (960 - 3 * spriteSize * spriteScale) / 2
tileYOffset = (640 - 3 * spriteSize * spriteScale) / 2
for i in range(0,14)
s = str(i+1)
pos = positions[i]
x = pos % 4
y = floor(pos / 4)
xp = x * spriteSize + (spriteSize - (s.len * 14 + 2)) / 2
yp = y * spriteSize + 20
gfx.print s, xp, yp, color.black, "normal"
sprite = new Sprite
sprite.image = gfx.getImage(x * spriteSize, y * spriteSize, spriteSize, spriteSize)
sprite.scale = spriteScale
xs = i % 4; ys = 3 - floor(i / 4)
sprite.x = spriteSize * (xs) * spriteScale + tileXOffset
sprite.y = spriteSize * ys * spriteScale + tileYOffset
sprite.localBounds = new Bounds
sprite.localBounds.width = spriteSize
sprite.localBounds.height = spriteSize
// tint the blocks with different shades of brown
sat = floor(rnd * 47 - 10) * 3
sprite.tint = color.rgb(153 + sat, 102 + sat, 51 + sat)
sprites.push(sprite)
end for
return sprites
end function
moveTiles = function(sprites, instructions, t = 6, mute = false)
direction = instructions[0]
delta = Directions[direction]
if not mute and woodSound and direction then woodSound.play 0.1
for i in range(96, 1, -t)
for tile in instructions[1:]
sprites[tile].x += delta[1] * t
sprites[tile].y += -delta[0] * t
end for
wait 1/3200
end for
end function
// These coordinates are [row,col] not [x,y]
Directions = {"up": [-1,0], "right": [0,1], "down": [1, 0], "left": [0,-1]}
TileNum = range(1, 15)
Puzzle15 = {"grid":[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],
"blankPos": [3,3], "movesToShuffled": [], "movesMade": [], "moveCount": 0}
Puzzle15.__setTile = function(position, value)
row = position[0]; col = position[1]
self.grid[row][col] = value
end function
Puzzle15.__getTile = function(position)
row = position[0]; col = position[1]
return self.grid[row][col]
end function
Puzzle15.__getOppositeDirection = function(direction)
directions = Directions.indexes
oppix = (directions.indexOf(direction) + 2) % 4
return directions[oppix]
end function
Puzzle15.__getDirectionToTile = function(n)
for row in range(0, 3)
for col in range(0, 3)
if self.grid[row][col] == n then
dr = row - self.getBlankPos[0]
dc = col - self.getBlankPos[1]
return Directions.indexOf([sign(dr), sign(dc)])
end if
end for
end for
return null
end function
Puzzle15.getState = function
return self.grid
end function
Puzzle15.getBlankPos = function
return self.blankPos
end function
Puzzle15.hasWon = function
count = 1
for r in range(0, 3)
for c in range(0, 3)
if self.grid[r][c] != count then return false
count += 1
end for
end for
return true
end function
Puzzle15.move = function(direction)
if not Directions.hasIndex(direction) then return false
move = Directions[direction]
curPos = self.blankPos[:]
newPos = [curPos[0] + move[0], curPos[1] + move[1]]
if (-1 < newPos[0] < 4) and (-1 < newPos[1] < 4) then
value = self.__getTile(newPos)
self.__setTile(curPos, value)
self.__setTile(newPos, 16) // 16 is the blank tile
self.blankPos = newPos
if self.movesMade.len > 0 then
lastMove = self.movesMade[-1]
else
lastMove = ""
end if
if lastMove != "" and self.__getOppositeDirection(lastMove) == direction then
self.movesMade.pop
else
self.movesMade.push(direction)
end if
self.moveCount += 1
return value // return tile that was moved
else
return false
end if
end function
Puzzle15.moveNumber = function(n)
direction = Puzzle15.__getDirectionToTile(n)
origDir = direction
if direction == null then return 0
tiles = [self.__getOppositeDirection(direction)]
while origDir == direction
tileNum = self.move(origDir)
tiles.insert(1, tileNum)
direction = self.__getDirectionToTile(n)
end while
return tiles
end function
Puzzle15.shuffle = function(n, sprites)
lastMove = ""
directions = Directions.indexes
cnt = 0
instructions = []
while self.movesToShuffled.len < n
if self.movesToShuffled.len == 0 then
lastMove = ""
else
lastMove = self.movesToShuffled[-1]
end if
moveTo = directions[floor(rnd * 4)]
cnt += 1
oppMove = self.__getOppositeDirection(moveTo)
tileMoved = self.move(moveTo)
if oppMove != lastMove and tileMoved then
instructions.push([oppMove, tileMoved])
lastMove = moveTo
self.movesToShuffled.push(moveTo)
else if oppMove == lastMove then
self.movesToShuffled.pop
instructions.pop
end if
end while
for i in instructions
moveTiles(sprites, i, 96, true)
end for
end function
clear
display(4).sprites = puzzleTiles
gfx.clear
Puzzle15.shuffle(200, display(4).sprites)
while not Puzzle15.hasWon
if mouse.button and not wasPressed then
tile = 16
for i in range(1, 15)
sprite = display(4).sprites[i]
//print sprite.localBounds
if sprite.contains(mouse) then tile = i
end for
if tile != 16 then
instructions = Puzzle15.moveNumber(tile)
if instructions then moveTiles(display(4).sprites, instructions)
end if
end if
wasPressed = mouse.button
yield
end while
fanfare = file.loadSound("/sys/sounds/fanfare.wav")
fanfare.play 0.25
while fanfare.isPlaying
end while
key.get

View file

@ -1,33 +1,31 @@
-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">ESC<span style="color: #0000FF;">=<span style="color: #000000;">27<span style="color: #0000FF;">,</span> <span style="color: #000000;">UP<span style="color: #0000FF;">=<span style="color: #000000;">328<span style="color: #0000FF;">,</span> <span style="color: #000000;">LEFT<span style="color: #0000FF;">=<span style="color: #000000;">331<span style="color: #0000FF;">,</span> <span style="color: #000000;">RIGHT<span style="color: #0000FF;">=<span style="color: #000000;">333<span style="color: #0000FF;">,</span> <span style="color: #000000;">DOWN<span style="color: #0000FF;">=<span style="color: #000000;">336</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">board</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">15<span style="color: #0000FF;">)<span style="color: #0000FF;">&<span style="color: #000000;">0<span style="color: #0000FF;">,</span> <span style="color: #000000;">solve</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">board</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">pos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">16</span>
constant ESC=27, UP=328, LEFT=331, RIGHT=333, DOWN=336
sequence board = tagset(15)&0, solve = board
integer pos = 16
<span style="color: #008080;">procedure</span> <span style="color: #000000;">print_board<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">board<span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008080;">iff<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">pos<span style="color: #0000FF;">?<span style="color: #008000;">" "<span style="color: #0000FF;">:<span style="color: #7060A8;">sprintf<span style="color: #0000FF;">(<span style="color: #008000;">"%3d"<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">board<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">}<span style="color: #0000FF;">)<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mod<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">4<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"\n"<span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"\n"<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure print_board()
for i=1 to length(board) do
puts(1,iff(i=pos?" ":sprintf("%3d",{board[i]})))
if mod(i,4)=0 then puts(1,"\n") end if
end for
puts(1,"\n")
end procedure
<span style="color: #008080;">procedure</span> <span style="color: #000000;">move<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">d<span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">new_pos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pos<span style="color: #0000FF;">+<span style="color: #0000FF;">{<span style="color: #0000FF;">+<span style="color: #000000;">4<span style="color: #0000FF;">,<span style="color: #0000FF;">+<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #0000FF;">-<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #0000FF;">-<span style="color: #000000;">4<span style="color: #0000FF;">}<span style="color: #0000FF;">[<span style="color: #000000;">d<span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">new_pos<span style="color: #0000FF;">>=<span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">new_pos<span style="color: #0000FF;"><=<span style="color: #000000;">16</span>
<span style="color: #008080;">and</span> <span style="color: #0000FF;">(<span style="color: #7060A8;">mod<span style="color: #0000FF;">(<span style="color: #000000;">pos<span style="color: #0000FF;">,<span style="color: #000000;">4<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #7060A8;">mod<span style="color: #0000FF;">(<span style="color: #000000;">new_pos<span style="color: #0000FF;">,<span style="color: #000000;">4<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- same col, or row:</span>
<span style="color: #008080;">or</span> <span style="color: #7060A8;">floor<span style="color: #0000FF;">(<span style="color: #0000FF;">(<span style="color: #000000;">pos<span style="color: #0000FF;">-<span style="color: #000000;">1<span style="color: #0000FF;">)<span style="color: #0000FF;">/<span style="color: #000000;">4<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #7060A8;">floor<span style="color: #0000FF;">(<span style="color: #0000FF;">(<span style="color: #000000;">new_pos<span style="color: #0000FF;">-<span style="color: #000000;">1<span style="color: #0000FF;">)<span style="color: #0000FF;">/<span style="color: #000000;">4<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">{<span style="color: #000000;">board<span style="color: #0000FF;">[<span style="color: #000000;">pos<span style="color: #0000FF;">]<span style="color: #0000FF;">,<span style="color: #000000;">board<span style="color: #0000FF;">[<span style="color: #000000;">new_pos<span style="color: #0000FF;">]<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #000000;">board<span style="color: #0000FF;">[<span style="color: #000000;">new_pos<span style="color: #0000FF;">]<span style="color: #0000FF;">,<span style="color: #000000;">0<span style="color: #0000FF;">}</span>
<span style="color: #000000;">pos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">new_pos</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
procedure move(integer d)
integer new_pos = pos+{+4,+1,-1,-4}[d]
if new_pos>=1 and new_pos<=16
and (mod(pos,4)=mod(new_pos,4) -- same col, or row:
or floor((pos-1)/4)=floor((new_pos-1)/4)) then
{board[pos],board[new_pos]} = {board[new_pos],0}
pos = new_pos
end if
end procedure
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">do</span> <span style="color: #000000;">move<span style="color: #0000FF;">(<span style="color: #7060A8;">rand<span style="color: #0000FF;">(<span style="color: #000000;">4<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">print_board<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">board<span style="color: #0000FF;">=<span style="color: #000000;">solve</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find<span style="color: #0000FF;">(<span style="color: #7060A8;">wait_key<span style="color: #0000FF;">(<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">ESC<span style="color: #0000FF;">,<span style="color: #000000;">UP<span style="color: #0000FF;">,<span style="color: #000000;">LEFT<span style="color: #0000FF;">,<span style="color: #000000;">RIGHT<span style="color: #0000FF;">,<span style="color: #000000;">DOWN<span style="color: #0000FF;">}<span style="color: #0000FF;">)<span style="color: #0000FF;">-<span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c<span style="color: #0000FF;">=<span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">move<span style="color: #0000FF;">(<span style="color: #000000;">c<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"solved!\n"<span style="color: #0000FF;">)
<!--
for i=1 to 5 do move(rand(4)) end for
while 1 do
print_board()
if board=solve then exit end if
integer c = find(wait_key(),{ESC,UP,LEFT,RIGHT,DOWN})-1
if c=0 then exit end if
move(c)
end while
puts(1,"solved!\n")

View file

@ -1,7 +1,7 @@
import "random" for Random
import "/dynamic" for Enum
import "/ioutil" for Input
import "/fmt" for Fmt
import "./dynamic" for Enum
import "./ioutil" for Input
import "./fmt" for Fmt
var Move = Enum.create("Move", ["up", "down", "right", "left"])

View file

@ -1,4 +1,4 @@
import "/long" for ULong
import "./long" for ULong
var Nr = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
var Nc = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]

View file

@ -6,10 +6,10 @@ Implement a 2D sliding block puzzle game where blocks with numbers are combined
:* &nbsp; The rules are that on each turn the player must choose a direction &nbsp; (up, down, left or right).
:* &nbsp; All tiles move as far as possible in that direction, some move more than others.
:* &nbsp; Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.
:* &nbsp; A move is valid when at least one tile can be moved, &nbsp; if only by combination.
:* &nbsp; A new tile with the value of &nbsp; '''2''' &nbsp; is spawned at the end of each turn at a randomly chosen empty square &nbsp; (if there is one).
:* &nbsp; Adding a new tile on a blank space. &nbsp; Most of the time, &nbsp; a new &nbsp; '''2''' &nbsp; is to be added, &nbsp; and occasionally &nbsp; ('''10%''' of the time), &nbsp; a &nbsp; '''4'''.
:* &nbsp; To win, &nbsp; the player must create a tile with the number &nbsp; '''2048'''.
:* &nbsp; A move is valid when at least one tile can be moved, including by combination.
:* &nbsp; A new tile is spawned at the end of each turn at a randomly chosen empty square &nbsp; (if there is one).
:* &nbsp; Most of the time, a new '''2''' is to be added, but occasionally ('''10%''' of the time), a '''4'''.
:* &nbsp; To win, the player must create a tile with the number '''2048'''.
:* &nbsp; The player loses if no valid moves are possible.
@ -17,7 +17,7 @@ The name comes from the popular open-source implementation of this game mechanic
;Requirements:
* &nbsp; "Non-greedy" movement. &nbsp; <br>&nbsp; The tiles that were created by combining other tiles should not be combined again during the same turn (move). &nbsp; <br>&nbsp; That is to say, &nbsp; that moving the tile row of:
* &nbsp; "Non-greedy" movement.<br>&nbsp; The tiles that were created by combining other tiles should not be combined again during the same turn (move).<br>&nbsp; That is to say, that moving the tile row of:
<big><big> [2][2][2][2] </big></big>
@ -29,7 +29,7 @@ The name comes from the popular open-source implementation of this game mechanic
<big><big> .........[8] </big></big>
* &nbsp; "Move direction priority". &nbsp; <br>&nbsp; If more than one variant of combining is possible, &nbsp; move direction shall indicate which combination will take effect. <br>&nbsp; For example, moving the tile row of:
* &nbsp; "Move direction priority".<br>&nbsp; If more than one variant of combining is possible, move direction shall indicate which combination will take effect. <br>&nbsp; For example, moving the tile row of:
<big><big> ...[2][2][2] </big></big>
@ -43,8 +43,8 @@ The name comes from the popular open-source implementation of this game mechanic
* &nbsp; Check for valid moves. &nbsp; The player shouldn't be able to skip their turn by trying a move that doesn't change the board.
* &nbsp; Check for a &nbsp;win condition.
* &nbsp; Check for valid moves. The player shouldn't be able to gain new tile by trying a move that doesn't change the board.
* &nbsp; Check for a win condition.
* &nbsp; Check for a lose condition.
<br><br>

View file

@ -0,0 +1,161 @@
begin enum 123
_lf
_rt
_dn
_up
_new
_end
end enum
str63 bd
colorref color(11)
byte zs
void local fn initialize
subclass window 1, @"2048",(0,0,438,438)
fn WindowSetBackgroundColor( 1, fn ColorBlack )
color(0) = fn ColorDarkGray
color(1) = fn ColorGray
color(2) = fn ColorLightGray
color(3) = fn ColorBlue
color(4) = fn ColorBrown
color(5) = fn ColorCyan
color(6) = fn ColorGreen
color(7) = fn ColorMagenta
color(8) = fn ColorOrange
color(9) = fn ColorPurple
color(10) = fn ColorYellow
color(11) = fn ColorRed
end fn
void local fn drawBoard
int x, y,r = 1, add
cls
for y = 320 to 20 step -100
for x = 20 to 320 step 100
rect fill (x,y,98,98),color( bd[r] )
select bd[r]
case < 4 : add = 40
case < 7 : add = 30
case < 10 : add = 20
case else : add = 6
end select
if bd[r] then print %(x+add, y+25)2^bd[r]
r++
next
next
end fn
local fn finish( won as bool )
CFStringRef s = @"GAME OVER"
CGRect r = fn windowContentRect( 1 )
r.origin.y += r.size.height - 20
r.size.height = 100
window 2,,r,NSwindowStyleMaskBorderless
if won
fn windowSetBackgroundColor( 2, color(11) )
s = @"CONGRATULATIONS—YOU DID IT!!"
text,24,fn ColorBlack,,NSTextAlignmentCenter
else
fn windowSetBackgroundColor( 2, fn ColorBlack )
text,24,fn ColorWhite,,NSTextAlignmentCenter
end if
print s
button _new,,,@"New Game", (229,20,100,32)
button _end,,,@"Quit", (109,20,100,32)
end fn
void local fn newGame
int r
text @"Arial bold", 36, fn ColorBlack, fn ColorClear
bd = chr$(0)
for r = 1 to 4
bd += bd
next
bd[rnd(16)] ++
do
r = rnd(16)
until bd[r] == 0
bd[r]++
zs = 14
fn drawBoard
end fn
local fn play( st as short, rd as short, cd as short )
short a, b, c, t, moved = 0
for a = st to st + rd * 3 step rd
// SHIFT
t = a
for b = a to a + cd * 3 step cd
if bd[b]
if t <> b then swap bd[t], bd[b] : moved ++
t += cd
end if
next
// MERGE
for b = a to a + cd * 2 step cd
if bd[b] > 0 && bd[b] == bd[b+cd]
bd[b]++ : c = b + cd
// FILL IN
while c <> a+cd*3
bd[c] = bd[c+cd] : c += cd
wend
bd[c] = 0
// CHECK FOR WIN
if bd[b] == 11 then fn drawBoard : fn finish( yes ) : exit fn
zs ++ : moved ++
end if
next
next
fn drawBoard
if moved == 0 then exit fn
// GROW
b = 0 : c = rnd(zs)
while c
b ++
if bd[b] == 0 then c--
wend
if rnd(10) - 1 then bd[b]++ else bd[b] = 2
zs--
timerbegin 0.25
fn drawBoard
timerend
if zs then exit fn
// IS GAME OVER?
for a = 1 to 12
if bd[a] == bd[a+4] then exit fn
next
for a = 1 to 13 step 4
if bd[a] == bd[a+1] || bd[a+1] == bd[a+2] || bd[a+2] == bd[a+3]¬
then exit fn
next
fn finish( no )
end fn
local fn doDialog(ev as long,tag as long, wnd as long)
select ev
case _windowKeyDown : if window() == 2 then exit fn
select fn EventKeyCode
case _up : fn play(13, 1, -4)
case _dn : fn play( 1, 1, 4)
case _lf : fn play( 1, 4, 1)
case _rt : fn play( 4, 4, -1)
case else : exit fn
end select
DialogEventSetBool(yes)
case _btnClick : window close 2
if tag == _end then end
fn newGame
case _windowWillClose : if wnd == 1 then end
end select
end fn
fn initialize
fn newGame
on dialog fn doDialog
handleevents

View file

@ -1,8 +1,8 @@
import "/dynamic" for Enum, Struct
import "./dynamic" for Enum, Struct
import "random" for Random
import "/ioutil" for Input
import "/fmt" for Fmt
import "/str" for Str
import "./ioutil" for Input
import "./fmt" for Fmt
import "./str" for Str
var MoveDirection = Enum.create("MoveDirection", ["up", "down", "left", "right"])

View file

@ -0,0 +1,31 @@
PLAYER = 1
COMP = 0
sum = 0
total = 0
turn = int(rand + 0.5)
dim precomp = {1, 1, 3, 2}
while sum < 21
turn = 1 - turn
print "The sum is "; sum
if turn = PLAYER then
print "It is your turn."
while total < 1 or total > 3 or total + sum > 21
input "How many would you like to total? ", total
end while
else
print "It is the computer's turn."
total = precomp[sum mod 4]
print "The computer totals ", total, "."
end if
print
sum += total
total = 0
end while
if turn = PLAYER then
print "Congratulations. You win."
else
print "Bad luck. The computer wins."
end if

View file

@ -0,0 +1,133 @@
100 rem 21 game
110 rem for rosetta code
120 '
130 rem initialization
140 l$ = chr$(157) : rem left cursor
150 dim p$(2),hc(2),ca(4) : hc(1) = 0 : hc(2) = 0 : rem players
160 ca(0) = 1 : ca(1) = 1 : ca(2) = 3 : ca(3) = 2 : rem computer answers
170 dim cn$(6) : for i = 1 to 6 : read cn$(i) : next i : rem computer names
180 def fnm(X)=(X-(INT(X/4))*4):REM modulo function
190 '
200 rem optionally set screen colors here
210 cls
220 print " 21 GAME"
230 print : print " The goal of this game is to take turns"
240 print " adding the value of either 1, 2, or 3"
250 print " to a running total. The first player"
260 print " to bring the total to 21..."
270 print : print " ... WINS THE GAME!"
280 print : gosub 1110
290 for p = 1 to 2
300 '
310 rem game setup and get players
320 for p = 1 to 2
330 print : print "Player ";p;l$;", [H]uman or [C]omputer? ";
340 k$ = inkey$ : if k$ <> "c" and k$ <> "h" then 340
350 print k$ : hc(p) = (k$ = "c")
360 print : print "Player";p;l$ "," : print "Enter your name"; : if hc(p) then goto 400
370 input p$(p)
380 next p
390 goto 420
400 gosub 1340 : print "? ";p$(p)
410 next p
420 print
430 for p = 1 to 2 : print p;l$;". ";p$(p) : next p
440 print : print "Is this correct (y/n)? ";
450 k$ = inkey$ : if k$ <> "y" and k$ <> "n" then 450
460 print k$ : if k$ = "n" then goto 290
470 print : print "Who will play first (1 or 2)? ";
480 k$ = inkey$ : if k$ < "1" or k$ > "2" then 480
490 fp = asc(k$)-48 : print k$ : print
500 print "Okay, ";p$(fp);" will play first." : print : gosub 1110
510 cls
520 '
530 rem start main game loop
540 pi = fp : rt = 0
550 print "Total so far:";rt
560 print : print p$(pi);"'s turn."
570 if hc(pi) then gosub 1240
580 if not hc(pi) then gosub 1170
590 rt = rt+ad
600 if rt = 21 then goto 680
610 if rt > 21 then print : print p$(pi);" loses by going over 21!!" : goto 700
620 pi = pi+1 : if pi > 2 then pi = 1
630 goto 550
640 print : print " ... WINS THE GAME!"
650 print : gosub 1110
660 '
670 for p = 1 to 2
680 rem winner winner chicken dinner
690 print : print "21! ";p$(pi);" wins the game!!!"
700 print : print "Would you like to play again? ";
710 k$ = inkey$ : if k$ <> "n" and k$ <> "y" then 710
720 print k$
730 if k$ = "n" then print : print "Okay, maybe another time. Bye!" : end
740 goto 200
750 print k$ : hc(p) = (k$ = "c")
760 print : print "Player";p;l$ "," : print "Enter your name"; : if hc(p) then goto 800
770 input p$(p)
780 next p
790 goto 820
800 gosub 1340 : print "? ";p$(p)
810 next p
820 print : for p = 1 to 2 : print p;l$;". ";p$(p) : next p
830 print : print "Is this correct (y/n)? ";
840 k$ = inkey$ : if k$ <> "y" and k$ <> "n" then 840
850 print k$ : if k$ = "n" then goto 660
860 print : print "Who will play first (1 or 2)? ";
870 k$ = inkey$ : if k$ < "1" or k$ > "2" then 870
880 fp = asc(k$)-48 : print k$ : print
890 print "Okay, ";p$(fp);" will play first." : print : gosub 1110
900 '
910 rem start main game loop
920 pi = fp : rt = 0
930 print chr$(147);"Total so far: ";rt
940 print : print p$(pi);"'s turn."
950 if hc(pi) then gosub 1240
960 if not hc(pi) then gosub 1170
970 rt = rt+ad
980 if rt = 21 then goto 1030
990 if rt > 21 then print : print p$(pi);" loses by going over 21!!" : goto 1050
1000 pi = pi+1 : if pi > 2 then pi = 1
1010 goto 930
1020 '
1030 rem winner winner chicken dinner
1040 print : print "21! ";p$(pi);" wins the game!!!"
1050 print : print "Would you like to play again? ";
1060 k$ = inkey$ : if k$ <> "n" and k$ <> "y" then 1060
1070 print k$
1080 if k$ = "n" then print : print "Okay, maybe another time. Bye!" : end
1090 goto 490
1100 '
1110 rem pause for keypress
1120 z$ = " Press a key to continue. "
1130 print z$
1140 k$ = inkey$ : if k$ = "" then 1140
1150 return
1160 '
1170 rem human player move
1180 print : print "How much to add,"
1190 print "1, 2, or 3 (0 to quit)"; : input ad
1200 if ad < 0 or ad > 3 then print : print "Illegal amount. Try again." : goto 1180
1210 if ad = 0 then print : print "Game was ended by ";p$(pi);"." : end
1220 return
1230 '
1240 rem computer player move
1250 print : print "Thinking...";
1260 tt = int(rnd(1)*10)
1270 for t = 1 to tt : print "."; : for i = 1 to 250 : next i : next t : print
1280 rm = fn m(rt)
1290 ad = ca(rm)
1300 print : print p$(pi);" adds ";ca(rm);l$;"."
1310 for t = 1 to 1000 : next t
1320 return
1330 '
1340 rem pick a computer name
1350 pn = int(rnd(1)*6)+1 : t$ = cn$(pn)
1360 if t$ = p$(p-1) then goto 1350
1370 p$(p) = t$
1380 return
1390 '
1400 rem some computer names to pick from
1410 data "Commodore 64","VIC-20","Commodore 128"
1420 data "PET","Plus/4","Commodore 16"

View file

@ -0,0 +1,40 @@
If OpenConsole()
PLAYER.i = 1
COMP.i = 0
sum.i = 0
total.i = 0
turn.i = Random(1) + 0.5
Dim precomp.i(3)
precomp(0) = 1
precomp(1) = 1
precomp(2) = 3
precomp(3) = 2
While sum < 21
turn = 1 - turn
PrintN("The sum is " + Str(sum))
If turn = PLAYER
PrintN("It is your turn.")
While total < 1 Or total > 3 Or total + sum > 21
Print("How many would you like to total? ")
total = Val(Input())
Wend
Else
PrintN("It is the computer's turn.")
total = precomp(sum % 4)
PrintN("The computer totals " + Str(total) + ".")
EndIf
PrintN("")
sum + total
total = 0
Wend
If turn = PLAYER
PrintN("Congratulations. You win.")
Else
PrintN("Bad luck. The computer wins.")
EndIf
Input()
EndIf

View file

@ -0,0 +1,34 @@
PLAYER = 1
COMP = 0
RANDOMIZE TIMER
sum = 0
total = 0
turn = INT(RND + 0.5)
DIM precomp(0 TO 3)
precomp(0) = 1 : precomp(1) = 1
precomp(2) = 3 : precomp(3) = 2
WHILE sum < 21
turn = 1 - turn
PRINT "The sum is "; sum
IF turn = PLAYER THEN
PRINT "It is your turn."
WHILE total < 1 OR total > 3 OR total + sum > 21
INPUT "How many would you like to total? ", total
WEND
ELSE
PRINT "It is the computer's turn."
total = precomp(sum MOD 4)
PRINT "The computer totals"; total; "."
END IF
PRINT
sum = sum + total
total = 0
WEND
IF turn = PLAYER THEN
PRINT "Congratulations. You win."
ELSE
PRINT "Bad luck. The computer wins."
END IF

View file

@ -0,0 +1,30 @@
LET player = 1
LET comp = 0
RANDOMIZE
LET sum = 0
LET total = 0
LET turn = INT(RND+0.5)
DIM precomp(0 TO 3)
LET precomp(0) = 1
LET precomp(1) = 1
LET precomp(2) = 3
LET precomp(3) = 2
DO WHILE sum < 21
LET turn = 1-turn
PRINT "The sum is "; sum
IF turn = player THEN
PRINT "It is your turn."
DO WHILE total < 1 OR total > 3 OR total+sum > 21
INPUT prompt "How many would you like to total? ": total
LOOP
ELSE
PRINT "It is the computer's turn."
LET total = precomp(remainder(round(sum),4))
PRINT USING "The computer totals #.": total
END IF
PRINT
LET sum = sum+total
LET total = 0
LOOP
IF turn = player THEN PRINT "Congratulations. You win." ELSE PRINT "Bad luck. The computer wins."
END

View file

@ -1,5 +1,5 @@
import "/fmt" for Conv
import "/ioutil" for Input
import "./fmt" for Conv
import "./ioutil" for Input
import "random" for Random
var total = 0

View file

@ -0,0 +1,33 @@
PLAYER = 1
COMP = 0
sum = 0
total = 0
turn = int(ran() + 0.5)
dim precomp(3)
precomp(0) = 1 : precomp(1) = 1
precomp(2) = 3 : precomp(3) = 2
while sum < 21
turn = 1 - turn
print "The sum is ", sum
if turn = PLAYER then
print "It is your turn."
while total < 1 or total > 3 or total + sum > 21
input "How many would you like to total? " total
wend
else
print "It is the computer's turn."
total = precomp(mod(sum, 4))
print "The computer totals ", total, "."
fi
print
sum = sum + total
total = 0
wend
if turn = PLAYER then
print "Congratulations. You win."
else
print "Bad luck. The computer wins."
fi

View file

@ -1,5 +1,5 @@
import "random" for Random
import "/dynamic" for Tuple, Enum, Struct
import "./dynamic" for Tuple, Enum, Struct
var N_CARDS = 4
var SOLVE_GOAL = 24

View file

@ -13,7 +13,7 @@ class ExpressionTree
{
auto level := new Integer(0);
s.forEach:(ch)
s.forEach::(ch)
{
var node := new DynamicStruct();
@ -22,9 +22,9 @@ class ExpressionTree
$45 { node.Level := level + 1; node.Operation := mssg subtract } // -
$42 { node.Level := level + 2; node.Operation := mssg multiply } // *
$47 { node.Level := level + 2; node.Operation := mssg divide } // /
$40 { level.append(10); ^ self } // (
$41 { level.reduce(10); ^ self } // )
: {
$40 { level.append(10); ^ self } // (
$41 { level.reduce(10); ^ self } // )
! {
node.Leaf := ch.toString().toReal();
node.Level := level + 3
};
@ -112,34 +112,34 @@ class TwentyFourGame
{
theNumbers := new object[]
{
1 + randomGenerator.nextInt:9,
1 + randomGenerator.nextInt:9,
1 + randomGenerator.nextInt:9,
1 + randomGenerator.nextInt:9
1 + randomGenerator.nextInt(9),
1 + randomGenerator.nextInt(9),
1 + randomGenerator.nextInt(9),
1 + randomGenerator.nextInt(9)
}
}
help()
{
console
.printLine:"------------------------------- Instructions ------------------------------"
.printLine:"Four digits will be displayed."
.printLine:"Enter an equation using all of those four digits that evaluates to 24"
.printLine:"Only * / + - operators and () are allowed"
.printLine:"Digits can only be used once, but in any order you need."
.printLine:"Digits cannot be combined - i.e.: 12 + 12 when given 1,2,2,1 is not allowed"
.printLine:"Submit a blank line to skip the current puzzle."
.printLine:"Type 'q' to quit"
.printLine("------------------------------- Instructions ------------------------------")
.printLine("Four digits will be displayed.")
.printLine("Enter an equation using all of those four digits that evaluates to 24")
.printLine("Only * / + - operators and () are allowed")
.printLine("Digits can only be used once, but in any order you need.")
.printLine("Digits cannot be combined - i.e.: 12 + 12 when given 1,2,2,1 is not allowed")
.printLine("Submit a blank line to skip the current puzzle.")
.printLine("Type 'q' to quit")
.writeLine()
.printLine:"Example: given 2 3 8 2, answer should resemble 8*3-(2-2)"
.printLine:"------------------------------- --------------------------------------------"
.printLine("Example: given 2 3 8 2, answer should resemble 8*3-(2-2)")
.printLine("------------------------------- --------------------------------------------")
}
prompt()
{
theNumbers.forEach:(n){ console.print(n," ") };
theNumbers.forEach::(n){ console.print(n," ") };
console.print:": "
console.print(": ")
}
resolve(expr)
@ -147,13 +147,10 @@ class TwentyFourGame
var tree := new ExpressionTree(expr);
var leaves := new ArrayList();
tree.readLeaves:leaves;
tree.readLeaves(leaves);
ifnot (leaves.ascendant().sequenceEqual(theNumbers.ascendant())) {
console
.printLine:"Invalid input. Enter an equation using all of those four digits. Try again.";
^ self
};
ifnot (leaves.ascendant().sequenceEqual(theNumbers.ascendant()))
{ console.printLine("Invalid input. Enter an equation using all of those four digits. Try again."); ^ self };
var result := tree.Value;
if (result == 24)
@ -181,7 +178,7 @@ extension gameOp
{
if (expr == "")
{
console.printLine:"Skipping this puzzle"; self.newPuzzle()
console.printLine("Skipping this puzzle"); self.newPuzzle()
}
else
{
@ -191,7 +188,7 @@ extension gameOp
}
catch(Exception e)
{
console.printLine:e
console.printLine(e)
//console.printLine:"An error occurred. Check your input and try again."
}
};

View file

@ -1,6 +1,6 @@
import "random" for Random
import "/ioutil" for Input
import "/seq" for Stack
import "./ioutil" for Input
import "./seq" for Stack
var R = Random.new()

View file

@ -0,0 +1,71 @@
combinations = function(elements, comboLength, unique=true)
n = elements.len
if comboLength > n then return []
allCombos = []
genCombos=function(start, currCombo)
if currCombo.len == comboLength then
allCombos.push(currCombo)
return
end if
if start == n then return
for i in range(start, n - 1)
newCombo = currCombo + [elements[i]]
genCombos(i + unique, newCombo)
end for
end function
genCombos(0, [])
return allCombos
end function
permutations = function(elements, permLength=null)
n = elements.len
elements.sort
if permLength == null then permLength = n
allPerms = []
genPerms = function(prefix, remainingElements)
if prefix.len == permLength then
allPerms.push(prefix)
return
end if
for i in range(0, remainingElements.len - 1)
if i > 0 and remainingElements[i] == remainingElements[i-1] then continue
newPrefix = prefix + [remainingElements[i]]
newRemains = remainingElements[:i] + remainingElements[i+1:]
genPerms(newPrefix, newRemains)
end for
end function
genPerms([],elements)
return allPerms
end function
ringsEqual = function(a)
if a.len != 7 then return false
return a[0]+a[1] == a[1]+a[2]+a[3] == a[3]+a[4]+a[5] == a[5] + a[6]
end function
fourRings = function(lo, hi, unique, show)
rng = range(lo, hi)
combos = combinations(rng, 7, unique)
cnt = 0
for c in combos
for p in permutations(c)
if ringsEqual(p) then
cnt += 1
if show then print p.join(", ")
end if
end for
end for
uniStr = [" nonunique", " unique"]
print cnt + uniStr[unique] + " solutions for " + lo + " to " + hi
print
end function
fourRings(1, 7, true, true)
fourRings(3, 9, true, true)
fourRings(0, 9, false, false)

View file

@ -1,4 +1,4 @@
import "/fmt" for Fmt
import "./fmt" for Fmt
var a = 0
var b = 0

View file

@ -1,5 +1,5 @@
import "/big" for BigInt
import "/fmt" for Fmt
import "./big" for BigInt
import "./fmt" for Fmt
var cache = [[BigInt.one]]
var cumu = Fn.new { |n|

View file

@ -8,7 +8,7 @@ extension bottleOp
bottleDescription()
= self.toPrintable() + (self != 1).iif(" bottles"," bottle");
bottleEnumerator() = new Variable(self).doWith:(n)
bottleEnumerator() = new Variable(self).doWith::(n)
{
^ new Enumerator
{
@ -18,7 +18,7 @@ extension bottleOp
.printLine(n.bottleDescription()," of beer on the wall")
.printLine(n.bottleDescription()," of beer")
.printLine("Take one down, pass it around")
.printLine((n.reduce:1).bottleDescription()," of beer on the wall");
.printLine((n.reduce(1)).bottleDescription()," of beer on the wall");
reset() {}
@ -31,5 +31,5 @@ public program()
{
var bottles := 99;
bottles.bottleEnumerator().forEach:printingLn
bottles.bottleEnumerator().forEach(printingLn)
}

View file

@ -1,6 +1,6 @@
for (i in 99...0) {
System.print("%(i) bottles of beer on the wall,")
System.print("%(i) bottles of beer,")
System.print("Take one down, pass it around,")
System.print("%(i - 1) bottles of beer on the wall.\n")
System.print("%(i) bottles of beer on the wall,")
System.print("%(i) bottles of beer,")
System.print("Take one down, pass it around,")
System.print("%(i - 1) bottles of beer on the wall.\n")
}

View file

@ -1,14 +1,14 @@
#!/usr/bin/env yamlscript
#!/usr/bin/env ys-0
# Print the verses to "99 Bottles of Beer"
#
# usage:
# yamlscript 99-bottles.ys [<count>]
# ys 99-bottles.ys [<count>]
defn main(number=99):
map(say):
map(paragraph):
(number .. 1)
defn main(&[number]):
each [n ((number || 99) .. 1)]:
say:
paragraph: n
defn paragraph(num): |
$(bottles num) of beer on the wall,
@ -17,7 +17,7 @@ defn paragraph(num): |
$(bottles (num - 1)) of beer on the wall.
defn bottles(n):
???:
(n == 0) : "No more bottles"
(n == 1) : "1 bottle"
:else : "$n bottles"
cond:
(n == 0) "No more bottles"
(n == 1) "1 bottle"
:else str(n " bottles")

1
Task/A+B/Nu/a+b.nu Normal file
View file

@ -0,0 +1 @@
input | parse "{a} {b}" | first | values | into int | math sum

View file

@ -1 +1 @@
say read(String).words»to_i»()«+»
say read(String).words»to_i()»«+»

View file

@ -1,18 +0,0 @@
REM Rosetta Code problem: https://rosettacode.org/wiki/A+B
REM by Jjuanhdez, 06/2022
10 LET C = 0
LET D = 0
PRINT "Enter an integer: "
INPUT A
IF A < 0 THEN LET C = A * -1
PRINT "Enter other integer: "
INPUT B
IF B < 0 THEN LET D = B * -1
IF C > 1000 THEN GOTO 60
IF D > 1000 THEN GOTO 60
50 PRINT "Their sum is ", A + B
GOTO 70
60 PRINT "Both integers must be in the range [-1000..1000] - try again."
GOTO 10
70 END

View file

@ -0,0 +1,13 @@
// Input two values on single line in text format
Get_Input(10, "Enter two integers separated by a space: ")
// Extract two numeric values from the text
Buf_Switch(Buf_Free)
Reg_Ins(10)
BOF
#1 = Num_Eval(ADVANCE)
#2 = Num_Eval()
Buf_Quit(OK)
// Calculate and display the results
Num_Type(#1 + #2)

View file

@ -0,0 +1,3 @@
#1 = Get_Num("Enter number A: ")
#2 = Get_Num("Enter number B: ")
Num_Type(#1 + #2)

21
Task/A+B/XBasic/a+b.basic Normal file
View file

@ -0,0 +1,21 @@
PROGRAM "A+B"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
a$ = INLINE$("Enter integer A: ")
a = SLONG(a$)
b$ = INLINE$("Enter integer B: ")
b = SLONG(b$)
DO WHILE 1
IF ABS(a) > 1000 OR ABS(b) > 1000 THEN
PRINT "Both integers must be in the interval [-1000..1000] - try again."
PRINT
ELSE
PRINT "Their sum is"; a + b
EXIT DO
END IF
LOOP
END FUNCTION
END PROGRAM

View file

@ -10,7 +10,7 @@ extension op
{
var list := ArrayList.load(blocks);
^ nil == (cast string(self)).toUpper().seekEach:(ch)
^ nil == (cast string(self)).toUpper().seekEach::(ch)
{
var index := list.indexOfElement
((word => word.indexOf(0, ch) != -1).asComparator());
@ -39,7 +39,7 @@ public program()
Enumerator e := words.enumerator();
e.next();
words.forEach:(word)
words.forEach::(word)
{
console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks));
}

View file

@ -1,4 +1,4 @@
import "/fmt" for Fmt
import "./fmt" for Fmt
var r // recursive
r = Fn.new { |word, bl|
@ -25,5 +25,5 @@ var newSpeller = Fn.new { |blocks|
var sp = newSpeller.call("BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")
for (word in ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]) {
System.print("%(Fmt.s(-7, word)) %(sp.call(word))")
Fmt.print("$-7s $s", word, sp.call(word))
}

View file

@ -0,0 +1,133 @@
#include <algorithm>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <vector>
const std::string ADFGVX = "ADFGVX";
const std::string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
std::random_device random;
std::mt19937 mersenne_twister(random());
std::vector<std::vector<char>> initialise_polybius_square() {
std::vector<char> letters(ALPHABET.begin(), ALPHABET.end());
std::shuffle(letters.begin(), letters.end(), mersenne_twister);
std::vector<std::vector<char>> result = { 6, std::vector<char>(6, 0) };
for ( int32_t row = 0; row < 6; ++row ) {
for ( int32_t column = 0; column < 6; ++column ) {
result[row][column] = letters[6 * row + column];
}
}
return result;
}
// Create a key using a word from the dictionary 'unixdict.txt'
std::string create_key(const uint64_t& size) {
if ( size < 7 || size > 12 ) {
throw std::invalid_argument("Key should contain between 7 and 12 letters, both inclusive.");
}
std::vector<std::string> candidates;
std::fstream file_stream;
file_stream.open("../unixdict.txt");
std::string word;
while ( file_stream >> word ) {
if ( word.length() == size &&
word.length() == std::unordered_set<char>{ word.begin(), word.end() }.size() ) {
std::transform(word.begin(), word.end(), word.begin(), [](const char& ch){ return std::toupper(ch); });
if ( word.find_first_not_of(ALPHABET) == std::string::npos ) {
candidates.emplace_back(word);
}
}
}
std::shuffle(candidates.begin(), candidates.end(), mersenne_twister);
std::string key = candidates[0];
return key;
}
std::string encrypt(const std::string& plain_text,
const std::vector<std::vector<char>>& polybius,
const std::string& key) {
std::string code = "";
for ( const char& ch : plain_text ) {
for ( int32_t row = 0; row < 6; ++row ) {
for ( int32_t column = 0; column < 6; ++column ) {
if ( polybius[row][column] == ch ) {
code += ADFGVX[row];
code += ADFGVX[column];
}
}
}
}
std::string encrypted = "";
for ( const char& ch : key ) {
for ( uint64_t i = key.find(ch); i < code.length(); i += key.length() ) {
encrypted += code[i];
}
encrypted += " ";
}
return encrypted;
}
std::string decrypt(const std::string& encrypted_text,
const std::vector<std::vector<char>>& polybius,
const std::string& key) {
const uint64_t space_count = std::count(encrypted_text.begin(), encrypted_text.end(), ' ');
const uint64_t code_size = encrypted_text.length() - space_count;
std::vector<std::string> blocks;
std::stringstream stream(encrypted_text);
std:: string word;
while ( stream >> word ) {
blocks.emplace_back(word);
}
std::string code = "";
for ( int32_t i = 0; code.length() < code_size; ++i ) {
for ( const std::string& block : blocks ) {
if ( code.length() < code_size ) {
code += block[i];
}
}
}
std::string plain_text = "";
for ( uint64_t i = 0; i < code_size - 1; i += 2 ) {
int32_t row = ADFGVX.find(code[i]);
int32_t column = ADFGVX.find(code[i + 1]);
plain_text += polybius[row][column];
}
return plain_text;
}
int main() {
const std::vector<std::vector<char>> polybius = initialise_polybius_square();
std::cout << "The 6 x 6 Polybius square:" << std::endl;
std::cout << " | A D F G V X" << std::endl;
std::cout << "--------------" << std::endl;
for ( int32_t row = 0; row < 6; ++row ) {
std::cout << ADFGVX[row] << "|";
for ( int32_t column = 0; column < 6; ++column ) {
std::cout << " " << polybius[row][column];
}
std::cout << std::endl;
}
std::cout << std::endl;
const std::string key = create_key(9);
std::cout << "The key is " << key << std::endl << std::endl;
const std::string plain_text = "ATTACKAT1200AM";
std::cout << "Plain text: " << plain_text <<std::endl << std::endl;
const std::string encrypted_text = encrypt(plain_text, polybius, key);
std::cout << "Encrypted: " << encrypted_text << std::endl << std::endl;
const std::string decrypted_text = decrypt(encrypted_text, polybius, key);
std::cout << "Decrypted: " << decrypted_text << std::endl;
}

View file

@ -0,0 +1,110 @@
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public final class ADFGVXCipher {
public static void main(String[] args) throws IOException {
final char[][] polybius = initialisePolybiusSquare();
System.out.println("The 6 x 6 Polybius square:");
System.out.println(" | A D F G V X");
System.out.println("--------------");
for ( int row = 0; row < 6; row++ ) {
System.out.print(ADFGVX.charAt(row) + "|");
for ( int column = 0; column < 6; column++ ) {
System.out.print(" " + polybius[row][column]);
}
System.out.println();
}
System.out.println();
final String key = createKey(9);
System.out.println("The key is " + key);
System.out.println();
final String plainText = "ATTACKAT1200AM";
System.out.println("Plain text: " + plainText);
System.out.println();
final String encryptedText = encrypt(plainText, polybius, key);
System.out.println("Encrypted: " + encryptedText);
System.out.println();
final String decryptedText = decrypt(encryptedText, polybius, key);
System.out.println("Decrypted: " + decryptedText);
}
private static String encrypt(String plainText, char[][] polybius, String key) {
String code = "";
for ( char ch : plainText.toCharArray() ) {
for ( int row = 0; row < 6; row++ ) {
for ( int column = 0; column < 6; column++ ) {
if ( polybius[row][column] == ch ) {
code += ADFGVX.charAt(row) + "" + ADFGVX.charAt(column);
}
}
}
}
String encrypted = "";
for ( char ch : key.toCharArray() ) {
for ( int i = key.indexOf(ch); i < code.length(); i += key.length() ) {
encrypted += code.charAt(i);
}
encrypted += " ";
}
return encrypted;
}
private static String decrypt(String encryptedText, char[][] polybius, String key) {
final int codeSize = encryptedText.replace(" ", "").length();
String code = "";
for ( int i = 0; code.length() < codeSize; i++ ) {
for ( String block : encryptedText.split(" ") ) {
if ( code.length() < codeSize ) {
code += block.charAt(i);
}
}
}
String plainText = "";
for ( int i = 0; i < codeSize - 1; i += 2 ) {
int row = ADFGVX.indexOf(code.substring(i, i + 1));
int column = ADFGVX.indexOf(code.substring(i + 1, i + 2));
plainText += polybius[row][column];
}
return plainText;
}
// Create a key using a word from the dictionary 'unixdict.txt'
private static String createKey(int size) throws IOException {
if ( size < 7 || size > 12 ) {
throw new AssertionError("Key should contain between 7 and 12 letters, both inclusive.");
}
List<String> candidates = Files.lines(Path.of("unixdict.txt"))
.filter( word -> word.length() == size )
.filter( word -> word.chars().distinct().count() == word.length() )
.filter( word -> word.chars().allMatch(Character::isLetterOrDigit) )
.collect(Collectors.toList());
Collections.shuffle(candidates);
return candidates.get(0).toUpperCase();
}
private static char[][] initialisePolybiusSquare() {
List<String> letters = Arrays.asList("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split(""));
Collections.shuffle(letters);
char[][] result = new char[6][6];
for ( int row = 0; row < 6; row++ ) {
for ( int column = 0; column < 6; column++ ) {
result[row][column] = letters.get(6 * row + column).charAt(0);
}
}
return result;
}
private static final String ADFGVX = "ADFGVX";
}

View file

@ -1,7 +1,7 @@
import "random" for Random
import "/ioutil" for FileUtil
import "/seq" for Lst
import "/str" for Char, Str
import "./ioutil" for FileUtil
import "./seq" for Lst
import "./str" for Char, Str
var rand = Random.new()
var adfgvx = "ADFGVX"

View file

@ -1,6 +1,6 @@
import "/dynamic" for Tuple
import "/fmt" for Fmt
import "/big" for BigInt
import "./dynamic" for Tuple
import "./fmt" for Fmt
import "./big" for BigInt
var Result = Tuple.create("Result", ["name", "size", "start", "end"])

View file

@ -0,0 +1,212 @@
(defvar avl-all-nodes (make-vector 100 nil))
(defvar avl-root-node nil "root node")
(defun avl-create-node (key parent)
(copy-tree `((:key . ,key) (:balance . nil) (:height . nil)
(:left . nil) (:right . nil) (:parent . ,parent))))
(defun avl-node (pos)
(if (or (null pos) (> pos (1- (length avl-all-nodes))))
nil
(aref avl-all-nodes pos)))
(defun avl-node-prop (noderef &rest props)
(if (null noderef)
nil
(progn
;;(when (integerp noderef) (setq node (avl-node node)))
(let ((val noderef))
(dolist (prop props)
(if (null (avl-node val))
(setq val nil)
(progn
(setq val (alist-get prop (avl-node val))))))
val)
)
)
)
(defun avl-set-prop (node &rest props-and-value)
(when (integerp node) (setq node (avl-node node)))
(when (< (length props-and-value) 2)
(error "Both property name and value must be given."))
(let (noderef (props (seq-take props-and-value (1- (length props-and-value))))
(value (seq-elt props-and-value (1- (length props-and-value)))))
(when (> (length props) 0)
(dolist (prop (seq-take props (1- (length props))))
(if (null node)
(progn (setq noderef nil) (setq node nil))
(progn
(setq noderef (alist-get prop node))
(setq node (avl-node noderef))))))
(if (or (null (last props)) (null node))
nil
(setcdr (assoc (car (last props)) node) value))))
(defun avl-height (noderef)
(or (avl-node-prop noderef :height) -1))
(defun avl-reheight (noderef)
(if (null noderef)
nil
(avl-set-prop noderef :height
(1+ (max (avl-height (avl-node-prop noderef :left))
(avl-height (avl-node-prop noderef :right)))))))
(defun avl-setbalance (noderef)
;;(when (integerp node) (setq node (avl-node node)))
(avl-reheight noderef)
(avl-set-prop noderef :balance
(- (avl-height (avl-node-prop noderef :right))
(avl-height (avl-node-prop noderef :left)))))
(defun avl-add-node (key parent)
(let (result (idx 0))
(cl-loop for idx from 0 to (1- (seq-length avl-all-nodes))
while (null result) do
(when (null (aref avl-all-nodes idx))
(aset avl-all-nodes idx (avl-create-node key parent))
(setq result idx)))
result))
(defun avl-insert (key)
(if (null avl-root-node)
(progn (setq avl-root-node (avl-add-node key nil)) avl-root-node)
(progn
(let ((n avl-root-node) (end-loop nil) parent go-left result)
(while (not end-loop)
(if (equal key (avl-node-prop n :key))
(setq end-loop 't)
(progn
(setq parent n)
(setq go-left (> (avl-node-prop n :key) key))
(setq n (if go-left
(avl-node-prop n :left)
(avl-node-prop n :right)))
(when (null n)
(setq result (avl-add-node key parent))
(if go-left
(progn
(avl-set-prop parent :left result))
(progn
(avl-set-prop parent :right result)))
(avl-rebalance parent) ;;rebalance
(setq end-loop 't)))))
result))))
(defun avl-rotate-left (noderef)
(when (not (integerp noderef)) (error "parameter must be an integer"))
(let ((a noderef) b)
(setq b (avl-node-prop a :right))
(avl-set-prop b :parent (avl-node-prop a :parent))
(avl-set-prop a :right (avl-node-prop b :left))
(when (avl-node-prop a :right) (avl-set-prop a :right :parent a))
(avl-set-prop b :left a)
(avl-set-prop a :parent b)
(when (not (null (avl-node-prop b :parent)))
(if (equal (avl-node-prop b :parent :right) a)
(avl-set-prop b :parent :right b)
(avl-set-prop b :parent :left b)))
(avl-setbalance a)
(avl-setbalance b)
b))
(defun avl-rotate-right (node-idx)
(when (not (integerp node-idx)) (error "parameter must be an integer"))
(let ((a node-idx) b)
(setq b (avl-node-prop a :left))
(avl-set-prop b :parent (avl-node-prop a :parent))
(avl-set-prop a :left (avl-node-prop b :right))
(when (avl-node-prop a :right) (avl-set-prop a :right :parent a))
(avl-set-prop b :left a)
(avl-set-prop a :parent b)
(when (not (null (avl-node-prop b :parent)))
(if (equal (avl-node-prop b :parent :right) a)
(avl-set-prop b :parent :right b)
(avl-set-prop b :parent :left b)))
(avl-setbalance a)
(avl-setbalance b)
b))
(defun avl-rotate-left-then-right (noderef)
(avl-set-prop noderef :left (avl-rotate-left (avl-node-prop noderef :left)))
(avl-rotate-right noderef))
(defun avl-rotate-right-then-left (noderef)
(avl-set-prop noderef :right (avl-rotate-left (avl-node-prop noderef :right)))
(avl-rotate-left noderef))
(defun avl-rebalance (noderef)
(avl-setbalance noderef)
(cond
((equal -2 (avl-node-prop noderef :balance))
(if (>= (avl-height (avl-node-prop noderef :left :left))
(avl-height (avl-node-prop noderef :left :right)))
(setq noderef (avl-rotate-right noderef))
(setq noderef (avl-rotate-left-then-right noderef)))
)
((equal 2 (avl-node-prop noderef :balance))
(if (>= (avl-height (avl-node-prop noderef :right :right))
(avl-height (avl-node-prop noderef :right :left)))
(setq noderef (avl-rotate-left noderef))
(setq noderef (avl-rotate-right-then-left noderef)))))
(if (not (null (avl-node-prop noderef :parent)))
(avl-rebalance (avl-node-prop noderef :parent))
(setq avl-root-node noderef)))
(defun avl-delete (noderef)
(when noderef
(when (and (null (avl-node-prop noderef :left))
(null (avl-node-prop noderef :right)))
(if (null (avl-node-prop noderef :parent))
(setq avl-root-node nil)
(let ((parent (avl-node-prop noderef :parent)))
(if (equal noderef (avl-node-prop parent :left))
(avl-set-prop parent :left nil)
(avl-set-prop parent :right nil))
(avl-rebalance parent))))
(if (not (null (avl-node-prop noderef :left)))
(let ((child (avl-node-prop noderef :left)))
(while (not (null (avl-node-prop child :right)))
(setq child (avl-node-prop child :right)))
(avl-set-prop noderef :key (avl-node-prop child :key))
(avl-delete child))
(let ((child (avl-node-prop noderef :right)))
(while (not (null (avl-node-prop child :left)))
(setq child (avl-node-prop child :left)))
(avl-set-prop noderef :key (avl-node-prop child :key))
(avl-delete child)))))
;; Main procedure
(let ((cnt 10) balances)
(fillarray avl-all-nodes nil)
(setq avl-root-node nil)
(dotimes (val cnt)
(avl-insert (1+ val)))
(setq balances (seq-map (lambda (x) (or (avl-node-prop x :balance) 0))
(number-sequence 0 (1- cnt))))
(message "Inserting values 1 to %d" cnt)
(message "Printing balance: %s" (string-join (seq-map (lambda (x) (format "%S" x)) balances) " ")))

View file

@ -0,0 +1,21 @@
library(stringi)
abbrev <- function(w) {
w1 <- stri_split_fixed(w," ") %>% unlist()
if (length(w1) != 7) stop("Error: not enough days in the week.")
maxv <- max(sapply(w1,\(x) nchar(x)))
for (i in 1:maxv) {
tl <- stri_sub(w1,1,i) %>% unique() %>% length()
if (tl == 7) return(i)
}
}
# Main
lines <- readLines("daysOfWeek.txt")
for (l in lines) {
if (nchar(l) == 0) {
cat("\n")
} else {
cat(paste(abbrev(l),l),"\n")
}
}

View file

@ -1,7 +1,7 @@
import "io" for File
import "/pattern" for Pattern
import "/seq" for Lst
import "/fmt" for Fmt
import "./pattern" for Pattern
import "./seq" for Lst
import "./fmt" for Fmt
var p = Pattern.new("+1/s")
var lines = File.read("days_of_week.txt").split("\n").map { |l| l.trim() }

View file

@ -0,0 +1,33 @@
library(stringi)
cmds_block <- "
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"
cmds <- cmds_block %>% trimws() %>% stri_split_regex("\\s+") %>% unlist()
check_word <- function(inputw,comw) {
inputl <- nchar(inputw)
coml <- nchar(comw)
cap_cnt <- stri_count_regex(comw,"[A-Z]")
ifelse(cap_cnt != 0 && inputl >= cap_cnt && inputl <= coml &&
stri_startswith_fixed(toupper(comw),toupper(inputw)),T,F)
}
# Inputs
intstr_list <- "riG rePEAT copies put mo rest types fup. 6 poweRin" %>%
stri_split_regex("\\s+") %>% unlist()
# Results
results <- sapply(intstr_list,\(y) {
matc <- cmds[sapply(cmds,\(x) check_word(y,x))]
ifelse(length(matc) != 0,toupper(matc[1]),"*error*")
})
print(results)

View file

@ -1,5 +1,5 @@
import "/fmt" for Fmt
import "/str" for Str
import "./fmt" for Fmt
import "./str" for Str
var table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " +

View file

@ -1,5 +1,5 @@
import "/fmt" for Fmt
import "/str" for Str
import "./fmt" for Fmt
import "./str" for Str
var table =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +

View file

@ -1,4 +1,4 @@
import "/fmt" for Fmt
import "./fmt" for Fmt
class Sandpile {
static init() {

View file

@ -0,0 +1,76 @@
colors = [color.black, color.yellow, color.orange,
color.brown, color.red, color.fuchsia,
color.purple, color.blue, color.navy]
rows = 48; rowRange = range(0, rows-1)
cols = 72; colRange = range(0, cols-1)
particlesOfSand = rows * cols
divBase = particlesOfSand / (colors.len - 4)
deltas = [[0,-1],[-1, 0], [1, 0],[0, 1]]
displayGrid = function(grid, td)
for y in globals.rowRange
for x in globals.colRange
colorIx = grid[y][x]
// determine the rest of the colors if > 3 by division
if colorIx > 3 then colorIx = (colorIx - 3) / divBase + 4
td.setCell x,y, colorIx
end for
end for
end function
clear
// Prepare a tile display
// Generate image used for the tiles from the defined above.
// The colors are to indicate height of a sand pile.
img = Image.create(colors.len, 1);
for i in range(0, colors.len - 1)
img.setPixel(i, 0, colors[i])
end for
grid = []
for y in rowRange
row = []
for x in colRange
row.push(0)
end for
grid.push(row)
end for
grid[rows/2][cols/2] = particlesOfSand
display(4).mode = displayMode.tile
td = display(4)
td.cellSize = 640/48 // size of cells on screen
td.extent = [cols, rows]
td.overlap = 0 // adds a small gap between cells
td.tileSet = img; td.tileSetTileSize = 1
td.clear 0
toTopple = []
for y in rowRange
for x in colRange
if grid[y][x] > 3 and toTopple.indexOf([x,y]) == null then toTopple.push([x,y])
end for
end for
tt = time
while toTopple.len > 0
nextGen = []
for cell in toTopple
x = cell[0]; y = cell[1]
grid[y][x] -= 4
for delta in deltas
x1 = (x + delta[0]) % cols; y1 = (y + delta[1]) % rows
grid[y1][x1] += 1
end for
end for
for y in rowRange
for x in colRange
if grid[y][x] > 3 and nextGen.indexOf([x,y]) == null then nextGen.push([x,y])
end for
end for
toTopple = nextGen
displayGrid(grid, td)
end while
key.get()

View file

@ -0,0 +1,42 @@
# Return (x,y) index from a grid from an index in a list based on the grid size
pos_to_index <- function(n) {
f1 <- n/gridsize
col <- ifelse(n%%gridsize == 0, f1,as.integer(f1)+1)
row <- n - ((col-1)*gridsize)
list(row=row,col=col)
}
# Return adjacent indexes (north, east, south, west)
adjacent_indexes <- function(r,c) {
rup <- r - 1
rdn <- ifelse(r == gridsize,0,r + 1)
cleft <- c - 1
cright <- ifelse(c==gridsize,0,c+1)
list(up=c(rup,c),right=c(r,cright),left=c(r,cleft),down=c(rdn,c))
}
# Generate Abelian pattern
abelian <- function(gridsize,sand) {
mat_ <- matrix(rep(0,gridsize^2),gridsize)
midv <- as.integer(gridsize/2) + 1
mat_[midv,midv] <- sand
cat("Before\n")
print(mat_)
while(T) {
cnt <- cnt + 1
tgt <- which(mat_ >= 4)
if (length(tgt) == 0) break
pos <- pos_to_index(tgt[1])
idxes <- adjacent_indexes(pos$row,pos$col)
mat_[pos$row,pos$col] <- mat_[pos$row,pos$col] - 4
for (i in idxes) if (0 %in% i == F) mat_[i[1],i[2]] <- mat_[i[1],i[2]] +1
}
cat("After\n")
print(mat_)
}
# Main
abelian(10,64)

View file

@ -1,4 +1,4 @@
import "/fmt" for Fmt
import "./fmt" for Fmt
class Sandpile {
// 'a' is a list of integers in row order

View file

@ -1,4 +1,4 @@
^|EMal doesn't support abstract types with partial implementations,
^|EMal does not support abstract types with partial implementations,
|but can use interfaces.
|^
type Beast

View file

@ -1,4 +1,4 @@
import "/fmt" for Fmt
import "./fmt" for Fmt
class Beast{
kind {}

View file

@ -0,0 +1,17 @@
program classifications;
P := properdivisorsums(20000);
print("Deficient:", #[n : n in [1..#P] | P(n) < n]);
print(" Perfect:", #[n : n in [1..#P] | P(n) = n]);
print(" Abundant:", #[n : n in [1..#P] | P(n) > n]);
proc properdivisorsums(n);
p := [0];
loop for i in [1..n] do
loop for j in [i*2, i*3..n] do
p(j) +:= i;
end loop;
end loop;
return p;
end proc;
end program;

View file

@ -1,4 +1,4 @@
import "/math" for Int, Nums
import "./math" for Int, Nums
var d = 0
var a = 0

View file

@ -3,30 +3,30 @@ var abundantCount = 0
var deficientCount = 0
var perfectCount = 0
var pds = []
pds.add( 0 ) // element 0
pds.add( 0 ) // element 1
for( i in 2 .. maxNumber ){
pds.add( 1 )
var pds = []
pds.add(0) // element 0
pds.add(0) // element 1
for (i in 2..maxNumber) {
pds.add(1)
}
for( i in 2 .. maxNumber ){
for (i in 2..maxNumber) {
var j = i + i
while( j < maxNumber ){
pds[ j ] = pds[ j ] + i
while (j <= maxNumber) {
pds[j] = pds[j] + i
j = j + i
}
}
for( n in 1 .. maxNumber ){
var pdSum = pds[ n ]
if ( pdSum < n ){
for (n in 1..maxNumber) {
var pdSum = pds[n]
if (pdSum < n) {
deficientCount = deficientCount + 1
} else if( pdSum == n ){
perfectCount = perfectCount + 1
} else if (pdSum == n) {
perfectCount = perfectCount + 1
} else { // pdSum > n
abundantCount = abundantCount + 1
abundantCount = abundantCount + 1
}
}
System.print( "Abundant : %(abundantCount)" )
System.print( "Deficient: %(deficientCount)" )
System.print( "Perfect : %(perfectCount)" )
System.print("Abundant : %(abundantCount)")
System.print("Deficient: %(deficientCount)")
System.print("Perfect : %(perfectCount)")

View file

@ -0,0 +1,44 @@
divisorSum = function(n)
ans = 0
i = 1
while i * i <= n
if n % i == 0 then
ans += i
j = floor(n / i)
if j != i then ans += j
end if
i += 1
end while
return ans
end function
cnt = 0
n = 1
while cnt < 25
sum = divisorSum(n) - n
if sum > n then
print n + ": " + sum
cnt += 1
end if
n += 2
end while
while true
sum = divisorSum(n) - n
if sum > n then
cnt += 1
if cnt == 1000 then break
end if
n += 2
end while
print "The 1000th abundant number is " + n + " with a proper divisor sum of " + sum
n = 1000000001
while true
sum = divisorSum(n) - n
if sum > n and n > 1000000000 then break
n += 2
end while
print "The first abundant number > 1b is " + n + " with a proper divisor sum of " + sum

View file

@ -1,5 +1,5 @@
import "/fmt" for Fmt
import "/math" for Int, Nums
import "./fmt" for Fmt
import "./math" for Int, Nums
var sumStr = Fn.new { |divs| divs.reduce("") { |acc, div| acc + "%(div) + " }[0...-3] }
@ -14,9 +14,9 @@ var abundantOdd = Fn.new { |searchFrom, countFrom, countTo, printOne|
if (!printOne || count >= countTo) {
var s = sumStr.call(divs)
if (!printOne) {
System.print("%(Fmt.d(2, count)). %(Fmt.d(5, n)) < %(s) = %(tot)")
Fmt.print("$2d. $5d < $s = $d", count, n, s, tot)
} else {
System.print("%(n) < %(s) = %(tot)")
Fmt.print("$d < $s = $d", n, s, tot)
}
}
}

View file

@ -3,7 +3,7 @@ in Org:RosettaCode
|that are usually not nullable, such as int or real.
|In the following code we are telling EMal that int and real implement
|the Number virtual interface, so that it can only
|accept null (because it's an interface), int, and real values.
|accept null (because it is an interface), int, and real values.
|^
type Number allows int, real
type AccumulatorUsingNumber
@ -32,7 +32,7 @@ fun foo = fun by var n
end
type Main
^|we have developed two solutions,
|it's time to create a list holding both data types.
|it is time to create a list holding both data types.
|We iterate over the solutions in order to test them.
|^
List solutions = generic[AccumulatorUsingNumber, AccumulatorUsingVar]

View file

@ -1,5 +1,5 @@
function(acc)
= (n => acc.append:n);
= (n => acc.append(n));
accumulator(n)
= function(new Variable(n));

View file

@ -0,0 +1,25 @@
Accumulator = function(n)
adder = {"sum": n}
adder.plus = function(n)
self.sum += n
return self.sum
end function
adder.getSum = function(n)
obj = self
_sum = function(n)
return obj.plus(n)
end function
return @_sum
end function
return adder.getSum
end function
acc1 = Accumulator(0)
print acc1(10) // prints 10
print acc1(2) // prints 12
acc2 = Accumulator(1)
print acc2(100) // prints 101
print acc1(0) // prints 12

View file

@ -0,0 +1,10 @@
let fac = fn(n) {
fn(i) {
n := n + i
}
}
let x = fac(1)
x(5)
fac(3)
print(x(2.3))

View file

@ -0,0 +1,85 @@
function GCD(n, d)
if(d = 0) then return n else return GCD(d, n % d)
end function
function Totient(n)
tot = 0
for m = 1 to n
if GCD(m, n) = 1 then tot += 1
next m
return tot
end function
function isPowerful(m)
n = m
f = 2
l = sqr(m)
if m <= 1 then return false
while true
q = n/f
if (n % f) = 0 then
if (m %(f*f)) then return false
n = q
if f > n then exit while
else
f += 1
if f > l then
if (m % (n*n)) then return false
exit while
end if
end if
end while
return true
end function
function isAchilles(n)
if not isPowerful(n) then return false
m = 2
a = m*m
do
do
if a = n then return false
a *= m
until a > n
m += 1
a = m*m
until a > n
return true
end function
print "First 50 Achilles numbers:"
num = 0
n = 1
do
if isAchilles(n) then
print rjust(n, 5);
num += 1
if (num % 10) <> 0 then print " "; else print
end if
n += 1
until num >= 50
print : print
print "First 20 strong Achilles numbers:"
num = 0
n = 1
do
if isAchilles(n) and isAchilles(Totient(n)) then
print rjust(n, 5);
num += 1
if (num % 10) <> 0 then print " "; else print
end if
n += 1
until num >= 20
print : print
print "Number of Achilles numbers with:"
for i = 2 to 6
inicio = fix(10.0 ^ (i-1))
num = 0
for n = inicio to inicio*10-1
if isAchilles(n) then num += 1
next n
print i; " digits:"; num
next i

View file

@ -2,11 +2,11 @@ use strict;
use warnings;
use feature <say current_sub>;
use experimental 'signatures';
use List::AllUtils <max head uniqint>;
use ntheory <is_square_free is_power euler_phi>;
use Math::AnyNum <:overload idiv iroot ipow is_coprime>;
use List::AllUtils <max head>;
use ntheory <is_square_free euler_phi>;
use Math::AnyNum <:overload idiv is_power iroot ipow is_coprime>;
sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }
sub table { my $t = shift() * (my $c = 1 + length max @_); (sprintf(('%' . $c . 'd') x @_, @_)) =~ s/.{1,$t}\K/\n/gr }
sub powerful_numbers ($n, $k = 2) {
my @powerful;
@ -16,19 +16,21 @@ sub powerful_numbers ($n, $k = 2) {
if ($r > $k) { next unless is_square_free($v) and is_coprime($m, $v) }
__SUB__->($m * ipow($v, $r), $r - 1);
}
}->(1, 2*$k - 1);
}->(1, 2 * $k - 1);
sort { $a <=> $b } @powerful;
}
my(@P, @achilles, %Ahash, @strong);
@P = uniqint @P, powerful_numbers(10**9, $_) for 2..9; shift @P;
my (@achilles, %Ahash, @strong);
my @P = powerful_numbers(10**9, 2);
!is_power($_) and push @achilles, $_ and $Ahash{$_}++ for @P;
$Ahash{euler_phi $_} and push @strong, $_ for @achilles;
say "First 50 Achilles numbers:\n" . table 10, head 50, @achilles;
say "First 50 Achilles numbers:\n" . table 10, head 50, @achilles;
say "First 30 strong Achilles numbers:\n" . table 10, head 30, @strong;
say "Number of Achilles numbers with:\n";
for my $l (2..9) {
my $c; $l == length and $c++ for @achilles;
for my $l (2 .. 9) {
my $c;
$l == length and $c++ for @achilles;
say "$l digits: $c";
}

View file

@ -0,0 +1,14 @@
var P = 2.powerful(1e9)
var achilles = Set(P.grep{ !.is_power }...)
var strong_achilles = achilles.grep { achilles.has(.phi) }
say "First 50 Achilles numbers:"
achilles.sort.first(50).slices(10).each { .map{'%4s'%_}.join(' ').say }
say "\nFirst 30 strong Achilles numbers:"
strong_achilles.sort.first(30).slices(10).each { .map{'%5s'%_}.join(' ').say }
say "\nNumber of Achilles numbers with:"
achilles.to_a.group_by{.len}.sort_by{|k| k.to_i }.each_2d{|a,b|
say "#{a} digits: #{b.len}"
}

View file

@ -6,21 +6,6 @@ var maxDigits = 8
var limit = 10.pow(maxDigits)
var c = Int.primeSieve(limit-1, false)
var totient = Fn.new { |n|
var tot = n
var i = 2
while (i*i <= n) {
if (n%i == 0) {
while(n%i == 0) n = (n/i).floor
tot = tot - (tot/i).floor
}
if (i == 2) i = 1
i = i + 2
}
if (n > 1) tot = tot - (tot/n).floor
return tot
}
var isPerfectPower = Fn.new { |n|
if (n == 1) return true
var x = 2
@ -63,7 +48,7 @@ var isAchilles = Fn.new { |n| c[n] && isPowerful.call(n) && !isPerfectPower.call
var isStrongAchilles = Fn.new { |n|
if (!isAchilles.call(n)) return false
var tot = totient.call(n)
var tot = Int.totient(n)
return isAchilles.call(tot)
}
@ -78,7 +63,7 @@ while (count < 50) {
}
n = n + 1
}
for (chunk in Lst.chunks(achilles, 10)) Fmt.print("$4d", chunk)
Fmt.tprint("$4d", achilles, 10)
System.print("\nFirst 30 strong Achilles numbers:")
var strongAchilles = []
@ -91,7 +76,7 @@ while (count < 30) {
}
n = n + 1
}
for (chunk in Lst.chunks(strongAchilles, 10)) Fmt.print("$5d", chunk)
Fmt.tprint("$5d", strongAchilles, 10)
System.print("\nNumber of Achilles numbers with:")
var pow = 10

View file

@ -1,22 +1,8 @@
import "./set" for Set
import "./seq" for Lst
import "./math" for Int
import "./fmt" for Fmt
var totient = Fn.new { |n|
var tot = n
var i = 2
while (i*i <= n) {
if (n%i == 0) {
while(n%i == 0) n = (n/i).floor
tot = tot - (tot/i).floor
}
if (i == 2) i = 1
i = i + 2
}
if (n > 1) tot = tot - (tot/n).floor
return tot
}
var pps = Set.new()
var getPerfectPowers = Fn.new { |maxExp|
@ -52,21 +38,21 @@ var achilles = achillesSet.toList
achilles.sort()
System.print("First 50 Achilles numbers:")
for (chunk in Lst.chunks(achilles[0..49], 10)) Fmt.print("$4d", chunk)
Fmt.tprint("$4d", achilles.take(50), 10)
System.print("\nFirst 30 strong Achilles numbers:")
var strongAchilles = []
var count = 0
var n = 0
while (count < 30) {
var tot = totient.call(achilles[n])
var tot = Int.totient(achilles[n])
if (achillesSet.contains(tot)) {
strongAchilles.add(achilles[n])
count = count + 1
}
n = n + 1
}
for (chunk in Lst.chunks(strongAchilles, 10)) Fmt.print("$5d", chunk)
Fmt.tprint("$5d", strongAchilles, 10)
System.print("\nNumber of Achilles numbers with:")
for (d in 2..maxDigits) {

View file

@ -2,29 +2,29 @@ import extensions;
ackermann(m,n)
{
if(n < 0 || m < 0)
{
InvalidArgumentException.raise()
};
if(n < 0 || m < 0)
{
InvalidArgumentException.raise()
};
m =>
0 { ^n + 1 }
: {
n =>
0 { ^ackermann(m - 1,1) }
: { ^ackermann(m - 1,ackermann(m,n-1)) }
}
m =>
0 { ^n + 1 }
! {
n =>
0 { ^ackermann(m - 1,1) }
! { ^ackermann(m - 1,ackermann(m,n-1)) }
}
}
public program()
{
for(int i:=0, i <= 3, i += 1)
{
for(int j := 0, j <= 5, j += 1)
{
console.printLine("A(",i,",",j,")=",ackermann(i,j))
}
};
for(int i:=0, i <= 3, i += 1)
{
for(int j := 0, j <= 5, j += 1)
{
console.printLine("A(",i,",",j,")=",ackermann(i,j))
}
};
console.readChar()
console.readChar()
}

View file

@ -0,0 +1,9 @@
let A = fn(m, n) {
if m == 0 {n + 1}
else if m > 0 and n == 0 {A(m - 1, 1)}
else {A(m - 1, A(m, n - 1))}
}
print(A(0, 0))
print(A(3, 4))
print(A(3, 1))

View file

@ -1,4 +1,4 @@
/* active_directory_connect.wren */
/* Active_Directory_Connect.wren */
foreign class LDAP {
construct init(host, port) {}

View file

@ -100,7 +100,7 @@ int main(int argc, char **argv) {
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "active_directory_connect.wren";
const char* fileName = "Active_Directory_Connect.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {

View file

@ -1,4 +1,4 @@
/* active_directory_search_for_user.wren */
/* Active_Directory_Search_for_a_user.wren */
var LDAP_SCOPE_SUBTREE = 0x0002

View file

@ -125,7 +125,7 @@ int main(int argc, char **argv) {
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "active_directory_search_for_user.wren";
const char* fileName = "Active_Directory_Search_for_a_user.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {

View file

@ -0,0 +1,34 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public final class AddVariableToClassInstanceAtRuntime {
public static void main(String[] args) {
Demonstration demo = new Demonstration();
System.out.println("Create two variables at runtime: ");
Scanner scanner = new Scanner(System.in);
for ( int i = 1; i <= 2; i++ ) {
System.out.println(" Variable number " + i + ":");
System.out.print(" Enter name: ");
String name = scanner.nextLine();
System.out.print(" Enter value: ");
String value = scanner.nextLine();
demo.runtimeVariables.put(name, value);
System.out.println();
}
scanner.close();
System.out.println("Two new runtime variables appear to have been created.");
for ( Map.Entry<String, Object> entry : demo.runtimeVariables.entrySet() ) {
System.out.println("Variable " + entry.getKey() + " = " + entry.getValue());
}
}
}
final class Demonstration {
Map<String, Object> runtimeVariables = new HashMap<String, Object>();
}

View file

@ -0,0 +1,28 @@
isPrime = function(n)
if n <= 3 then return n > 1
if n % 2 == 0 or n % 3 == 0 then return false
i = 5
while i ^ 2 <= n
if n % i == 0 or n % (i + 2) == 0 then return false
i += 6
end while
return true
end function
digitSum = function(n)
sum = 0
while n > 0
sum += n % 10
n = floor(n / 10)
end while
return sum
end function
additive = []
for i in range(2, 500)
if isPrime(i) and isPrime(digitSum(i)) then additive.push(i)
end for
print "There are " + additive.len + " additive primes under 500."
print additive

View file

@ -0,0 +1,9 @@
digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10)
is.prime <- function(n) n == 2L || all(n %% 2L:max(2,floor(sqrt(n))) != 0)
range_int <- 2:500
v <- sapply(range_int, \(x) is.prime(x) && is.prime(digitsum(x)))
cat(paste("Found",length(range_int[v]),"additive primes less than 500"))
print(range_int[v])

View file

@ -1,5 +1,5 @@
import "/math" for Int
import "/fmt" for Fmt
import "./math" for Int
import "./fmt" for Fmt
var sumDigits = Fn.new { |n|
var sum = 0

View file

@ -0,0 +1,72 @@
public class Task {
enum Color { R, B }
sealed interface Tree<A extends Comparable<A>> permits E, T {
default Tree<A> insert(A a) {
return switch(ins(a)) {
case T(_, var l, var v, var r) -> new T<>(Color.B, l, v, r);
case E() -> new E<>();
};
}
Tree<A> ins(A a);
}
record E<A extends Comparable<A>>() implements Tree<A> {
@Override
public Tree<A> ins(A a) {
return new T<>(Color.R, new E<>(), a, new E<>());
}
@Override
public String toString() { return "E"; }
}
record T<A extends Comparable<A>>(Color color, Tree<A> left,
A value, Tree<A> right) implements Tree<A> {
@Override
public Tree<A> ins(A a) {
return switch(Integer.valueOf(a.compareTo(value))) {
case Integer i when i < 0 -> new T<>(color, left.ins(a), value, right).balance();
case Integer i when i > 0 -> new T<>(color, left, value, right.ins(a)).balance();
default -> this;
};
}
private Tree<A> balance() {
if (color == Color.R) return this;
return switch (this) {
// unnamed patterns (case T<A>(_, ...)) are a JDK21 Preview feature
case T<A>(_, T<A>(_, T<A>(_, var a, var x, var b), var y, var c), var z, var d)
when left instanceof T<A> le && le.left instanceof T<A> le_le &&
le.color == Color.R && le_le.color == Color.R ->
new T<>(Color.R, new T<>(Color.B, a, x, b), y, new T<>(Color.B, c, z, d));
case T<A>(_, T<A>(_, var a, var x, T<A>(_, var b, var y, var c)), var z, var d)
when left instanceof T<A> le && le.right instanceof T<A> le_ri &&
le.color == Color.R && le_ri.color == Color.R ->
new T<>(Color.R, new T<>(Color.B, a, x, b), y, new T<>(Color.B, c, z, d));
case T<A>(_, var a, var x, T<A>(_, T<A>(_, var b, var y, var c), var z, var d))
when right instanceof T<A> ri && ri.left instanceof T<A> ri_le &&
ri.color == Color.R && ri_le.color == Color.R ->
new T<>(Color.R, new T<>(Color.B, a, x, b), y, new T<>(Color.B, c, z, d));
case T<A>(_, var a, var x, T<A>(_, var b, var y, T<A>(_, var c, var z, var d)))
when right instanceof T<A> ri && ri.right instanceof T<A> ri_ri &&
ri.color == Color.R && ri_ri.color == Color.R ->
new T<>(Color.R, new T<>(Color.B, a, x, b), y, new T<>(Color.B, c, z, d));
default -> this;
};
}
@Override
public String toString() {
return STR."T[\{color}, \{left}, \{value}, \{right}]"; // String templates are a JDK 21 Preview feature
}
}
public static void main(String[] args) {
Tree<Integer> tree = new E<>();
for (var i : IntStream.rangeClosed(1, 16).toArray()) {
tree = tree.insert(i);
}
System.out.println(tree);
}
}

View file

@ -0,0 +1,10 @@
align{
left {}
right {(-)}
center {(-()+(-)÷2)}
text ⎕NGET
words (('$'))¨(~text⎕TC)text
sizes 1+¨¨words
method
,/(sizes)method¨¨words
}

View file

@ -10,7 +10,7 @@ proc read . .
.
.
.
call read
read
#
proc out mode . .
for inp$ in inp$[]
@ -40,11 +40,11 @@ proc out mode . .
print ""
.
.
call out 1
out 1
print ""
call out 2
out 2
print ""
call out 3
out 3
#
input_data
Given$a$text$file$of$many$lines,$where$fields$within$a$line$

View file

@ -0,0 +1,58 @@
Alignment = {"left": -1, "center": 0, "right": 1}
Align = {}
Align.load = function(contents)
self.lines = contents.split(char(13))
self.rows = []
self.numColumns = 0
for line in self.lines
columns = line.split("$")
if columns.len > self.numColumns then self.numColumns = columns.len
self.rows.push(columns)
end for
self.widths = []
for col in range(0, self.numColumns - 1)
maxWidth = 0
for line in self.rows
if col > line.len - 1 then continue
if line[col].len > maxWidth then maxWidth = line[col].len
end for
self.widths.push(maxWidth)
end for
end function
Align.__getField = function(word, width, alignment)
if alignment == Alignment.left then return (word + " " * width)[:width]
if alignment == Alignment.right then return (" " * width+word)[-width:]
if alignment == Alignment.center then
leftMargin = floor((width - word.len) / 2)
return (" " * leftMargin + word + " " * width)[:width]
end if
end function
Align.output = function(alignment)
for line in self.rows
for c in range(0, line.len - 1)
print self.__getField(line[c], self.widths[c], alignment) + " ", ""
end for
print
end for
end function
txt = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" + char(13)
txt += "are$delineated$by$a$single$'dollar'$character,$write$a$program" + char(13)
txt += "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" + char(13)
txt += "column$are$separated$by$at$least$one$space." + char(13)
txt += "Further,$allow$for$each$word$in$a$column$to$be$either$left$" + char(13)
txt += "justified,$right$justified,$or$center$justified$within$its$column."
Align.load(txt)
print "Left alignment:"
Align.output(Alignment.left)
print
print "Right alignment:"
Align.output(Alignment.right)
print
print "Centered: "
Align.output(Alignment.center)

View file

@ -0,0 +1,34 @@
program align;
magic := false; $ turn off regexp matching in GNU SETL
read_file;
ncols := max/[#line : line in lines];
sizes := [1+max/[#(line(col) ? "") : line in lines] : col in [1..ncols]];
loop for line in lines do
print(+/[align(line(col), sizes(col)) : col in [1..#line]]);
end loop;
read_file::
f := open(command_line(1), "r");
lines := [];
loop doing geta(f, line); while line /= om do
lines with:= split(line, "$");
end loop;
close(f);
proc align(s, n);
case command_line(2) of
("r"): return lpad(s, n);
("l"): return rpad(s, n);
("c"): return center(s, n);
end case;
end proc;
proc center(s, n);
padding := n - #s;
l := " " * ceil(padding/2);
r := " " * floor(padding/2);
return l + s + r;
end proc;
end program;

View file

@ -1,5 +1,5 @@
import "io" for File
import "/fmt" for Fmt
import "./fmt" for Fmt
var LEFT = 0
var RIGHT = 1

View file

@ -0,0 +1,57 @@
string 0;
def LF=$0A, CR=$0D;
def Left, Right, Center;
proc AlignCols(S); \Display string S with its columns aligned
char S, C, Field(80), ColWidth(80);
int I, J, N, Just;
proc Justify;
int T;
proc SpOut(M); \Output M space characters
int M, K;
for K:= 0 to M-1 do ChOut(0, ^ );
proc FieldOut; \Output Field of N characters
int K;
for K:= 0 to N-1 do ChOut(0, Field(K));
[case Just of
Left: [FieldOut(N); SpOut(ColWidth(J)-N+1)];
Right: [SpOut(ColWidth(J)-N+1); FieldOut(N)];
Center:[T:= ColWidth(J)-N+1;
SpOut(T/2); FieldOut(N); SpOut(T/2 + rem(0))]
other [];
];
[\Get width (in characters) of each column
for J:= 0 to 80-1 do ColWidth(J):= 0;
I:= 0; J:= 0; N:= 0;
loop [repeat C:= S(I); I:= I+1 until C # CR;
if N > ColWidth(J) then ColWidth(J):= N;
case C of
0: quit;
^$: [N:= 0; J:= J+1];
LF: [N:= 0; J:= J+1; J:= 0]
other N:= N+1;
];
for Just:= Left to Center do
[I:= 0; J:= 0; N:= 0;
loop [repeat C:= S(I); I:= I+1 until C # CR;
case C of
0: [Justify(Just); CrLf(0); quit];
^$: [Justify(Just); N:= 0; J:= J+1];
LF: [Justify(Just); CrLf(0); N:= 0; J:= 0]
other [Field(N):= C; N:= N+1];
];
CrLf(0);
];
];
AlignCols("Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.")

View file

@ -1,6 +1,6 @@
import "/fmt" for Conv, Fmt
import "/math" for Int, Nums
import "/seq" for Lst
import "./fmt" for Conv, Fmt
import "./math" for Int, Nums
import "./seq" for Lst
class Classification {
construct new(seq, aliquot) {
@ -36,18 +36,18 @@ var classifySequence = Fn.new { |k|
System.print("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
for (k in 1..10) {
var c = classifySequence.call(k)
System.print("%(Fmt.d(2, k)): %(Fmt.s(-15, c.aliquot)) %(c.seq)")
Fmt.print("$2d: $-15s $n", k, c.aliquot, c.seq)
}
System.print()
var a = [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488]
for (k in a) {
var c = classifySequence.call(k)
System.print("%(Fmt.d(7, k)): %(Fmt.s(-15, c.aliquot)) %(c.seq)")
Fmt.print("$7d: $-15s $n", k, c.aliquot, c.seq)
}
System.print()
var k = 15355717786080
var c = classifySequence.call(k)
var seq = c.seq.map { |i| Conv.dec(i) }.toList // ensure 15 digit integer is printed in full
System.print("%(k): %(Fmt.s(-15, c.aliquot)) %(seq)")
Fmt.print("$d: $-15s $n", k, c.aliquot, seq)

View file

@ -1,5 +1,5 @@
import "/big" for BigInt, BigRat
import "/fmt" for Fmt
import "./big" for BigInt, BigRat
import "./fmt" for Fmt
var factorial = Fn.new { |n|
if (n < 2) return BigInt.one

View file

@ -0,0 +1,29 @@
(function prime-sieve search siever sieved
(return-when (empty? siever) (.. vec sieved search))
(let [p ps] ((juxt 0 (skip 1)) siever))
(recur (remove #(div? % p) search)
(remove #(div? % p) ps)
(append p sieved)))
(function primes n
(prime-sieve (range 2 (inc n)) (range 2 (ceil (sqrt n))) []))
(function decompose n ps factors
(return-when (= n 1) factors)
(let div (find (div? n) ps))
(recur (/ n div) ps (append div factors)))
(function almost-prime up-to n k
(return-when (zero? up-to) [])
(let ps (primes n))
(if (= k (len (decompose n ps [])))
(prepend n (almost-prime (dec up-to) (inc n) k))
(almost-prime up-to (inc n) k)))
(function row n
(-> n
@(almost-prime 10 1)
(join " ")
@(str n (match n 1 "st" 2 "nd" 3 "rd" "th") " almost-primes: " )))
(join "\n" (map row (range 1 6)))

View file

@ -0,0 +1,24 @@
primeFactory = function(n=2)
if n < 2 then return ""
for i in range(2, n)
p = floor(n / i)
q = n % i
if not q then return str(i) + " " + str(primeFactory(p))
end for
return n
end function
getAlmostPrimes = function(k)
almost = []
n = 2
while almost.len < 10
primes = primeFactory(n).trim.split
if primes.len == k then almost.push(n)
n += 1
end while
return almost
end function
for i in range(1, 5)
print i + ": " + getAlmostPrimes(i)
end for

View file

@ -0,0 +1,46 @@
func almost_primes(a, b, k) {
a = max(2**k, a)
var arr = []
func (m, lo, k) {
var hi = idiv(b,m).iroot(k)
if (k == 1) {
lo = max(lo, idiv_ceil(a, m))
each_prime(lo, hi, {|p|
arr << m*p
})
return nil
}
each_prime(lo, hi, {|p|
var t = m*p
var u = idiv_ceil(a, t)
var v = idiv(b, t)
next if (u > v)
__FUNC__(t, p, k-1)
})
}(1, 2, k)
return arr.sort
}
for k in (1..5) {
var (x=10, lo=1, hi=2)
var arr = []
loop {
arr += almost_primes(lo, hi, k)
break if (arr.len >= x)
lo = hi+1
hi = 2*lo
}
say arr.first(x)
}

View file

@ -0,0 +1,4 @@
for k in (1..5) {
var x = 10
say k.almost_primes(x.nth_almost_prime(k))
}

View file

@ -1,18 +0,0 @@
func is_k_almost_prime(n, k) {
for (var (p, f) = (2, 0); (f < k) && (p*p <= n); ++p) {
(n /= p; ++f) while (p `divides` n)
}
n > 1 ? (f.inc == k) : (f == k)
}
{ |k|
var x = 10
say gather {
{ |i|
if (is_k_almost_prime(i, k)) {
take(i)
--x == 0 && break
}
} << 1..Inf
}
} << 1..5

View file

@ -1,13 +1,11 @@
fn k_prime(n int, k int) bool {
mut nf := 0
mut nn := n
for i in 2 .. nn+1 {
for i in 2..nn + 1 {
for nn % i == 0 {
if nf == k {
return false
}
if nf == k {return false}
nf++
nn/=i
nn /= i
}
}
return nf == k
@ -16,10 +14,8 @@ fn k_prime(n int, k int) bool {
fn gen(k int, n int) []int {
mut r := []int{len:n}
mut nx := 2
for i in 0 .. n {
for !k_prime(nx, k) {
nx++
}
for i in 0..n {
for !k_prime(nx, k) {nx++}
r[i] = nx
nx++
}
@ -27,7 +23,5 @@ fn gen(k int, n int) []int {
}
fn main(){
for k in 1..6 {
println('$k ${gen(k,10)}')
}
for k in 1..6 {println('$k ${gen(k,10)}')}
}

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