task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #Nim | Nim | import strformat, strutils, tables
type
Sequence = seq[Natural]
Context = object
divisors: seq[int]
subtractors: seq[int]
seqCache: Table[int, Sequence] # Mapping number -> sequence to reach 1.
stepCache: Table[int, int] # Mapping number -> number of steps to reach 1.
proc initContext(divisors, subtractors: openArray[int]): Context =
## Initialize a context.
for d in divisors: doAssert d > 1, "divisors must be greater than 1."
for s in subtractors: doAssert s > 0, "substractors must be greater than 0."
result.divisors = @divisors
result.subtractors = @subtractors
result.seqCache[1] = @[Natural 1]
result.stepCache[1] = 0
proc minStepsDown(context: var Context; n: Natural): Sequence =
# Return a minimal sequence to reach the value 1.
assert n > 0, "“n” must be positive."
if n in context.seqCache: return context.seqCache[n]
var
minSteps = int.high
minPath: Sequence
for val in context.divisors:
if n mod val == 0:
var path = context.minStepsDown(n div val)
if path.len < minSteps:
minSteps = path.len
minPath = move(path)
for val in context.subtractors:
if n - val > 0:
var path = context.minStepsDown(n - val)
if path.len < minSteps:
minSteps = path.len
minPath = move(path)
result = n & minPath
context.seqCache[n] = result
proc minStepsDownCount(context: var Context; n: Natural): int =
## Compute the mininum number of steps without keeping the sequence.
assert n > 0, "“n” must be positive."
if n in context.stepCache: return context.stepCache[n]
result = int.high
for val in context.divisors:
if n mod val == 0:
let steps = context.minStepsDownCount(n div val)
if steps < result: result = steps
for val in context.subtractors:
if n - val > 0:
let steps = context.minStepsDownCount(n - val)
if steps < result: result = steps
inc result
context.stepCache[n] = result
template plural(n: int): string =
if n > 1: "s" else: ""
proc printMinStepsDown(context: var Context; n: Natural) =
## Search and print the sequence to reach one.
let sol = context.minStepsDown(n)
stdout.write &"{n} takes {sol.len - 1} step{plural(sol.len - 1)}: "
var prev = 0
for val in sol:
if prev == 0:
stdout.write val
elif prev - val in context.subtractors:
stdout.write " - ", prev - val, " → ", val
else:
stdout.write " / ", prev div val, " → ", val
prev = val
stdout.write '\n'
proc maxMinStepsCount(context: var Context; nmax: Positive): tuple[steps: int; list: seq[int]] =
## Return the maximal number of steps needed for numbers between 1 and "nmax"
## and the list of numbers needing this number of steps.
for n in 2..nmax:
let nsteps = context.minStepsDownCount(n)
if nsteps == result.steps:
result.list.add n
elif nsteps > result.steps:
result.steps = nsteps
result.list = @[n]
proc run(divisors, subtractors: openArray[int]) =
## Run the search for given divisors and subtractors.
var context = initContext(divisors, subtractors)
echo &"Using divisors: {divisors} and substractors: {subtractors}"
for n in 1..10: context.printMinStepsDown(n)
for nmax in [2_000, 20_000]:
let (steps, list) = context.maxMinStepsCount(nmax)
stdout.write if list.len == 1: &"There is 1 number " else: &"There are {list.len} numbers "
echo &"below {nmax} that require {steps} steps: ", list.join(", ")
run(divisors = [2, 3], subtractors = [1])
echo ""
run(divisors = [2, 3], subtractors = [2]) |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Minimal_steps_down_to_1
use warnings;
no warnings 'recursion';
use List::Util qw( first );
use Data::Dump 'dd';
for ( [ 2000, [2, 3], [1] ], [ 2000, [2, 3], [2] ] )
{
my ( $n, $div, $sub ) = @$_;
print "\n", '-' x 40, " divisors @$div subtractors @$sub\n";
my ($solve, $max) = minimal( @$_ );
printf "%4d takes %s step(s): %s\n",
$_, $solve->[$_] =~ tr/ // - 1, $solve->[$_] for 1 .. 10;
print "\n";
printf "%d number(s) below %d that take $#$max steps: %s\n",
$max->[-1] =~ tr/ //, $n, $max->[-1];
($solve, $max) = minimal( 20000, $div, $sub );
printf "%d number(s) below %d that take $#$max steps: %s\n",
$max->[-1] =~ tr/ //, 20000, $max->[-1];
}
sub minimal
{
my ($top, $div, $sub) = @_;
my @solve = (0, ' ');
my @maximal;
for my $n ( 2 .. $top )
{
my @pick;
for my $d ( @$div )
{
$n % $d and next;
my $ans = "/$d $solve[$n / $d]";
$pick[$ans =~ tr/ //] //= $ans;
}
for my $s ( @$sub )
{
$n > $s or next;
my $ans = "-$s $solve[$n - $s]";
$pick[$ans =~ tr/ //] //= $ans;
}
$solve[$n] = first { defined } @pick;
$maximal[$solve[$n] =~ tr/ // - 1] .= " $n";
}
return \@solve, \@maximal;
} |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #VBScript | VBScript | 'N-queens problem - non recursive & structured - vbs - 24/02/2017
const l=15
dim a(),s(),u(): redim a(l),s(l),u(4*l-2)
for i=1 to l: a(i)=i: next
for n=1 to l
m=0
i=1
j=0
r=2*n-1
Do
i=i-1
j=j+1
p=0
q=-r
Do
i=i+1
u(p)=1
u(q+r)=1
z=a(j): a(j)=a(i): a(i)=z 'swap a(i),a(j)
p=i-a(i)+n
q=i+a(i)-1
s(i)=j
j=i+1
Loop Until j>n Or u(p)<>0 Or u(q+r)<>0
If u(p)=0 Then
If u(q+r)=0 Then
m=m+1 'm: number of solutions
'x="": for k=1 to n: x=x&" "&a(k): next: msgbox x,,m
End If
End If
j=s(i)
Do While j>=n And i<>0
Do
z=a(j): a(j)=a(i): a(i)=z 'swap a(i),a(j)
j=j-1
Loop Until j<i
i=i-1
p=i-a(i)+n
q=i+a(i)-1
j=s(i)
u(p)=0
u(q+r)=0
Loop
Loop Until i=0
wscript.echo n &":"& m
next 'n |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #uBasic.2F4tH | uBasic/4tH | LOCAL(1) ' main uses locals as well
FOR a@ = 0 TO 200 ' set the array
@(a@) = -1
NEXT
PRINT "F sequence:" ' print the F-sequence
FOR a@ = 0 TO 20
PRINT FUNC(_f(a@));" ";
NEXT
PRINT
PRINT "M sequence:" ' print the M-sequence
FOR a@ = 0 TO 20
PRINT FUNC(_m(a@));" ";
NEXT
PRINT
END
_f PARAM(1) ' F-function
IF a@ = 0 THEN RETURN (1) ' memoize the solution
IF @(a@) < 0 THEN @(a@) = a@ - FUNC(_m(FUNC(_f(a@ - 1))))
RETURN (@(a@)) ' return array element
_m PARAM(1) ' M-function
IF a@ = 0 THEN RETURN (0) ' memoize the solution
IF @(a@+100) < 0 THEN @(a@+100) = a@ - FUNC(_f(FUNC(_m(a@ - 1))))
RETURN (@(a@+100)) ' return array element |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #OCaml | OCaml | let () =
let max = 12 in
let fmax = float_of_int max in
let dgts = int_of_float (ceil (log10 (fmax *. fmax))) in
let fmt = Printf.printf " %*d" dgts in
let fmt2 = Printf.printf "%*s%c" dgts in
fmt2 "" 'x';
for i = 1 to max do fmt i done;
print_string "\n\n";
for j = 1 to max do
fmt j;
for i = 1 to pred j do fmt2 "" ' '; done;
for i = j to max do fmt (i*j); done;
print_newline()
done;
print_newline() |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Ada | Ada | with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
procedure Minesweeper is
package IO renames Ada.Text_IO;
package Nat_IO is new IO.Integer_IO (Natural);
package Nat_RNG is new Ada.Numerics.Discrete_Random (Natural);
type Stuff is (Empty, Mine);
type Field is record
Contents : Stuff := Empty;
Opened : Boolean := False;
Marked : Boolean := False;
end record;
type Grid is array (Positive range <>, Positive range <>) of Field;
-- counts how many mines are in the surrounding fields
function Mines_Nearby (Item : Grid; X, Y : Positive) return Natural is
Result : Natural := 0;
begin
-- left of X:Y
if X > Item'First (1) then
-- above X-1:Y
if Y > Item'First (2) then
if Item (X - 1, Y - 1).Contents = Mine then
Result := Result + 1;
end if;
end if;
-- X-1:Y
if Item (X - 1, Y).Contents = Mine then
Result := Result + 1;
end if;
-- below X-1:Y
if Y < Item'Last (2) then
if Item (X - 1, Y + 1).Contents = Mine then
Result := Result + 1;
end if;
end if;
end if;
-- above of X:Y
if Y > Item'First (2) then
if Item (X, Y - 1).Contents = Mine then
Result := Result + 1;
end if;
end if;
-- below of X:Y
if Y < Item'Last (2) then
if Item (X, Y + 1).Contents = Mine then
Result := Result + 1;
end if;
end if;
-- right of X:Y
if X < Item'Last (1) then
-- above X+1:Y
if Y > Item'First (2) then
if Item (X + 1, Y - 1).Contents = Mine then
Result := Result + 1;
end if;
end if;
-- X+1:Y
if Item (X + 1, Y).Contents = Mine then
Result := Result + 1;
end if;
-- below X+1:Y
if Y < Item'Last (2) then
if Item (X + 1, Y + 1).Contents = Mine then
Result := Result + 1;
end if;
end if;
end if;
return Result;
end Mines_Nearby;
-- outputs the grid
procedure Put (Item : Grid) is
Mines : Natural := 0;
begin
IO.Put (" ");
for X in Item'Range (1) loop
Nat_IO.Put (Item => X, Width => 3);
end loop;
IO.New_Line;
IO.Put (" +");
for X in Item'Range (1) loop
IO.Put ("---");
end loop;
IO.Put ('+');
IO.New_Line;
for Y in Item'Range (2) loop
Nat_IO.Put (Item => Y, Width => 3);
IO.Put ('|');
for X in Item'Range (1) loop
if Item (X, Y).Opened then
if Item (X, Y).Contents = Empty then
if Item (X, Y).Marked then
IO.Put (" - ");
else
Mines := Mines_Nearby (Item, X, Y);
if Mines > 0 then
Nat_IO.Put (Item => Mines, Width => 2);
IO.Put (' ');
else
IO.Put (" ");
end if;
end if;
else
if Item (X, Y).Marked then
IO.Put (" + ");
else
IO.Put (" X ");
end if;
end if;
elsif Item (X, Y).Marked then
IO.Put (" ? ");
else
IO.Put (" . ");
end if;
end loop;
IO.Put ('|');
IO.New_Line;
end loop;
IO.Put (" +");
for X in Item'Range (1) loop
IO.Put ("---");
end loop;
IO.Put ('+');
IO.New_Line;
end Put;
-- marks a field as possible bomb
procedure Mark (Item : in out Grid; X, Y : in Positive) is
begin
if Item (X, Y).Opened then
IO.Put_Line ("Field already open!");
else
Item (X, Y).Marked := not Item (X, Y).Marked;
end if;
end Mark;
-- clears a field and it's neighbours, if they don't have mines
procedure Clear
(Item : in out Grid;
X, Y : in Positive;
Killed : out Boolean)
is
-- clears the neighbours, if they don't have mines
procedure Clear_Neighbours (The_X, The_Y : Positive) is
begin
-- mark current field opened
Item (The_X, The_Y).Opened := True;
-- only proceed if neighbours don't have mines
if Mines_Nearby (Item, The_X, The_Y) = 0 then
-- left of X:Y
if The_X > Item'First (1) then
-- above X-1:Y
if The_Y > Item'First (2) then
if not Item (The_X - 1, The_Y - 1).Opened and
not Item (The_X - 1, The_Y - 1).Marked
then
Clear_Neighbours (The_X - 1, The_Y - 1);
end if;
end if;
-- X-1:Y
if not Item (The_X - 1, The_Y).Opened and
not Item (The_X - 1, The_Y).Marked
then
Clear_Neighbours (The_X - 1, The_Y);
end if;
-- below X-1:Y
if The_Y < Item'Last (2) then
if not Item (The_X - 1, The_Y + 1).Opened and
not Item (The_X - 1, The_Y + 1).Marked
then
Clear_Neighbours (The_X - 1, The_Y + 1);
end if;
end if;
end if;
-- above X:Y
if The_Y > Item'First (2) then
if not Item (The_X, The_Y - 1).Opened and
not Item (The_X, The_Y - 1).Marked
then
Clear_Neighbours (The_X, The_Y - 1);
end if;
end if;
-- below X:Y
if The_Y < Item'Last (2) then
if not Item (The_X, The_Y + 1).Opened and
not Item (The_X, The_Y + 1).Marked
then
Clear_Neighbours (The_X, The_Y + 1);
end if;
end if;
-- right of X:Y
if The_X < Item'Last (1) then
-- above X+1:Y
if The_Y > Item'First (2) then
if not Item (The_X + 1, The_Y - 1).Opened and
not Item (The_X + 1, The_Y - 1).Marked
then
Clear_Neighbours (The_X + 1, The_Y - 1);
end if;
end if;
-- X+1:Y
if not Item (The_X + 1, The_Y).Opened and
not Item (The_X + 1, The_Y).Marked
then
Clear_Neighbours (The_X + 1, The_Y);
end if;
-- below X+1:Y
if The_Y < Item'Last (2) then
if not Item (The_X + 1, The_Y + 1).Opened and
not Item (The_X + 1, The_Y + 1).Marked
then
Clear_Neighbours (The_X + 1, The_Y + 1);
end if;
end if;
end if;
end if;
end Clear_Neighbours;
begin
Killed := False;
-- only clear closed and unmarked fields
if Item (X, Y).Opened then
IO.Put_Line ("Field already open!");
elsif Item (X, Y).Marked then
IO.Put_Line ("Field already marked!");
else
Killed := Item (X, Y).Contents = Mine;
-- game over if killed, no need to clear
if not Killed then
Clear_Neighbours (X, Y);
end if;
end if;
end Clear;
-- marks all fields as open
procedure Open_All (Item : in out Grid) is
begin
for X in Item'Range (1) loop
for Y in Item'Range (2) loop
Item (X, Y).Opened := True;
end loop;
end loop;
end Open_All;
-- counts the number of marks
function Count_Marks (Item : Grid) return Natural is
Result : Natural := 0;
begin
for X in Item'Range (1) loop
for Y in Item'Range (2) loop
if Item (X, Y).Marked then
Result := Result + 1;
end if;
end loop;
end loop;
return Result;
end Count_Marks;
-- read and validate user input
procedure Get_Coordinates
(Max_X, Max_Y : Positive;
X, Y : out Positive;
Valid : out Boolean)
is
begin
Valid := False;
IO.Put ("X: ");
Nat_IO.Get (X);
IO.Put ("Y: ");
Nat_IO.Get (Y);
Valid := X > 0 and X <= Max_X and Y > 0 and Y <= Max_Y;
exception
when Constraint_Error =>
Valid := False;
end Get_Coordinates;
-- randomly place bombs
procedure Set_Bombs (Item : in out Grid; Max_X, Max_Y, Count : Positive) is
Generator : Nat_RNG.Generator;
X, Y : Positive;
begin
Nat_RNG.Reset (Generator);
for I in 1 .. Count loop
Placement : loop
X := Nat_RNG.Random (Generator) mod Max_X + 1;
Y := Nat_RNG.Random (Generator) mod Max_Y + 1;
-- redo placement if X:Y already full
if Item (X, Y).Contents = Empty then
Item (X, Y).Contents := Mine;
exit Placement;
end if;
end loop Placement;
end loop;
end Set_Bombs;
Width, Height : Positive;
begin
-- can be dynamically set
Width := 6;
Height := 4;
declare
The_Grid : Grid (1 .. Width, 1 .. Height);
-- 20% bombs
Bomb_Count : Positive := Width * Height * 20 / 100;
Finished : Boolean := False;
Action : Character;
Chosen_X, Chosen_Y : Positive;
Valid_Entry : Boolean;
begin
IO.Put ("Nr. Bombs: ");
Nat_IO.Put (Item => Bomb_Count, Width => 0);
IO.New_Line;
Set_Bombs
(Item => The_Grid,
Max_X => Width,
Max_Y => Height,
Count => Bomb_Count);
while not Finished and Count_Marks (The_Grid) /= Bomb_Count loop
Put (The_Grid);
IO.Put ("Input (c/m/r): ");
IO.Get (Action);
case Action is
when 'c' | 'C' =>
Get_Coordinates
(Max_X => Width,
Max_Y => Height,
X => Chosen_X,
Y => Chosen_Y,
Valid => Valid_Entry);
if Valid_Entry then
Clear
(Item => The_Grid,
X => Chosen_X,
Y => Chosen_Y,
Killed => Finished);
if Finished then
IO.Put_Line ("You stepped on a mine!");
end if;
else
IO.Put_Line ("Invalid input, retry!");
end if;
when 'm' | 'M' =>
Get_Coordinates
(Max_X => Width,
Max_Y => Height,
X => Chosen_X,
Y => Chosen_Y,
Valid => Valid_Entry);
if Valid_Entry then
Mark (Item => The_Grid, X => Chosen_X, Y => Chosen_Y);
else
IO.Put_Line ("Invalid input, retry!");
end if;
when 'r' | 'R' =>
Finished := True;
when others =>
IO.Put_Line ("Invalid input, retry!");
end case;
end loop;
Open_All (The_Grid);
IO.Put_Line
("Solution: (+ = correctly marked, - = incorrectly marked)");
Put (The_Grid);
end;
end Minesweeper; |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #C.2B.2B | C++ | #include <iostream>
#include <vector>
__int128 imax(__int128 a, __int128 b) {
if (a > b) {
return a;
}
return b;
}
__int128 ipow(__int128 b, __int128 n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return b;
}
__int128 res = b;
while (n > 1) {
res *= b;
n--;
}
return res;
}
__int128 imod(__int128 m, __int128 n) {
__int128 result = m % n;
if (result < 0) {
result += n;
}
return result;
}
bool valid(__int128 n) {
if (n < 0) {
return false;
}
while (n > 0) {
int r = n % 10;
if (r > 1) {
return false;
}
n /= 10;
}
return true;
}
__int128 mpm(const __int128 n) {
if (n == 1) {
return 1;
}
std::vector<__int128> L(n * n, 0);
L[0] = 1;
L[1] = 1;
__int128 m, k, r, j;
m = 0;
while (true) {
m++;
if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) {
break;
}
L[m * n + 0] = 1;
for (k = 1; k < n; k++) {
L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]);
}
}
r = ipow(10, m);
k = imod(-r, n);
for (j = m - 1; j >= 1; j--) {
if (L[(j - 1) * n + k] == 0) {
r = r + ipow(10, j);
k = imod(k - ipow(10, j), n);
}
}
if (k == 1) {
r++;
}
return r / n;
}
std::ostream& operator<<(std::ostream& os, __int128 n) {
char buffer[64]; // more then is needed, but is nice and round;
int pos = (sizeof(buffer) / sizeof(char)) - 1;
bool negative = false;
if (n < 0) {
negative = true;
n = -n;
}
buffer[pos] = 0;
while (n > 0) {
int rem = n % 10;
buffer[--pos] = rem + '0';
n /= 10;
}
if (negative) {
buffer[--pos] = '-';
}
return os << &buffer[pos];
}
void test(__int128 n) {
__int128 mult = mpm(n);
if (mult > 0) {
std::cout << n << " * " << mult << " = " << (n * mult) << '\n';
} else {
std::cout << n << "(no solution)\n";
}
}
int main() {
int i;
// 1-10 (inclusive)
for (i = 1; i <= 10; i++) {
test(i);
}
// 95-105 (inclusive)
for (i = 95; i <= 105; i++) {
test(i);
}
test(297);
test(576);
test(594); // needs a larger number type (64 bits signed)
test(891);
test(909);
test(999); // needs a larger number type (87 bits signed)
// optional
test(1998);
test(2079);
test(2251);
test(2277);
// stretch
test(2439);
test(2997);
test(4878);
return 0;
} |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #Dc | Dc | 2988348162058574136915891421498819466320163312926952423791023078876139 2351399303373464486466122544523690094744975233415544072992656881240319 10 40^|p |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #Delphi | Delphi |
program Modular_exponentiation;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Velthuis.BigIntegers;
var
a, b, m: BigInteger;
begin
a := BigInteger.Parse('2988348162058574136915891421498819466320163312926952423791023078876139');
b := BigInteger.Parse('2351399303373464486466122544523690094744975233415544072992656881240319');
m := BigInteger.Pow(10, 40);
Writeln(BigInteger.ModPow(a, b, m).ToString);
readln;
end. |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #jq | jq | def assert($e; $msg): if $e then . else "assertion violation @ \($msg)" | error end;
def is_integer: type=="number" and floor == .;
# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
|
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #Julia | Julia | struct Modulo{T<:Integer} <: Integer
val::T
mod::T
Modulo(n::T, m::T) where T = new{T}(mod(n, m), m)
end
modulo(n::Integer, m::Integer) = Modulo(promote(n, m)...)
Base.show(io::IO, md::Modulo) = print(io, md.val, " (mod $(md.mod))")
Base.convert(::Type{T}, md::Modulo) where T<:Integer = convert(T, md.val)
Base.copy(md::Modulo{T}) where T = Modulo{T}(md.val, md.mod)
Base.:+(md::Modulo) = copy(md)
Base.:-(md::Modulo) = Modulo(md.mod - md.val, md.mod)
for op in (:+, :-, :*, :÷, :^)
@eval function Base.$op(a::Modulo, b::Integer)
val = $op(a.val, b)
return Modulo(mod(val, a.mod), a.mod)
end
@eval Base.$op(a::Integer, b::Modulo) = $op(b, a)
@eval function Base.$op(a::Modulo, b::Modulo)
if a.mod != b.mod throw(InexactError()) end
val = $op(a.val, b.val)
return Modulo(mod(val, a.mod), a.mod)
end
end
f(x) = x ^ 100 + x + 1
@show f(modulo(10, 13)) |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Prolog | Prolog | main:-
between(1, 40, N),
min_mult_dsum(N, M),
writef('%6r', [M]),
(0 is N mod 10 -> nl ; true),
fail.
main.
min_mult_dsum(N, M):-
min_mult_dsum(N, 1, M).
min_mult_dsum(N, M, M):-
P is M * N,
digit_sum(P, N),
!.
min_mult_dsum(N, K, M):-
L is K + 1,
min_mult_dsum(N, L, M).
digit_sum(N, Sum):-
digit_sum(N, Sum, 0).
digit_sum(N, Sum, S1):-
N < 10,
!,
Sum is S1 + N.
digit_sum(N, Sum, S1):-
divmod(N, 10, M, Digit),
S2 is S1 + Digit,
digit_sum(M, Sum, S2). |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #Phix | Phix | with javascript_semantics
sequence cache = {},
ckeys = {}
function ms21(integer n, sequence ds)
integer cdx = find(ds,ckeys)
if cdx=0 then
ckeys = append(ckeys,ds)
cache = append(cache,{{}})
cdx = length(cache)
end if
for i=length(cache[cdx])+1 to n do
integer ms = n+2
sequence steps = {}
for j=1 to length(ds) do -- (d then s)
for k=1 to length(ds[j]) do
integer dsk = ds[j][k],
ok = iff(j=1?remainder(i,dsk)=0:i>dsk)
if ok then
integer m = iff(j=1?i/dsk:i-dsk),
l = length(cache[cdx][m])+1
if ms>l then
ms = l
string step = sprintf("%s%d -> %d",{"/-"[j],dsk,m})
steps = prepend(deep_copy(cache[cdx][m]),step)
end if
end if
end for
end for
if steps = {} then ?9/0 end if
cache[cdx] = append(cache[cdx],steps)
end for
return cache[cdx][n]
end function
procedure show10(sequence ds)
printf(1,"\nWith divisors %v and subtractors %v:\n",ds)
for n=1 to 10 do
sequence steps = ms21(n,ds)
integer ns = length(steps)
string ps = iff(ns=1?"":"s"),
eg = iff(ns=0?"":", eg "&join(steps,","))
printf(1,"%2d takes %d step%s%s\n",{n,ns,ps,eg})
end for
end procedure
procedure maxsteps(sequence ds, integer lim)
integer ms = -1, ls
sequence mc = {}, steps, args
for n=1 to lim do
steps = ms21(n,ds)
ls = length(steps)
if ls>ms then
ms = ls
mc = {n}
elsif ls=ms then
mc &= n
end if
end for
integer lm = length(mc)
string {are,ps,ns} = iff(lm=1?{"is","","s"}:{"are","s",""})
args = { are,lm, ps, lim, ns,ms, shorten(mc,"",3)}
printf(1,"There %s %d number%s below %d that require%s %d steps: %v\n",args)
end procedure
show10({{2,3},{1}})
maxsteps({{2,3},{1}},2000)
maxsteps({{2,3},{1}},20000)
maxsteps({{2,3},{1}},50000)
show10({{2,3},{2}})
maxsteps({{2,3},{2}},2000)
maxsteps({{2,3},{2}},20000)
maxsteps({{2,3},{2}},50000)
|
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Visual_Basic | Visual Basic | 'N-queens problem - non recursive & structured - vb6 - 25/02/2017
Sub n_queens()
Const l = 15 'number of queens
Const b = False 'print option
Dim a(l), s(l), u(4 * l - 2)
Dim n, m, i, j, p, q, r, k, t, z
For i = 1 To UBound(a): a(i) = i: Next i
For n = 1 To l
m = 0
i = 1
j = 0
r = 2 * n - 1
Do
i = i - 1
j = j + 1
p = 0
q = -r
Do
i = i + 1
u(p) = 1
u(q + r) = 1
z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j)
p = i - a(i) + n
q = i + a(i) - 1
s(i) = j
j = i + 1
Loop Until j > n Or u(p) Or u(q + r)
If u(p) = 0 Then
If u(q + r) = 0 Then
m = m + 1 'm: number of solutions
If b Then
Debug.Print "n="; n; "m="; m
For k = 1 To n
For t = 1 To n
Debug.Print IIf(a(n - k + 1) = t, "Q", ".");
Next t
Debug.Print
Next k
End If
End If
End If
j = s(i)
Do While j >= n And i <> 0
Do
z = a(j): a(j) = a(i): a(i) = z 'Swap a(i), a(j)
j = j - 1
Loop Until j < i
i = i - 1
p = i - a(i) + n
q = i + a(i) - 1
j = s(i)
u(p) = 0
u(q + r) = 0
Loop
Loop Until i = 0
Debug.Print n, m 'number of queens, number of solutions
Next n
End Sub 'n_queens |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #UNIX_Shell | UNIX Shell | M()
{
local n
n=$1
if [[ $n -eq 0 ]]; then
echo -n 0
else
echo -n $(( n - $(F $(M $((n-1)) ) ) ))
fi
}
F()
{
local n
n=$1
if [[ $n -eq 0 ]]; then
echo -n 1
else
echo -n $(( n - $(M $(F $((n-1)) ) ) ))
fi
}
for((i=0; i < 20; i++)); do
F $i
echo -n " "
done
echo
for((i=0; i < 20; i++)); do
M $i
echo -n " "
done
echo |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #PARI.2FGP | PARI/GP | for(y=1,12,printf("%2Ps| ",y);for(x=1,12,print1(if(y>x,"",x*y)"\t"));print) |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #AutoHotkey | AutoHotkey | ; Minesweeper.ahk - v1.0.6
; (c) Dec 28, 2008 by derRaphael
; Licensed under the Terms of EUPL 1.0
; Modded by Sobriquet and re-licenced as CeCILL v2
; Modded (again) by Sobriquet and re-licenced as GPL v1.3
#NoEnv
#NoTrayIcon
SetBatchLines,-1
#SingleInstance,Off
/*
[InGameSettings]
*/
Level =Beginner
Width =9
Height =9
MineMax =10
Marks =1
Color =1
Sound =0
BestTimeBeginner =999 seconds Anonymous
BestTimeIntermediate=999 seconds Anonymous
BestTimeExpert =999 seconds Anonymous
; above settings are accessed as variables AND modified by IniWrite - be careful
BlockSize =16
Title =Minesweeper
MineCount =0
mColor =Blue,Green,Red,Purple,Navy,Olive,Maroon,Teal
GameOver =0
TimePassed =0
; Add mines randomly
While (MineCount<MineMax) ; loop as long as neccessary
{
Random,x,1,%Width% ; get random horizontal position
Random,y,1,%Height% ; get random vertical position
If (T_x%x%y%y%!="M") ; only if not already a mine
T_x%x%y%y%:="M" ; assign as mine
,MineCount++ ; keep count
}
Gui +OwnDialogs
;Menu,Tray,Icon,C:\WINDOWS\system32\winmine.exe,1
Menu,GameMenu,Add,&New F2,NewGame
Menu,GameMenu,Add
Menu,GameMenu,Add,&Beginner,LevelMenu
Menu,GameMenu,Add,&Intermediate,LevelMenu
Menu,GameMenu,Add,&Expert,LevelMenu
Menu,GameMenu,Add,&Custom...,CustomMenu
Menu,GameMenu,Add
Menu,GameMenu,Add,&Marks (?),ToggleMenu
Menu,GameMenu,Add,Co&lor,ToggleMenu
Menu,GameMenu,Add,&Sound,ToggleMenu
Menu,GameMenu,Add
Menu,GameMenu,Add,Best &Times...,BestTimesMenu
Menu,GameMenu,Add
Menu,GameMenu,Add,E&xit,GuiClose
Menu,GameMenu,Check,% "&" level . (level="Custom" ? "..." : "")
If (Marks)
Menu,GameMenu,Check,&Marks (?)
If (Color)
Menu,GameMenu,Check,Co&lor
If (Sound)
Menu,GameMenu,Check,&Sound
Menu,HelpMenu,Add,&Contents F1,HelpMenu
Menu,HelpMenu,Add,&Search for Help on...,HelpMenu
Menu,HelpMenu,Add,Using &Help,HelpMenu
Menu,HelpMenu,Add
Menu,HelpMenu,Add,&About Minesweeper...,AboutMenu
Menu,MainMenu,Add,&Game,:GameMenu
Menu,MainMenu,Add,&Help,:HelpMenu
Gui,Menu,MainMenu
Gui,Font,s22,WingDings
Gui,Add,Button,% "h31 w31 y13 gNewGame vNewGame x" Width*BlockSize/2-4,K ; J=Smiley / K=Line / L=Frowny / m=Circle
Gui,Font,s16 Bold,Arial
Gui,Add,Text,% "x13 y14 w45 Border Center vMineCount c" (color ? "Red" : "White"),% SubStr("00" MineCount,-2) ; Remaining mine count
Gui,Add,Text,% "x" Width*BlockSize-34 " y14 w45 Border Center vTimer c" (color ? "Red" : "White"),000 ; Timer
; Buttons
Gui,Font,s11,WingDings
Loop,% Height ; iterate vertically
{
y:=A_Index ; remember line
Loop,% Width ; set covers
{
x:=A_Index
Gui,Add,Button,% "vB_x" x "y" y " w" BlockSize ; mark variable / width
. " h" BlockSize " " (x = 1 ; height / if 1st block
? "x" 12 " y" y*BlockSize+39 ; fix vertical offset
: "yp x+0") ; otherwise stay inline /w prev. box
}
}
; Show Gui
Gui,Show,% "w" ((Width>9 ? Width : 9))*BlockSize+24 " h" Height*BlockSize+68,%Title%
OnMessage(0x53,"WM_HELP") ; invoke Help handling for tooltips
Return ;--------------------------------------------------------; End of auto-execute section
#IfWinActive Minesweeper ahk_class AutoHotkeyGUI ; variable %title% not supported
StartGame(x,y) {
Global
If (TimePassed)
Return
If (T_x%x%y%y%="M") ; we'll save you this time
{
T_x%x%y%y%:="" ; remove this mine
Loop,% Height
{
y:=A_Index
Loop,% Width
{
x:=A_Index
If ( T_x%x%y%y%!="M") ; add it to first available non-mine square
T_x%x%y%y%:="M"
,break:=1
IfEqual,break,1,Break
}
IfEqual,break,1,Break
}
}
Loop,% Height ; iterate over height
{
y:=A_Index
Loop,% Width ; iterate over width
{
x:=A_Index
Gui,Font
If (T_x%x%y%y%="M") { ; check for mine
Gui,Font,s11,WingDings
hColor:="Black" ; set color for text
} Else {
Loop,3 { ; loop over neighbors: three columns vertically
ty:=y-2+A_Index ; calculate top offset
Loop,3 { ; and three horizontally
tx:=x-2+A_Index ; calculate left offset
If (T_x%tx%y%ty%="M") ; no mine and inbound
T_x%x%y%y%++ ; update hint txt
}
}
Gui,Font,s11 Bold,Courier New Bold
If (Color)
Loop,Parse,mColor,`, ; find color
If (T_x%x%y%y% = A_Index) { ; hinttxt to color
hColor:=A_LoopField ; set color for text
Break
}
Else hColor:="Black"
}
Gui,Add,Text,% "c" hColor " Border +Center vT_x" x "y" y ; set color / variable
. " w" BlockSize " h" BlockSize " " (x = 1 ; width / height / if 1st block
? "x" 12 " y" y*BlockSize+39 ; fix vertical position
: "yp x+0") ; otherwise align to previous box
,% T_x%x%y%y% ; M is WingDings for mine
GuiControl,Hide,T_x%x%y%y%
}
}
GuiControl,,Timer,% "00" . TimePassed:=1
SetTimer,UpdateTimer,1000 ; start timer
If (Sound)
SoundPlay,C:\WINDOWS\media\chord.wav
}
GuiSize:
If (TimePassed)
SetTimer,UpdateTimer,On ; for cheat below
Return
UpdateTimer: ; timer
GuiControl,,Timer,% (++TimePassed < 999) ? SubStr("00" TimePassed,-2) : 999
If (Sound)
SoundPlay,C:\WINDOWS\media\chord.wav
Return
Check(x,y){
Global
If (GameOver || B_x%x%y%y% != "" ; the game is over / prevent click on flagged squares and already-opened squares
|| x<1 || x>Width || y<1 || y>Height) ; do not check neighbor on illegal squares
Return
If (T_x%x%y%y%="") { ; empty field?
CheckNeighbor(x,y) ; uncover it and any neighbours
} Else If (T_x%x%y%y% != "M") { ; no Mine, ok?
GuiControl,Hide,B_x%x%y%y% ; hide covering button
GuiControl,Show,T_x%x%y%y%
B_x%x%y%y%:=1 ; remember we been here
UpdateChecks()
} Else { ; ewww ... it's a mine!
SetTimer,UpdateTimer,Off ; kill timer
GuiControl,,T_x%x%y%y%,N ; set to Jolly Roger=N to mark death location
GuiControl,,NewGame,L ; set Smiley Btn to Frown=L
RevealAll()
If (Sound) ; do we sound?
If (FileExist("C:\Program Files\Microsoft Office\Office12\MEDIA\Explode.wav"))
SoundPlay,C:\Program Files\Microsoft Office\Office12\MEDIA\Explode.wav
Else
SoundPlay,C:\WINDOWS\Media\notify.wav
}
}
CheckNeighbor(x,y) { ; This function checks neighbours of the clicked
Global ; field and uncovers empty fields plus adjacent hint fields
If (GameOver || B_x%x%y%y%!="")
Return
GuiControl,Hide,B_x%x%y%y% ; uncover it
GuiControl,Show,T_x%x%y%y%
B_x%x%y%y%:=1 ; remember it
UpdateChecks()
If (T_x%x%y%y%!="") ; is neighbour an nonchecked 0 value field?
Return
If (y-1>=1) ; check upper neighbour
CheckNeighbor(x,y-1)
If (y+1<=Height) ; check lower neighbour
CheckNeighbor(x,y+1)
If (x-1>=1) ; check left neighbour
CheckNeighbor(x-1,y)
If (x+1<=Width) ; check right neighbour
CheckNeighbor(x+1,y)
If (x-1>=1 && y-1>=1) ; check corner neighbour
CheckNeighbor(x-1,y-1)
If (x-1>=1 && y+1<=Height) ; check corner neighbour
CheckNeighbor(x-1,y+1)
If (x+1<=Width && y-1>=1) ; check corner neighbour
CheckNeighbor(x+1,y-1)
If (x+1<=Width && y+1<=Height) ; check corner neighbour
CheckNeighbor(x+1,y+1)
}
UpdateChecks() {
Global
MineCount:=MineMax, Die1:=Die2:=0
Loop,% Height
{
y:=A_Index
Loop,% Width
{
x:=A_Index
If (B_x%x%y%y%="O")
MineCount--
If (T_x%x%y%y%="M" && B_x%x%y%y%!="O") || (T_x%x%y%y%!="M" && B_x%x%y%y%="O")
Die1++
If (B_x%x%y%y%="" && T_x%x%y%y%!="M")
Die2++
}
}
GuiControl,,MineCount,% SubStr("00" MineCount,-2)
If (Die1 && Die2)
Return ; only get past here if flags+untouched squares match mines perfectly
SetTimer,UpdateTimer,Off ; game won - kill timer
GuiControl,,NewGame,J ; set Smiley Btn to Smile=J
RevealAll()
If (Sound) ; play sound
SoundPlay,C:\WINDOWS\Media\tada.wav
If (level!="Custom" && TimePassed < SubStr(BestTime%level%,1,InStr(BestTime%level%," ")-1) )
{
InputBox,name,Congratulations!,You have the fastest time`nfor level %level%.`nPlease enter your name.`n,,,,,,,,%A_UserName%
If (name && !ErrorLevel)
{
BestTime%level%:=%TimePassed% seconds %name%
IniWrite,BestTime%level%,%A_ScriptFullPath%,InGameSettings,BestTime%level%
}
}
}
RevealAll(){
Global
Loop,% Height ; uncover all
{
y:=A_Index
Loop,% Width
{
x:=A_Index
If(T_x%x%y%y%="M")
{
GuiControl,Hide,B_x%x%y%y%
GuiControl,Show,T_x%x%y%y%
}
}
}
GameOver:=True ; remember the game's over to block clicks
}
~F2::NewGame()
NewGame(){
NewGame:
Reload
ExitApp
}
LevelMenu:
If (A_ThisMenuItem="&Beginner")
level:="Beginner", Width:=9, Height:=9, MineMax:=10
Else If (A_ThisMenuItem="&Intermediate")
level:="Intermediate", Width:=16, Height:=16, MineMax:=40
Else If (A_ThisMenuItem="&Expert")
level:="Expert", Width:=30, Height:=16, MineMax:=99
IniWrite,%level%,%A_ScriptFullPath%,InGameSettings,level
IniWrite,%Width%,%A_ScriptFullPath%,InGameSettings,Width
IniWrite,%Height%,%A_ScriptFullPath%,InGameSettings,Height
IniWrite,%MineMax%,%A_ScriptFullPath%,InGameSettings,MineMax
IniWrite,%Marks%,%A_ScriptFullPath%,InGameSettings,Marks
IniWrite,%Sound%,%A_ScriptFullPath%,InGameSettings,Sound
IniWrite,%Color%,%A_ScriptFullPath%,InGameSettings,Color
NewGame()
Return
CustomMenu: ; label for setting window
Gui,2:+Owner1 ; make Gui#2 owned by gameWindow
Gui,2:Default ; set to default
Gui,1:+Disabled ; disable gameWindow
Gui,-MinimizeBox +E0x00000400
Gui,Add,Text,x15 y36 w38 h16,&Height:
Gui,Add,Edit,Number x60 y33 w38 h20 vHeight HwndHwndHeight,%Height% ; use inGame settings
Gui,Add,Text,x15 y60 w38 h16,&Width:
Gui,Add,Edit,Number x60 y57 w38 h20 vWidth HwndHwndWidth,%Width%
Gui,Add,Text,x15 y85 w38 h16,&Mines:
Gui,Add,Edit,Number x60 y81 w38 h20 vMineMax HwndHwndMines,%MineMax%
Gui,Add,Button,x120 y33 w60 h26 Default HwndHwndOK,OK
Gui,Add,Button,x120 y75 w60 h26 g2GuiClose HwndHwndCancel,Cancel ; jump directly to 2GuiClose label
Gui,Show,w195 h138,Custom Field
Return
2ButtonOK: ; label for OK button in settings window
Gui,2:Submit,NoHide
level:="Custom"
MineMax:=MineMax<10 ? 10 : MineMax>((Width-1)*(Height-1)) ? ((Width-1)*(Height-1)) : MineMax
Width:=Width<9 ? 9 : Width>30 ? 30 : Width
Height:=Height<9 ? 9 : Height>24 ? 24 : Height
GoSub,LevelMenu
Return
2GuiClose:
2GuiEscape:
Gui,1:-Disabled ; reset GUI status and destroy setting window
Gui,1:Default
Gui,2:Destroy
Return
ToggleMenu:
Toggle:=RegExReplace(RegExReplace(A_ThisMenuItem,"\s.*"),"&")
temp:=%Toggle%
%Toggle%:=!%Toggle%
Menu,GameMenu,ToggleCheck,%A_ThisMenuItem%
IniWrite,% %Toggle%,%A_ScriptFullPath%,InGameSettings,%Toggle%
Return
BestTimesMenu:
Gui,3:+Owner1
Gui,3:Default
Gui,1:+Disabled
Gui,-MinimizeBox +E0x00000400
Gui,Add,Text,x15 y22 w250 vBestTimeBeginner HwndHwndBTB,Beginner: %BestTimeBeginner%
Gui,Add,Text,x15 y38 w250 vBestTimeIntermediate HwndHwndBTI,Intermediate: %BestTimeIntermediate%
Gui,Add,Text,x15 y54 w250 vBestTimeExpert HwndHwndBTE,Expert: %BestTimeExpert%
Gui,Add,Button,x38 y89 w75 h20 HwndHwndRS,&Reset Scores
Gui,Add,Button,x173 y89 w45 h20 Default HwndHwndOK,OK
Gui,Show,w255 h122,Fastest Mine Sweepers
Return
3ButtonResetScores:
BestTimeBeginner =999 seconds Anonymous
BestTimeIntermediate=999 seconds Anonymous
BestTimeExpert =999 seconds Anonymous
GuiControl,,BestTimeBeginner,Beginner: %BestTimeBeginner%`nIntermediate: %BestTimeIntermediate%`nExpert: %BestTimeExpert%
GuiControl,,BestTimeIntermediate,Intermediate: %BestTimeIntermediate%`nExpert: %BestTimeExpert%
GuiControl,,BestTimeExpert,Expert: %BestTimeExpert%
IniWrite,%BestTimeBeginner%,%A_ScriptFullPath%,InGameSettings,BestTimeBeginner
IniWrite,%BestTimeIntermediate%,%A_ScriptFullPath%,InGameSettings,BestTimeIntermediate
IniWrite,%BestTimeExpert%,%A_ScriptFullPath%,InGameSettings,BestTimeExpert
3GuiEscape: ; fall through:
3GuiClose:
3ButtonOK:
Gui,1:-Disabled ; reset GUI status and destroy setting window
Gui,1:Default
Gui,3:Destroy
Return
^q::
GuiClose:
ExitApp
HelpMenu:
;Run C:\WINDOWS\Help\winmine.chm
Return
AboutMenu:
Msgbox,64,About Minesweeper,AutoHotkey (r) Minesweeper`nVersion 1.0.6`nCopyright (c) 2014`nby derRaphael and Sobriquet
Return
~LButton::
~!LButton::
~^LButton::
~#LButton::
Tooltip
If (GetKeyState("RButton","P"))
Return
If A_OSVersion not in WIN_2003,WIN_XP,WIN_2000,WIN_NT4,WIN_95,WIN_98,WIN_ME
If(A_PriorHotkey="~*LButton Up" && A_TimeSincePriorHotkey<100)
GoTo,*MButton Up ; invoke MButton handling for autofill on left double-click in vista+
If (GameOver)
Return
MouseGetPos,,y
If (y>47)
GuiControl,,NewGame,m
Return
~*LButton Up::
If (GetKeyState("RButton","P"))
GoTo,*MButton Up
If (GameOver)
Return
GuiControl,,NewGame,K
control:=GetControlFromClassNN(), NumX:=NumY:=0
RegExMatch(control,"Si)T_x(?P<X>\d+)y(?P<Y>\d+)",Num) ; get Position
StartGame(NumX,NumY) ; start game if neccessary
Check(NumX,NumY)
Return
+LButton::
*MButton::
Tooltip
If (GameOver)
Return
MouseGetPos,,y
If (y>47)
GuiControl,,NewGame,m
Return
+LButton Up::
*MButton Up::
If (GameOver)
Return
GuiControl,,NewGame,K
StartGame(NumX,NumY) ; start game if neccessary
If (GetKeyState("Esc","P"))
{
SetTimer,UpdateTimer,Off
Return
}
control:=GetControlFromClassNN(), NumX:=NumY:=0
RegExMatch(control,"Si)T_x(?P<X>\d+)y(?P<y>\d+)",Num)
If ( !NumX || !NumY || B_x%NumX%y%NumY%!=1)
Return
temp:=0
Loop,3 { ; loop over neighbors: three columns vertically
ty:=NumY-2+A_Index ; calculate top offset
Loop,3 { ; and three horizontally
tx:=NumX-2+A_Index ; calculate left offset
If (B_x%tx%y%ty% = "O") ; count number of marked mines around position
temp++
}
}
If (temp=T_x%NumX%y%NumY%)
Loop,3 { ; loop over neighbors: three columns vertically
ty:=NumY-2+A_Index ; calculate top offset
Loop,3 { ; and three horizontally
tx:=NumX-2+A_Index ; calculate left offset
Check(tx,ty) ; simulate user clicking on each surrounding square
}
}
Return
~*RButton::
If (GameOver || GetKeyState("LButton","P"))
Return
control:=GetControlFromClassNN(), NumX:=NumY:=0
RegExMatch(control,"Si)T_x(?P<X>\d+)y(?P<y>\d+)",Num) ; grab 'em
If ( !NumX || !NumY || B_x%NumX%y%NumY%=1)
Return
StartGame(NumX,NumY) ; start counter if neccessary
B_x%NumX%y%NumY%:=(B_x%NumX%y%NumY%="" ? "O" : (B_x%NumX%y%NumY%="O" && Marks=1 ? "I" : ""))
GuiControl,,B_x%NumX%y%NumY%,% B_x%NumX%y%NumY%
UpdateChecks()
Return
~*RButton Up::
If (GetKeyState("LButton","P"))
GoTo,*MButton Up
Return
GetControlFromClassNN(){
Global width
MouseGetPos,,,,control
If (SubStr(control,1,6)="Button")
NumX:=mod(SubStr(control,7)-2,width)+1,NumY:=(SubStr(control,7)-2)//width+1
Else If (SubStr(control,1,6)="Static")
NumX:=mod(SubStr(control,7)-3,width)+1,NumY:=(SubStr(control,7)-3)//width+1
Return "T_x" NumX "y" NumY
}
WM_HELP(_,_lphi)
{
Global
hItemHandle:=NumGet(_lphi+0,12)
If (hItemHandle=HwndBTB || hItemHandle=HwndBTI || hItemHandle=HwndBTE)
ToolTip Displays a player's best game time`, and the player's name`, for`neach level of play: Beginner`, Intermediate`, and Expert.
Else If (hItemHandle=HwndRS)
ToolTip Click to clear the current high scores.
Else If (hItemHandle=HwndOK)
ToolTip Closes the dialog box and saves any changes you`nhave made.
Else If (hItemHandle=HwndCancel)
ToolTip Closes the dialog box without saving any changes you have`nmade.
Else If (hItemHandle=HwndHeight)
ToolTip Specifies the number of vertical squares on the`nplaying field.
Else If (hItemHandle=HwndWidth)
ToolTip Specifies the number of horizontal squares on the`nplaying field.
Else If (hItemHandle=HwndMines)
ToolTip Specifies the number of mines to be placed on the`nplaying field.
}
:*?B0:xyzzy:: ; cheat
KeyWait,Shift,D T1 ; 1 sec grace period to press shift
If (ErrorLevel)
Return
While,GetKeyState("Shift","P")
{
control:=GetControlFromClassNN()
If (%control% = "M")
SplashImage,,B X0 Y0 W1 H1 CW000000 ; black pixel
Else
SplashImage,,B X0 Y0 W1 H1 CWFFFFFF ; white pixel
Sleep 100
}
SplashImage,Off
Return
/*
Version History
=================
Dec 29, 2008
1.0.0 Initial Release
1.0.1 BugFix
- Game Restart Issues mentioned by Frankie
- Guess count fixup I
- Startbehaviour of game (time didnt start when 1st click was RMB Guess)
Dec 30, 2008
1.0.2 BugFix
- Field Size Control vs Max MineCount / mentioned by °digit° / IsNull
1.0.3 BugFix
- Guess count fixup II mentioned by °digit°
- Corrected count when 'guessed' field uncovered
Dec 31, 2008
1.0.4 BugFix
- Fix of Min Field & MineSettings
Mar 7, 2014
1.0.5 AddFeatures
- Make appearance more like original
- Make first click always safe
- Re-license as CeCILL v2
Mar 8, 2014
1.0.6 AddFeatures
- Add cheat code
- Add middle-button shortcut
- Re-license as GPL 1.3
*/ |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #D | D | import std.algorithm;
import std.array;
import std.bigint;
import std.range;
import std.stdio;
void main() {
foreach (n; chain(iota(1, 11), iota(95, 106), only(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878))) {
auto result = getA004290(n);
writefln("A004290(%d) = %s = %s * %s", n, result, n, result / n);
}
}
BigInt getA004290(int n) {
if (n == 1) {
return BigInt(1);
}
auto L = uninitializedArray!(int[][])(n, n);
foreach (i; 2..n) {
L[0][i] = 0;
}
L[0][0] = 1;
L[0][1] = 1;
int m = 0;
BigInt ten = 10;
BigInt nBi = n;
while (true) {
m++;
if (L[m - 1][mod(-(ten ^^ m), nBi).toInt] == 1) {
break;
}
L[m][0] = 1;
foreach (k; 1..n) {
L[m][k] = max(L[m - 1][k], L[m - 1][mod(BigInt(k) - (ten ^^ m), nBi).toInt]);
}
}
auto r = ten ^^ m;
auto k = mod(-r, nBi);
foreach_reverse (j; 1 .. m) {
assert(j != m);
if (L[j - 1][k.toInt] == 0) {
r += ten ^^ j;
k = mod(k - (ten ^^ j), nBi);
}
}
if (k == 1) {
r++;
}
return r;
}
BigInt mod(BigInt m, BigInt n) {
auto result = m % n;
if (result < 0) {
result += n;
}
return result;
} |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #EchoLisp | EchoLisp |
(lib 'bigint)
(define a 2988348162058574136915891421498819466320163312926952423791023078876139)
(define b 2351399303373464486466122544523690094744975233415544072992656881240319)
(define m 1e40)
(powmod a b m)
→ 1527229998585248450016808958343740453059
;; powmod is a native function
;; it could be defined as follows :
(define (xpowmod base exp mod)
(define result 1)
(while ( !zero? exp)
(when (odd? exp) (set! result (% (* result base) mod)))
(/= exp 2)
(set! base (% (* base base) mod)))
result)
(xpowmod a b m)
→ 1527229998585248450016808958343740453059
|
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #Emacs_Lisp | Emacs Lisp | (let ((a "2988348162058574136915891421498819466320163312926952423791023078876139")
(b "2351399303373464486466122544523690094744975233415544072992656881240319"))
;; "$ ^ $$ mod (10 ^ 40)" performs modular exponentiation.
;; "unpack(-5, x)_1" unpacks the integer from the modulo form.
(message "%s" (calc-eval "unpack(-5, $ ^ $$ mod (10 ^ 40))_1" nil a b))) |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #Kotlin | Kotlin | // version 1.1.3
interface Ring<T> {
operator fun plus(other: Ring<T>): Ring<T>
operator fun times(other: Ring<T>): Ring<T>
val value: Int
val one: Ring<T>
}
fun <T> Ring<T>.pow(p: Int): Ring<T> {
require(p >= 0)
var pp = p
var pwr = this.one
while (pp-- > 0) pwr *= this
return pwr
}
class ModInt(override val value: Int, val modulo: Int): Ring<ModInt> {
override operator fun plus(other: Ring<ModInt>): ModInt {
require(other is ModInt && modulo == other.modulo)
return ModInt((value + other.value) % modulo, modulo)
}
override operator fun times(other: Ring<ModInt>): ModInt {
require(other is ModInt && modulo == other.modulo)
return ModInt((value * other.value) % modulo, modulo)
}
override val one get() = ModInt(1, modulo)
override fun toString() = "ModInt($value, $modulo)"
}
fun <T> f(x: Ring<T>): Ring<T> = x.pow(100) + x + x.one
fun main(args: Array<String>) {
val x = ModInt(10, 13)
val y = f(x)
println("x ^ 100 + x + 1 for x == ModInt(10, 13) is $y")
} |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Python | Python | '''A131382'''
from itertools import count, islice
# a131382 :: [Int]
def a131382():
'''An infinite series of the terms of A131382'''
return (
elemIndex(x)(
productDigitSums(x)
) for x in count(1)
)
# productDigitSums :: Int -> [Int]
def productDigitSums(n):
'''The sum of the decimal digits of n'''
return (digitSum(n * x) for x in count(0))
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''First 40 terms of A131382'''
print(
table(10)([
str(x) for x in islice(
a131382(),
40
)
])
)
# ----------------------- GENERIC ------------------------
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n, subdividing the
contents of xs. Where the length of xs is not evenly
divisible, the final list will be shorter than n.
'''
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
# digitSum :: Int -> Int
def digitSum(n):
'''The sum of the digital digits of n.
'''
return sum(int(x) for x in list(str(n)))
# elemIndex :: a -> [a] -> (None | Int)
def elemIndex(x):
'''Just the first index of x in xs,
or None if no elements match.
'''
def go(xs):
try:
return next(
i for i, v in enumerate(xs) if x == v
)
except StopIteration:
return None
return go
# table :: Int -> [String] -> String
def table(n):
'''A list of strings formatted as
right-justified rows of n columns.
'''
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
# MAIN ---
if __name__ == '__main__':
main() |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #Python | Python |
from functools import lru_cache
#%%
DIVS = {2, 3}
SUBS = {1}
class Minrec():
"Recursive, memoised minimised steps to 1"
def __init__(self, divs=DIVS, subs=SUBS):
self.divs, self.subs = divs, subs
@lru_cache(maxsize=None)
def _minrec(self, n):
"Recursive, memoised"
if n == 1:
return 0, ['=1']
possibles = {}
for d in self.divs:
if n % d == 0:
possibles[f'/{d}=>{n // d:2}'] = self._minrec(n // d)
for s in self.subs:
if n > s:
possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)
thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])
ret = 1 + count, [thiskind] + otherkinds
return ret
def __call__(self, n):
"Recursive, memoised"
ans = self._minrec(n)[1][:-1]
return len(ans), ans
if __name__ == '__main__':
for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:
minrec = Minrec(DIVS, SUBS)
print('\nMINIMUM STEPS TO 1: Recursive algorithm')
print(' Possible divisors: ', DIVS)
print(' Possible decrements:', SUBS)
for n in range(1, 11):
steps, how = minrec(n)
print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how))
upto = 2000
print(f'\n Those numbers up to {upto} that take the maximum, "minimal steps down to 1":')
stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))
mx = stepn[-1][0]
ans = [x[1] for x in stepn if x[0] == mx]
print(' Taking', mx, f'steps is/are the {len(ans)} numbers:',
', '.join(str(n) for n in sorted(ans)))
#print(minrec._minrec.cache_info())
print() |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Visual_Basic_.NET | Visual Basic .NET | 'N-queens problem - non recursive & structured - vb.net - 26/02/2017
Module Mod_n_queens
Sub n_queens()
Const l = 15 'number of queens
Const b = False 'print option
Dim a(l), s(l), u(4 * l - 2)
Dim n, m, i, j, p, q, r, k, t, z
Dim w As String
For i = 1 To UBound(a) : a(i) = i : Next i
For n = 1 To l
m = 0
i = 1
j = 0
r = 2 * n - 1
Do
i = i - 1
j = j + 1
p = 0
q = -r
Do
i = i + 1
u(p) = 1
u(q + r) = 1
z = a(j) : a(j) = a(i) : a(i) = z 'Swap a(i), a(j)
p = i - a(i) + n
q = i + a(i) - 1
s(i) = j
j = i + 1
Loop Until j > n Or u(p) Or u(q + r)
If u(p) = 0 Then
If u(q + r) = 0 Then
m = m + 1 'm: number of solutions
If b Then
Debug.Print("n=" & n & " m=" & m) : w = ""
For k = 1 To n
For t = 1 To n
w = w & If(a(n - k + 1) = t, "Q", ".")
Next t
Debug.Print(w)
Next k
End If
End If
End If
j = s(i)
Do While j >= n And i <> 0
Do
z = a(j) : a(j) = a(i) : a(i) = z 'Swap a(i), a(j)
j = j - 1
Loop Until j < i
i = i - 1
p = i - a(i) + n
q = i + a(i) - 1
j = s(i)
u(p) = 0
u(q + r) = 0
Loop
Loop Until i = 0
Debug.Print(n & vbTab & m) 'number of queens, number of solutions
Next n
End Sub 'n_queens
End Module |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Ursala | Ursala | #import std
#import nat
#import sol
#fix general_function_fixer 0
F = ~&?\1! difference^/~& M+ F+ predecessor
M = ~&?\0! difference^/~& F+ M+ predecessor |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Pascal | Pascal | our $max = 12;
our $width = length($max**2) + 1;
printf "%*s", $width, $_ foreach 'x|', 1..$max;
print "\n", '-' x ($width - 1), '+', '-' x ($max*$width), "\n";
foreach my $i (1..$max) {
printf "%*s", $width, $_
foreach "$i|", map { $_ >= $i and $_*$i } 1..$max;
print "\n";
} |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #BASIC256 | BASIC256 | N = 6 : M = 5 : H = 25 : P = 0.2
fastgraphics
graphsize N*H,(M+1)*H
font "Arial",H/2+1,75
dim f(N,M) # 1 open, 2 mine, 4 expected mine
dim s(N,M) # count of mines in a neighborhood
trian1 = {1,1,H-1,1,H-1,H-1} : trian2 = {1,1,1,H-1,H-1,H-1}
mine = {2,2, H/2,H/2-2, H-2,2, H/2+2,H/2, H-2,H-2, H/2,H/2+2, 2,H-2, H/2-2,H/2}
flag = {H/2-1,3, H/2+1,3, H-4,H/5, H/2+1,H*2/5, H/2+1,H*0.9-2, H*0.8,H-2, H*0.2,H-2, H/2-1,H*0.9-2}
mines = int(N*M*P) : k = mines : act = 0
while k>0
i = int(rand*N) : j = int(rand*M)
if not f[i,j] then
f[i,j] = 2 : k = k - 1 # set mine
s[i,j] = s[i,j] + 1 : gosub adj # count it
end if
end while
togo = M*N-mines : over = 0 : act = 1
gosub redraw
while not over
clickclear
while not clickb
pause 0.01
end while
i = int(clickx/H) : j = int(clicky/H)
if i<N and j<M then
if clickb=1 then
if not (f[i,j]&4) then ai = i : aj = j : gosub opencell
if not s[i,j] then gosub adj
else
if not (f[i,j]&1) then
if f[i,j]&4 then mines = mines+1
if not (f[i,j]&4) then mines = mines-1
f[i,j] = (f[i,j]&~4)|(~f[i,j]&4)
end if
end if
if not (togo or mines) then over = 1
gosub redraw
end if
end while
imgsave "Minesweeper_game_BASIC-256.png", "PNG"
end
redraw:
for i = 0 to N-1
for j = 0 to M-1
if over=-1 and f[i,j]&2 then f[i,j] = f[i,j]|1
gosub drawcell
next j
next i
# Counter
color (32,32,32) : rect 0,M*H,N*H,H
color white : x = 5 : y = M*H+H*0.05
if not over then text x,y,"Mines: " + mines
if over=1 then text x,y,"You won!"
if over=-1 then text x,y,"You lost"
refresh
return
drawcell:
color darkgrey
rect i*H,j*H,H,H
if f[i,j]&1=0 then # closed
color black : stamp i*H,j*H,trian1
color white : stamp i*H,j*H,trian2
color grey : rect i*H+2,j*H+2,H-4,H-4
if f[i,j]&4 then color blue : stamp i*H,j*H,flag
else
color 192,192,192 : rect i*H+1,j*H+1,H-2,H-2
# Draw
if f[i,j]&2 then # mine
if not (f[i,j]&4) then color red
if f[i,j]&4 then color darkgreen
circle i*H+H/2,j*H+H/2,H/5 : stamp i*H,j*H,mine
else
if s[i,j] then color (32,32,32) : text i*H+H/3,j*H+1,s[i,j]
end if
end if
return
adj:
aj = j-1
if j and i then ai = i-1 : gosub adjact
if j then ai = i : gosub adjact
if j and i<N-1 then ai = i+1 : gosub adjact
aj = j
if i then ai = i-1 : gosub adjact
if i<N-1 then ai = i+1 : gosub adjact
aj = j+1
if j<M-1 and i then ai = i-1 : gosub adjact
if j<M-1 then ai = i : gosub adjact
if j<M-1 and i<N-1 then ai = i+1 : gosub adjact
return
adjact:
if not act then s[ai,aj] = s[ai,aj]+1 : return
if act then gosub opencell : return
opencell:
if not (f[ai,aj]&1) then
f[ai,aj] = f[ai,aj]|1
togo = togo-1
end if
if f[ai,aj]&2 then over = -1
return |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #F.23 | F# |
// Minimum positive multiple in base 10 using only 0 and 1. Nigel Galloway: March 9th., 2020
let rec fN Σ n i g e l=if l=1||n=1 then Σ+1I else
match (10*i)%l with
g when n=g->Σ+10I**e
|i->match Set.map(fun n->(n+i)%l) g with
ф when ф.Contains n->fN (Σ+10I**e) ((l+n-i)%l) 1 (set[1]) 1 l
|ф->fN Σ n i (Set.unionMany [set[i];g;ф]) (e+1) l
let B10=fN 0I 0 1 (set[1]) 1
List.concat[[1..10];[95..105];[297;576;594;891;909;999;1998;2079;2251;2277;2439;2997;4878]]
|>List.iter(fun n->let g=B10 n in printfn "%d * %A = %A" n (g/bigint(n)) g)
|
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #Erlang | Erlang |
%%% For details of the algorithms used see
%%% https://en.wikipedia.org/wiki/Modular_exponentiation
-module modexp_rosetta.
-export [mod_exp/3,binary_exp/2,test/0].
mod_exp(Base,Exp,Mod) when
is_integer(Base),
is_integer(Exp),
is_integer(Mod),
Base > 0,
Exp > 0,
Mod > 0 ->
binary_exp_mod(Base,Exp,Mod).
binary_exp(Base,Exponent) ->
binary_exp(Base,Exponent,1).
binary_exp(_,0,Result) ->
Result;
binary_exp(Base,Exponent,Acc) ->
binary_exp(Base*Base,Exponent bsr 1,Acc * exp_factor(Base,Exponent)).
binary_exp_mod(Base,Exponent,Mod) ->
binary_exp_mod(Base rem Mod,Exponent,Mod,1).
binary_exp_mod(_,0,_,Result) ->
Result;
binary_exp_mod(Base,Exponent,Mod,Acc) ->
binary_exp_mod((Base*Base) rem Mod,
Exponent bsr 1,Mod,(Acc * exp_factor(Base,Exponent))rem Mod).
exp_factor(_,0) ->
1;
exp_factor(Base,1) ->
Base;
exp_factor(Base,Exponent) ->
exp_factor(Base,Exponent band 1).
test() ->
445 = mod_exp(4,13,497),
%% Rosetta code example:
mod_exp(2988348162058574136915891421498819466320163312926952423791023078876139,
2351399303373464486466122544523690094744975233415544072992656881240319,
binary_exp(10,40)).
|
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #Lua | Lua | function make(value, modulo)
local v = value % modulo
local tbl = {value=v, modulo=modulo}
local mt = {
__add = function(lhs, rhs)
if type(lhs) == "table" then
if type(rhs) == "table" then
if lhs.modulo ~= rhs.modulo then
error("Cannot add rings with different modulus")
end
return make(lhs.value + rhs.value, lhs.modulo)
else
return make(lhs.value + rhs, lhs.modulo)
end
else
error("lhs is not a table in +")
end
end,
__mul = function(lhs, rhs)
if lhs.modulo ~= rhs.modulo then
error("Cannot multiply rings with different modulus")
end
return make(lhs.value * rhs.value, lhs.modulo)
end,
__pow = function(b,p)
if p<0 then
error("p must be zero or greater")
end
local pp = p
local pwr = make(1, b.modulo)
while pp > 0 do
pp = pp - 1
pwr = pwr * b
end
return pwr
end,
__concat = function(lhs, rhs)
if type(lhs) == "table" and type(rhs) == "string" then
return "ModInt("..lhs.value..", "..lhs.modulo..")"..rhs
elseif type(lhs) == "string" and type(rhs) == "table" then
return lhs.."ModInt("..rhs.value..", "..rhs.modulo..")"
else
return "todo"
end
end
}
setmetatable(tbl, mt)
return tbl
end
function func(x)
return x ^ 100 + x + 1
end
-- main
local x = make(10, 13)
local y = func(x)
print("x ^ 100 + x + 1 for "..x.." is "..y) |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Raku | Raku | sub min-mult-dsum ($n) { (1..∞).first: (* × $n).comb.sum == $n }
say .fmt("%2d: ") ~ .&min-mult-dsum for flat 1..40, 41..70; |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Sidef | Sidef | var e = Enumerator({|f|
for n in (1..Inf) {
var k = 0
while (k.sumdigits != n) {
k += n
}
f(k/n)
}
})
var N = 60
var A = []
e.each {|v|
A << v
say A.splice.map { '%7s' % _ }.join(' ') if (A.len == 10)
break if (--N <= 0)
} |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #Raku | Raku | use Lingua::EN::Numbers;
for [2,3], 1, 2000,
[2,3], 1, 50000,
[2,3], 2, 2000,
[2,3], 2, 50000
-> @div, $sub, $limit {
my %min = 1 => {:op(''), :v(1), :s(0)};
(2..$limit).map( -> $n {
my @ops;
@ops.push: ($n / $_, "/$_") if $n %% $_ for @div;
@ops.push: ($n - $sub, "-$sub") if $n > $sub;
my $op = @ops.min( {%min{.[0]}<s>} );
%min{$n} = {:op($op[1]), :v($op[0]), :s(1 + %min{$op[0]}<s>)};
});
my $max = %min.max( {.value<s>} ).value<s>;
my @max = %min.grep( {.value.<s> == $max} )».key.sort(+*);
if $limit == 2000 {
say "\nDivisors: {@div.perl}, subtract: $sub";
steps(1..10);
}
say "\nUp to {comma $limit} found {+@max} number{+@max == 1 ?? '' !! 's'} " ~
"that require{+@max == 1 ?? 's' !! ''} at least $max steps.";
steps(@max);
sub steps (*@list) {
for @list -> $m {
my @op;
my $n = $m;
while %min{$n}<s> {
@op.push: "{%min{$n}<op>}=>{%min{$n}<v>}";
$n = %min{$n}<v>;
}
say "($m) {%min{$m}<s>} steps: ", @op.join(', ');
}
}
} |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Wart | Wart | def (nqueens n queens)
prn "step: " queens # show progress
if (len.queens = n)
prn "solution! " queens
# else
let row (if queens (queens.zero.zero + 1) 0)
for col 0 (col < n) ++col
let new_queens (cons (list row col) queens)
if (no conflicts.new_queens)
(nqueens n new_queens)
# check if the first queen in 'queens' lies on the same column or diagonal as
# any of the others
def (conflicts queens)
let (curr ... rest) queens
or (let curr_column curr.1
(some (fn(_) (= _ curr_column))
(map cadr rest))) # columns
(some (fn(_) (diagonal_match curr _))
rest)
def (diagonal_match curr other)
(= (abs (curr.0 - other.0))
(abs (curr.1 - other.1))) |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Vala | Vala | int F(int n) {
if (n == 0) return 1;
return n - M(F(n - 1));
}
int M(int n) {
if (n == 0) return 0;
return n - F(M(n - 1));
}
void main() {
print("n : ");
for (int s = 0; s < 25; s++){
print("%2d ", s);
}
print("\n------------------------------------------------------------------------------\n");
print("F : ");
for (int s = 0; s < 25; s++){
print("%2d ", F(s));
}
print("\nM : ");
for (int s = 0; s < 25; s++){
print("%2d ", M(s));
}
} |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Perl | Perl | our $max = 12;
our $width = length($max**2) + 1;
printf "%*s", $width, $_ foreach 'x|', 1..$max;
print "\n", '-' x ($width - 1), '+', '-' x ($max*$width), "\n";
foreach my $i (1..$max) {
printf "%*s", $width, $_
foreach "$i|", map { $_ >= $i and $_*$i } 1..$max;
print "\n";
} |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics the steps shown in the video.
1. Cards.
Create a common deck of cards of 52 cards (which are half red, half black).
Give the pack a good shuffle.
2. Deal from the shuffled deck, you'll be creating three piles.
Assemble the cards face down.
Turn up the top card and hold it in your hand.
if the card is black, then add the next card (unseen) to the "black" pile.
If the card is red, then add the next card (unseen) to the "red" pile.
Add the top card that you're holding to the discard pile. (You might optionally show these discarded cards to get an idea of the randomness).
Repeat the above for the rest of the shuffled deck.
3. Choose a random number (call it X) that will be used to swap cards from the "red" and "black" piles.
Randomly choose X cards from the "red" pile (unseen), let's call this the "red" bunch.
Randomly choose X cards from the "black" pile (unseen), let's call this the "black" bunch.
Put the "red" bunch into the "black" pile.
Put the "black" bunch into the "red" pile.
(The above two steps complete the swap of X cards of the "red" and "black" piles.
(Without knowing what those cards are --- they could be red or black, nobody knows).
4. Order from randomness?
Verify (or not) the mathematician's assertion that:
The number of black cards in the "black" pile equals the number of red cards in the "red" pile.
(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)
Show output on this page.
| #11l | 11l | //import random
V n = 52
V Black = ‘Black’
V Red = ‘Red’
V blacks = [Black] * (n I/ 2)
V reds = [Red] * (n I/ 2)
V pack = blacks [+] reds
random:shuffle(&pack)
[String] black_stack, red_stack, discard
L !pack.empty
V top = pack.pop()
I top == Black
black_stack.append(pack.pop())
E
red_stack.append(pack.pop())
discard.append(top)
print(‘(Discards: ’(discard.map(d -> d[0]).join(‘ ’))" )\n")
V max_swaps = min(black_stack.len, red_stack.len)
V swap_count = random:(0 .. max_swaps)
print(‘Swapping ’swap_count)
F random_partition(stack, count)
V stack_copy = copy(stack)
random:shuffle(&stack_copy)
R (stack_copy[count ..], stack_copy[0 .< count])
(black_stack, V black_swap) = random_partition(black_stack, swap_count)
(red_stack, V red_swap) = random_partition(red_stack, swap_count)
black_stack [+]= red_swap
red_stack [+]= black_swap
I black_stack.count(Black) == red_stack.count(Red)
print(‘Yeha! The mathematicians assertion is correct.’)
E
print(‘Whoops - The mathematicians (or my card manipulations) are flakey’) |
http://rosettacode.org/wiki/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, for all i and j less than or equal to n.
The Task
Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence.
Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence.
Demonstrating working through the first few terms longhand:
a1 = 1
1 + 1 = 2
Speculatively try a2 = 2
1 + 1 = 2
1 + 2 = 3
2 + 2 = 4
There are no repeated sums so 2 is the next number in the sequence.
Speculatively try a3 = 3
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
2 + 2 = 4
2 + 3 = 5
3 + 3 = 6
Sum of 4 is repeated so 3 is rejected.
Speculatively try a3 = 4
1 + 1 = 2
1 + 2 = 3
1 + 4 = 5
2 + 2 = 4
2 + 4 = 6
4 + 4 = 8
There are no repeated sums so 4 is the next number in the sequence.
And so on...
See also
OEIS:A005282 Mian-Chowla sequence | #11l | 11l | F contains(sums, s, ss)
L(i) 0 .< ss
I sums[i] == s
R 1B
R 0B
F mian_chowla()
V n = 100
V mc = [0] * n
mc[0] = 1
V sums = [0] * ((n * (n + 1)) >> 1)
sums[0] = 2
V ss = 1
L(i) 1 .< n
V le = ss
V j = mc[i - 1] + 1
L
mc[i] = j
V nxtJ = 0B
L(k) 0 .. i
V sum = mc[k] + j
I contains(sums, sum, ss)
ss = le
nxtJ = 1B
L.break
sums[ss] = sum
ss++
I !nxtJ
L.break
j++
R mc
print(‘The first 30 terms of the Mian-Chowla sequence are:’)
V mc = mian_chowla()
print_elements(mc[0.<30])
print()
print(‘Terms 91 to 100 of the Mian-Chowla sequence are:’)
print_elements(mc[90..]) |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #BCPL | BCPL | get "libhdr"
static $( randstate = 0 $)
manifest $(
nummask = #XF
flagmask = #X10
bombmask = #X20
revealed = #X40
MAXINT = (~0)>>1
MININT = ~MAXINT
$)
let min(x,y) = x<y -> x, y
and max(x,y) = x>y -> x, y
let rand() = valof
$( randstate := random(randstate)
resultis randstate >> 7
$)
let randto(x) = valof
$( let r, mask = ?, 1
while mask<x do mask := (mask << 1) | 1
r := rand() & mask repeatuntil r < x
resultis r
$)
// Place a bomb on the field (if not already a bomb)
let placebomb(field, xsize, ysize, x, y) =
(field!(y*xsize+x) & bombmask) ~= 0 -> false,
valof
$( for xa = max(x-1, 0) to min(x+1, xsize-1)
for ya = max(y-1, 0) to min(y+1, ysize-1)
$( let loc = ya*xsize+xa
let n = field!loc & nummask
field!loc := (field!loc & ~nummask) | (n + 1)
$)
field!(y*xsize+x) := field!(y*xsize+x) | bombmask
resultis true
$)
// Populate the field with N bombs
let populate(field, xsize, ysize, nbombs) be
$( for i=0 to xsize*ysize-1 do field!i := 0
while nbombs > 0
$( let x, y = randto(xsize), randto(ysize)
if placebomb(field, xsize, ysize, x, y) then
nbombs := nbombs - 1
$)
$)
// Reveal field (X,Y) - returns true if stepped on a bomb
let reveal(field, xsize, ysize, x, y) =
(field!(y*xsize+x) & bombmask) ~= 0 -> true,
valof
$( let loc = y*xsize+x
field!loc := field!loc | revealed
if (field!loc & nummask) = 0 then
for xa = max(x-1, 0) to min(x+1, xsize-1)
for ya = max(y-1, 0) to min(y+1, ysize-1)
if (field!(ya*xsize+xa) &
(bombmask | flagmask | revealed)) = 0 do
reveal(field, xsize, ysize, xa, ya)
resultis false
$)
// Toggle flag
let toggleflag(field, xsize, ysize, x, y) be
$( let loc = y*xsize+x
field!loc := field!loc neqv flagmask
$)
// Show the field. Returns true if won.
let showfield(field, xsize, ysize, kaboom) = valof
$( let bombs, flags, hidden, found = 0, 0, 0, 0
for i=0 to xsize*ysize-1
$( if (field!i & revealed) = 0 do hidden := hidden + 1
unless (field!i & bombmask) = 0 do bombs := bombs + 1
unless (field!i & flagmask) = 0 do flags := flags + 1
if (field!i & bombmask) ~= 0 & (field!i & flagmask) ~= 0
do found := found + 1
$)
writef("Bombs: %N - Flagged: %N - Hidden: %N*N", bombs, flags, hidden)
wrch('+')
for x=0 to xsize-1 do wrch('-')
writes("+*N")
for y=0 to ysize-1
$( wrch('|')
for x=0 to xsize-1
$( let loc = y*xsize+x
test kaboom & (field!loc & bombmask) ~= 0 do
wrch('**')
or test (field!loc & (flagmask | revealed)) = flagmask do
wrch('?')
or test (field!loc & revealed) = 0 do
wrch('.')
or test (field!loc & nummask) = 0 do
wrch(' ')
or
wrch('0' + (field!loc & nummask))
$)
writes("|*N")
$)
wrch('+')
for x=0 to xsize-1 do wrch('-')
writes("+*N")
resultis found = bombs
$)
// Ask a question, get number
let ask(q, min, max) = valof
$( let n = ?
$( writes(q)
n := readn()
$) repeatuntil min <= n <= max
resultis n
$)
// Read string
let reads(v) = valof
$( let ch = ?
v%0 := 0
$( ch := rdch()
if ch = endstreamch then resultis false
v%0 := v%0 + 1
v%(v%0) := ch
$) repeatuntil ch = '*N'
resultis true
$)
// Play game given field
let play(field, xsize, ysize) be
$( let x = ?
let y = ?
let ans = vec 80
if showfield(field, xsize, ysize, false)
$( writes("*NYou win!*N")
finish
$)
$( writes("*NR)eveal, F)lag, Q)uit? ")
unless reads(ans) finish
unless ans%0 = 2 & ans%2='*N' loop
ans%1 := ans%1 | 32
if ans%1 = 'q' then finish
$) repeatuntil ans%1='r' | ans%1='f'
y := ask("Row? ", 1, ysize)-1
x := ask("Column? ", 1, xsize)-1
switchon ans%1 into
$( case 'r':
unless (field!(y*xsize+x) & flagmask) = 0
$( writes("*NError: that field is flagged, unflag it first.*N")
endcase
$)
unless (field!(y*xsize+x) & revealed) = 0
$( writes("*NError: that field is already revealed.*N")
endcase
$)
if reveal(field, xsize, ysize, x, y)
$( writes("*N K A B O O M *N*N")
showfield(field, xsize, ysize, true)
finish
$)
endcase
case 'f':
test (field!(y*xsize+x) & revealed) = 0
do toggleflag(field, xsize, ysize, x, y)
or writes("*NError: that field is already revealed.*N")
endcase
$)
wrch('*N')
$) repeat
let start() be
$( let field, xsize, ysize, bombs = ?, ?, ?, ?
writes("Minesweeper*N-----------*N*N")
randstate := ask("Random seed? ", MININT, MAXINT)
xsize := ask("Width (4-64)? ", 4, 64)
ysize := ask("Height (4-22)? ", 4, 22)
// 10 to 20% bombs
bombs := muldiv(xsize,ysize,10) + randto(muldiv(xsize,ysize,10)+1)
field := getvec(xsize*ysize)
populate(field, xsize, ysize, bombs)
play(field, xsize, ysize)
$) |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #Factor | Factor | : is-1-or-0 ( char -- ? ) dup CHAR: 0 = [ drop t ] [ CHAR: 1 = ] if ;
: int-is-B10 ( n -- ? ) unparse [ is-1-or-0 ] all? ;
: B10-step ( x x -- x x ? ) dup int-is-B10 [ f ] [ over + t ] if ;
: find-B10 ( x -- x ) dup [ B10-step ] loop nip ; |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #F.23 | F# | let expMod a b n =
let rec loop a b c =
if b = 0I then c else
loop (a*a%n) (b>>>1) (if b&&&1I = 0I then c else c*a%n)
loop a b 1I
[<EntryPoint>]
let main argv =
let a = 2988348162058574136915891421498819466320163312926952423791023078876139I
let b = 2351399303373464486466122544523690094744975233415544072992656881240319I
printfn "%A" (expMod a b (10I**40)) // -> 1527229998585248450016808958343740453059
0 |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #Factor | Factor | ! Built-in
2988348162058574136915891421498819466320163312926952423791023078876139
2351399303373464486466122544523690094744975233415544072992656881240319
10 40 ^
^mod . |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | << FiniteFields`
x^100 + x + 1 /. x -> GF[13]@{10} |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #Nim | Nim | import macros, sequtils, strformat, strutils
const Subscripts: array['0'..'9', string] = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"]
# Modular integer with modulus N.
type ModInt[N: static int] = distinct int
#---------------------------------------------------------------------------------------------------
# Creation.
func initModInt[N](n: int): ModInt[N] =
## Create a modular integer from an integer.
static:
when N < 2: error "Modulus must be greater than 1."
if n >= N: raise newException(ValueError, &"value must be in 0..{N - 1}.")
result = ModInt[N](n)
#---------------------------------------------------------------------------------------------------
# Arithmetic operations: ModInt op ModInt, ModInt op int and int op ModInt.
func `+`*[N](a, b: ModInt[N]): ModInt[N] =
ModInt[N]((a.int + b.int) mod N)
func `+`*[N](a: ModInt[N]; b: int): ModInt[N] =
a + initModInt[N](b)
func `+`*[N](a: int; b: ModInt[N]): ModInt[N] =
initModInt[N](a) + b
func `*`*[N](a, b: ModInt[N]): ModInt[N] =
ModInt[N]((a.int * b.int) mod N)
func `*`*[N](a: ModInt[N]; b: int): ModInt[N] =
a * initModInt[N](b)
func `*`*[N](a: int; b: ModInt[N]): ModInt[N] =
initModInt[N](a) * b
func `^`*[N](a: ModInt[N]; n: Natural): ModInt[N] =
var a = a
var n = n
result = initModInt[N](1)
while n > 0:
if (n and 1) != 0:
result = result * a
n = n shr 1
a = a * a
#---------------------------------------------------------------------------------------------------
# Representation of a modular integer as a string.
template subscript(n: Natural): string =
mapIt($n, Subscripts[it]).join()
func `$`(a: ModInt): string =
&"{a.int}{subscript(a.N)})"
#---------------------------------------------------------------------------------------------------
# The function "f" defined for any modular integer, the same way it would be defined for an
# integer argument (except that such a function would be of no use as it would overflow for
# any argument different of 0 and 1).
func f(x: ModInt): ModInt = x^100 + x + 1
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
var x = initModInt[13](10)
echo &"f({x}) = {x}^100 + {x} + 1 = {f(x)}." |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Swift | Swift | import Foundation
func digitSum(_ num: Int) -> Int {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
for n in 1...70 {
for m in 1... {
if digitSum(m * n) == n {
print(String(format: "%8d", m), terminator: n % 10 == 0 ? "\n" : " ")
break
}
}
} |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #Wren | Wren | import "./math" for Int
import "./seq" for Lst
import "./fmt" for Fmt
var res = []
for (n in 1..70) {
var m = 1
while (Int.digitSum(m * n) != n) m = m + 1
res.add(m)
}
for (chunk in Lst.chunks(res, 10)) Fmt.print("$,10d", chunk) |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #Swift | Swift | func minToOne(divs: [Int], subs: [Int], upTo n: Int) -> ([Int], [[String]]) {
var table = Array(repeating: n + 2, count: n + 1)
var how = Array(repeating: [""], count: n + 2)
table[1] = 0
how[1] = ["="]
for t in 1..<n {
let thisPlus1 = table[t] + 1
for div in divs {
let dt = div * t
if dt <= n && thisPlus1 < table[dt] {
table[dt] = thisPlus1
how[dt] = how[t] + ["/\(div)=> \(t)"]
}
}
for sub in subs {
let st = sub + t
if st <= n && thisPlus1 < table[st] {
table[st] = thisPlus1
how[st] = how[t] + ["-\(sub)=> \(t)"]
}
}
}
return (table, how.map({ $0.reversed().dropLast() }))
}
for (divs, subs) in [([2, 3], [1]), ([2, 3], [2])] {
print("\nMINIMUM STEPS TO 1:")
print(" Possible divisors: \(divs)")
print(" Possible decrements: \(subs)")
let (table, hows) = minToOne(divs: divs, subs: subs, upTo: 10)
for n in 1...10 {
print(" mintab( \(n)) in { \(table[n])} by: ", hows[n].joined(separator: ", "))
}
for upTo in [2_000, 50_000] {
print("\n Those numbers up to \(upTo) that take the maximum, \"minimal steps down to 1\":")
let (table, _) = minToOne(divs: divs, subs: subs, upTo: upTo)
let max = table.dropFirst().max()!
let maxNs = table.enumerated().filter({ $0.element == max })
print(
" Taking", max, "steps are the \(maxNs.count) numbers:",
maxNs.map({ String($0.offset) }).joined(separator: ", ")
)
}
} |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #Wren | Wren | import "/fmt" for Fmt
var limit = 50000
var divs = []
var subs = []
var mins = []
// Assumes the numbers are presented in order up to 'limit'.
var minsteps = Fn.new { |n|
if (n == 1) {
mins[1] = []
return
}
var min = limit
var p = 0
var q = 0
var op = ""
for (div in divs) {
if (n%div == 0) {
var d = (n/div).floor
var steps = mins[d].count + 1
if (steps < min) {
min = steps
p = d
q = div
op = "/"
}
}
}
for (sub in subs) {
var d = n - sub
if (d >= 1) {
var steps = mins[d].count + 1
if (steps < min) {
min = steps
p = d
q = sub
op = "-"
}
}
}
mins[n].add("%(op)%(q) -> %(p)")
mins[n].addAll(mins[p])
}
for (r in 0..1) {
divs = [2, 3]
subs = (r == 0) ? [1] : [2]
mins = List.filled(limit+1, null)
for (i in 0..limit) mins[i] = []
Fmt.print("With: Divisors: $n, Subtractors: $n =>", divs, subs)
System.print(" Minimum number of steps to diminish the following numbers down to 1 is:")
for (i in 1..limit) {
minsteps.call(i)
if (i <= 10) {
var steps = mins[i].count
var plural = (steps == 1) ? " " : "s"
var mi = Fmt.v("s", 0, mins[i], 0, ", ", "")
Fmt.print(" $2d: $d step$s: $s", i, steps, plural, mi)
}
}
for (lim in [2000, 20000, 50000]) {
var max = 0
for (min in mins[0..lim]) {
var m = min.count
if (m > max) max = m
}
var maxs = []
var i = 0
for (min in mins[0..lim]) {
if (min.count == max) maxs.add(i)
i = i + 1
}
var nums = maxs.count
var verb = (nums == 1) ? "is" : "are"
var verb2 = (nums == 1) ? "has" : "have"
var plural = (nums == 1) ? "": "s"
Fmt.write(" There $s $d number$s in the range 1-$d ", verb, nums, plural, lim)
Fmt.print("that $s maximum 'minimal steps' of $d:", verb2, max)
System.print(" %(maxs)")
}
System.print()
} |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Wren | Wren | var count = 0
var c = []
var f = []
var nQueens // recursive
nQueens = Fn.new { |row, n|
for (x in 1..n) {
var outer = false
var y = 1
while (y < row) {
if ((c[y] == x) || (row - y == (x -c[y]).abs)) {
outer = true
break
}
y = y + 1
}
if (!outer) {
c[row] = x
if (row < n) {
nQueens.call(row + 1, n)
} else {
count = count + 1
if (count == 1) f = c.skip(1).map { |i| i - 1 }.toList
}
}
}
}
for (n in 1..14) {
count = 0
c = List.filled(n+1, 0)
f = []
nQueens.call(1, n)
System.print("For a %(n) x %(n) board:")
System.print(" Solutions = %(count)")
if (count > 0) System.print(" First is %(f)")
System.print()
} |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #VBA | VBA | Private Function F(ByVal n As Integer) As Integer
If n = 0 Then
F = 1
Else
F = n - M(F(n - 1))
End If
End Function
Private Function M(ByVal n As Integer) As Integer
If n = 0 Then
M = 0
Else
M = n - F(M(n - 1))
End If
End Function
Public Sub MR()
Dim i As Integer
For i = 0 To 20
Debug.Print F(i);
Next i
Debug.Print
For i = 0 To 20
Debug.Print M(i);
Next i
End Sub |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Phix | Phix | printf(1," | ")
for col=1 to 12 do
printf(1,"%4d",col)
end for
printf(1,"\n--+-"&repeat('-',12*4))
for row=1 to 12 do
printf(1,"\n%2d| ",row)
for col=1 to 12 do
printf(1,iff(col<row?" ":sprintf("%4d",row*col)))
end for
end for
|
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics the steps shown in the video.
1. Cards.
Create a common deck of cards of 52 cards (which are half red, half black).
Give the pack a good shuffle.
2. Deal from the shuffled deck, you'll be creating three piles.
Assemble the cards face down.
Turn up the top card and hold it in your hand.
if the card is black, then add the next card (unseen) to the "black" pile.
If the card is red, then add the next card (unseen) to the "red" pile.
Add the top card that you're holding to the discard pile. (You might optionally show these discarded cards to get an idea of the randomness).
Repeat the above for the rest of the shuffled deck.
3. Choose a random number (call it X) that will be used to swap cards from the "red" and "black" piles.
Randomly choose X cards from the "red" pile (unseen), let's call this the "red" bunch.
Randomly choose X cards from the "black" pile (unseen), let's call this the "black" bunch.
Put the "red" bunch into the "black" pile.
Put the "black" bunch into the "red" pile.
(The above two steps complete the swap of X cards of the "red" and "black" piles.
(Without knowing what those cards are --- they could be red or black, nobody knows).
4. Order from randomness?
Verify (or not) the mathematician's assertion that:
The number of black cards in the "black" pile equals the number of red cards in the "red" pile.
(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)
Show output on this page.
| #AppleScript | AppleScript | use AppleScript version "2.5" -- OS X 10.11 (El Capitan) or later
use framework "Foundation"
use framework "GameplayKit" -- For randomising functions.
on cardTrick()
(* Create a pack of "cards" and shuffle it. *)
set suits to {"♥️", "♣️", "♦️", "♠️"}
set cards to {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}
set deck to {}
repeat with s from 1 to (count suits)
set suit to item s of suits
repeat with c from 1 to (count cards)
set end of deck to item c of cards & suit
end repeat
end repeat
set deck to (current application's class "GKRandomSource"'s new()'s arrayByShufflingObjectsInArray:(deck)) as list
(* Perform the black pile/red pile/discard stuff. *)
set {blackPile, redPile, discardPile} to {{}, {}, {}}
repeat with c from 1 to (count deck) by 2
set topCard to item c of deck
if (character -1 of topCard is in "♣️♠️") then
set end of blackPile to item (c + 1) of deck
else
set end of redPile to item (c + 1) of deck
end if
set end of discardPile to topCard
end repeat
-- When equal numbers of two possibilities are randomly paired, the number of pairs whose members are
-- both one of the possibilities is the same as the number whose members are both the other. The cards
-- in the red and black piles have effectively been paired with cards of the eponymous colours, so
-- the number of reds in the red pile is already the same as the number of blacks in the black.
(* Take a random number of random cards from one pile and swap them with an equal number from the other,
religiously following the "red bunch"/"black bunch" ritual instead of simply swapping pairs of cards. *)
-- Where swapped cards are the same colour, this will make no difference at all. Where the colours
-- are different, both piles will either gain or lose a card of their relevant colour, maintaining
-- the defining balance either way.
set {redBunch, blackBunch} to {{}, {}}
set {redPileCount, blackPileCount} to {(count redPile), (count blackPile)}
set maxX to blackPileCount
if (redPileCount < maxX) then set maxX to redPileCount
set X to (current application's class "GKRandomDistribution"'s distributionForDieWithSideCount:(maxX))'s nextInt()
set RNG to current application's class "GKShuffledDistribution"'s distributionForDieWithSideCount:(redPileCount)
repeat X times
set r to RNG's nextInt()
set end of redBunch to item r of redPile
set item r of redPile to missing value
end repeat
set RNG to current application's class "GKShuffledDistribution"'s distributionForDieWithSideCount:(blackPileCount)
repeat X times
set b to RNG's nextInt()
set end of blackBunch to item b of blackPile
set item b of blackPile to missing value
end repeat
set blackPile to (blackPile's text) & redBunch
set redPile to (redPile's text) & blackBunch
(* Count and compare the number of blacks in the black pile and the number of reds in the red. *)
set blacksInBlackPile to 0
repeat with card in blackPile
if (character -1 of card is in "♣️♠️") then set blacksInBlackPile to blacksInBlackPile + 1
end repeat
set redsInRedPile to 0
repeat with card in redPile
if (character -1 of card is in "♥️♦️") then set redsInRedPile to redsInRedPile + 1
end repeat
return {truth:(blacksInBlackPile = redsInRedPile), reds:redPile, blacks:blackPile, discards:discardPile}
end cardTrick
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
on task()
set output to {}
repeat with i from 1 to 5
set {truth:truth, reds:reds, blacks:blacks, discards:discards} to cardTrick()
set end of output to "Test " & i & ": Assertion is " & truth
set end of output to "Red pile: " & join(reds, ", ")
set end of output to "Black pile: " & join(blacks, ", ")
set end of output to "Discards: " & join(items 1 thru 13 of discards, ", ")
set end of output to " " & (join(items 14 thru 26 of discards, ", ") & linefeed)
end repeat
return text 1 thru -2 of join(output, linefeed)
end task
return task() |
http://rosettacode.org/wiki/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, for all i and j less than or equal to n.
The Task
Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence.
Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence.
Demonstrating working through the first few terms longhand:
a1 = 1
1 + 1 = 2
Speculatively try a2 = 2
1 + 1 = 2
1 + 2 = 3
2 + 2 = 4
There are no repeated sums so 2 is the next number in the sequence.
Speculatively try a3 = 3
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
2 + 2 = 4
2 + 3 = 5
3 + 3 = 6
Sum of 4 is repeated so 3 is rejected.
Speculatively try a3 = 4
1 + 1 = 2
1 + 2 = 3
1 + 4 = 5
2 + 2 = 4
2 + 4 = 6
4 + 4 = 8
There are no repeated sums so 4 is the next number in the sequence.
And so on...
See also
OEIS:A005282 Mian-Chowla sequence | #Ada | Ada | with Ada.Text_IO;
with Ada.Containers.Hashed_Sets;
procedure Mian_Chowla_Sequence
is
type Natural_Array is array(Positive range <>) of Natural;
function Hash(P : in Positive) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type(P);
end Hash;
package Positive_Sets is new Ada.Containers.Hashed_Sets(Positive, Hash, "=");
function Mian_Chowla(N : in Positive) return Natural_Array
is
return_array : Natural_Array(1 .. N) := (others => 0);
nth : Positive := 1;
candidate : Positive := 1;
seen : Positive_Sets.Set;
begin
while nth <= N loop
declare
sums : Positive_Sets.Set;
terms : constant Natural_Array := return_array(1 .. nth-1) & candidate;
found : Boolean := False;
begin
for term of terms loop
if seen.Contains(term + candidate) then
found := True;
exit;
else
sums.Insert(term + candidate);
end if;
end loop;
if not found then
return_array(nth) := candidate;
seen.Union(sums);
nth := nth + 1;
end if;
candidate := candidate + 1;
end;
end loop;
return return_array;
end Mian_Chowla;
length : constant Positive := 100;
sequence : constant Natural_Array(1 .. length) := Mian_Chowla(length);
begin
Ada.Text_IO.Put_Line("Mian Chowla sequence first 30 terms :");
for term of sequence(1 .. 30) loop
Ada.Text_IO.Put(term'Img);
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line("Mian Chowla sequence terms 91 to 100 :");
for term of sequence(91 .. 100) loop
Ada.Text_IO.Put(term'Img);
end loop;
end Mian_Chowla_Sequence; |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #C | C | #if 0
Unix build:
make CPPFLAGS=-DNDEBUG LDLIBS=-lcurses mines
dwlmines, by David Lambert; sometime in the twentieth Century. The
program is meant to run in a terminal window compatible with curses
if unix is defined to cpp, or to an ANSI terminal when compiled
without unix macro defined. I suppose I have built this on a
windows 98 computer using gcc running in a cmd window. The original
probably came from a VAX running VMS with a vt100 sort of terminal.
Today I have xterm and gcc available so I will claim only that it
works with this combination.
As this program can automatically play all the trivially counted
safe squares. Action is quick leaving the player with only the
thoughtful action. Whereas 's' steps on the spot with the cursor,
capital 'S' (Stomp) invokes autoplay.
The cursor motion keys are as in the vi editor; hjkl move the cursor.
'd' displays the number of unclaimed bombs and cells.
'f' flags a cell.
The numbers on the field indicate the number of bombs in the
unclaimed neighboring cells. This is more useful than showing the
values you expect. You may find unflagging a cell adjacent to a
number will help you understand this.
There is extra code here. The multidimensional array allocator
allocarray is much better than those of Numerical Recipes in C. If
you subtracted the offset 1 to make the arrays FORTRAN like then
allocarray could substitute for those of NR in C.
#endif
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#ifndef NDEBUG
# define DEBUG_CODE(A) A
#else
# define DEBUG_CODE(A)
#endif
#include <time.h>
#define DIM(A) (sizeof((A))/sizeof(*(A)))
#define MAX(A,B) ((A)<(B)?(B):(A))
#define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L))
#define SET_BIT(A,B) ((A)|=1<<(B))
#define CLR_BIT(A,B) ((A)&=~(1<<(B)))
#define TGL_BIT(A,B) ((A)^=1<<(B))
#define INQ_BIT(A,B) ((A)&(1<<(B)))
#define FOREVER for(;;)
#define MODINC(i,mod) ((i)+1<(mod)?(i)+1:0)
#define MODDEC(i,mod) (((i)<=0?(mod):(i))-1)
void error(int status,const char *message) {
fprintf(stderr, "%s\n", message);
exit(status);
}
void*dwlcalloc(int n,size_t bytes) {
void*rv = (void*)calloc(n,bytes);
if (NULL == rv)
error(1,"memory allocation failure");
DEBUG_CODE(fprintf(stderr,"allocated address %p\n",rv);)
return rv;
}
void*allocarray(int rank,size_t*shape,size_t itemSize) {
/*
Allocates arbitrary dimensional arrays (and inits all pointers)
with only 1 call to malloc. David W. Lambert, written before 1990.
This is wonderful because one only need call free once to deallocate
the space. Special routines for each size array are not need for
allocation of for deallocation. Also calls to malloc might be expensive
because they might have to place operating system requests. One call
seems optimal.
*/
size_t size,i,j,dataSpace,pointerSpace,pointers,nextLevelIncrement;
char*memory,*pc,*nextpc;
if (rank < 2) {
if (rank < 0)
error(1,"invalid negative rank argument passed to allocarray");
size = rank < 1 ? 1 : *shape;
return dwlcalloc(size,itemSize);
}
pointerSpace = 0, dataSpace = 1;
for (i = 0; i < rank-1; ++i)
pointerSpace += (dataSpace *= shape[i]);
pointerSpace *= sizeof(char*);
dataSpace *= shape[i]*itemSize;
memory = pc = dwlcalloc(1,pointerSpace+dataSpace);
pointers = 1;
for (i = 0; i < rank-2; ) {
nextpc = pc + (pointers *= shape[i])*sizeof(char*);
nextLevelIncrement = shape[++i]*sizeof(char*);
for (j = 0; j < pointers; ++j)
*((char**)pc) = nextpc, pc+=sizeof(char*), nextpc += nextLevelIncrement;
}
nextpc = pc + (pointers *= shape[i])*sizeof(char*);
nextLevelIncrement = shape[++i]*itemSize;
for (j = 0; j < pointers; ++j)
*((char**)pc) = nextpc, pc+=sizeof(char*), nextpc += nextLevelIncrement;
return memory;
}
#define PRINT(element) \
if (NULL == print_elt) \
printf("%10.3e",*(double*)(element)); \
else \
(*print_elt)(element)
/* matprint prints an array in APL\360 style */
/* with a NULL element printing function matprint assumes an array of double */
void matprint(void*a,int rank,size_t*shape,size_t size,void(*print_elt)()) {
union {
unsigned **ppu;
unsigned *pu;
unsigned u;
} b;
int i;
if (rank <= 0 || NULL == shape)
PRINT(a);
else if (1 < rank) {
for (i = 0; i < shape[0]; ++i)
matprint(((void**)a)[i], rank-1,shape+1,size,print_elt);
putchar('\n');
for (i = 0, b.pu = a; i < shape[0]; ++i, b.u += size) {
PRINT(b.pu);
putchar(' ');
}
}
}
#ifdef __unix__
# include <curses.h>
# include <unistd.h>
# define SRANDOM srandom
# define RANDOM random
#else
# include <windows.h>
void addch(int c) { putchar(c); }
void addstr(const char*s) { fputs(s,stdout); }
# define ANSI putchar(27),putchar('[')
void initscr(void) { printf("%d\n",AllocConsole()); }
void cbreak(void) { ; }
void noecho(void) { ; }
void nonl(void) { ; }
int move(int r,int c) { ANSI; return printf("%d;%dH",r+1,c+1); }
int mvaddch(int r,int c,int ch) { move(r,c); addch(ch); }
void refresh(void) { ; }
# define WA_STANDOUT 32
int attr_on(int a,void*p) { ANSI; return printf("%dm",a); }
int attr_off(int a,void*p) { attr_on(0,NULL); }
# include <stdarg.h>
void printw(const char*fmt,...) {
va_list args;
va_start(args,fmt);
vprintf(fmt,args);
va_end(args);
}
void clrtoeol(void) {
ANSI;addstr("0J");
}
# define SRANDOM srand
# define RANDOM rand
#endif
#ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 1 /* just a guess */
#endif
#if 0
cell status
UNKN --- contains virgin earth (initial state)
MINE --- has a mine
FLAG --- was flagged
#endif
enum {UNKN,MINE,FLAG}; /* bit numbers */
#define DETECT(CELL,PROPERTY) (!!INQ_BIT(CELL,PROPERTY))
DEBUG_CODE( \
void pchr(void*a) { /* odd comment removed */ \
putchar('A'+*(char*a)); /* should print the nth char of alphabet */\
} /* where 'A' is 0 */ \
)
char**bd; /* the board */
size_t shape[2];
#define RWS (shape[0])
#define CLS (shape[1])
void populate(int x,int y,int pct) { /* finished size in col, row, % mines */
int i,j,c;
x = BIND(x,4,200), y = BIND(y,4,400); /* confine input as piecewise linear */
shape[0] = x+2, shape[1] = y+2; bd = (char**)allocarray(2,shape,sizeof(char));
memset(*bd,1<<UNKN,shape[0]*shape[1]*sizeof(char)); /* all unknown */
for (i = 0; i < shape[0]; ++i) /* border is safe */
bd[i][0] = bd[i][shape[1]-1] = 0;
for (i = 0; i < shape[1]; ++i)
bd[0][i] = bd[shape[0]-1][i] = 0;
{
time_t seed; /* now I would choose /dev/random */
printf("seed is %u\n",(unsigned)seed);
time(&seed), SRANDOM((unsigned)seed);
}
c = BIND(pct,1,99)*x*y/100; /* number of mines to set */
while(c) {
i = RANDOM(), j = 1+i%y, i = 1+(i>>16)%x;
if (! DETECT(bd[i][j],MINE)) /* 1 mine per site */
--c, SET_BIT(bd[i][j],MINE);
}
DEBUG_CODE(matprint(bd,2,shape,sizeof(int),pchr);)
RWS = x+1, CLS = y+1; /* shape now stores the upper bounds */
}
struct {
int i,j;
} neighbor[] = {
{-1,-1}, {-1, 0}, {-1, 1},
{ 0,-1}, /*home*/ { 0, 1},
{ 1,-1}, { 1, 0}, { 1, 1}
};
/* NEIGHBOR seems to map 0..8 to local 2D positions */
#define NEIGHBOR(I,J,K) (bd[(I)+neighbor[K].i][(J)+neighbor[K].j])
int cnx(int i,int j,char w) { /* count neighbors with property w */
int k,c = 0;
for (k = 0; k < DIM(neighbor); ++k)
c += DETECT(NEIGHBOR(i,j,k),w);
return c;
}
int row,col;
#define ME bd[row+1][col+1]
int step(void) {
if (DETECT(ME,FLAG)) return 1; /* flags offer protection */
if (DETECT(ME,MINE)) return 0; /* lose */
CLR_BIT(ME,UNKN);
return 1;
}
int autoplay(void) {
int i,j,k,change,m;
if (!step()) return 0;
do /* while changing */
for (change = 0, i = 1; i < RWS; ++i)
for (j = 1; j < CLS; ++j)
if (!DETECT(bd[i][j],UNKN)) { /* consider nghbrs of safe cells */
m = cnx(i,j,MINE);
if (cnx(i,j,FLAG) == m) { /* mines appear flagged */
for (k = 0; k < DIM(neighbor); ++k)
if (DETECT(NEIGHBOR(i,j,k),UNKN)&&!DETECT(NEIGHBOR(i,j,k),FLAG)) {
if (DETECT(NEIGHBOR(i,j,k),MINE)) { /* OOPS! */
row = i+neighbor[k].i-1, col = j+neighbor[k].j-1;
return 0;
}
change = 1, CLR_BIT(NEIGHBOR(i,j,k),UNKN);
}
} else if (cnx(i,j,UNKN) == m)
for (k = 0; k < DIM(neighbor); ++k)
if (DETECT(NEIGHBOR(i,j,k),UNKN))
change = 1, SET_BIT(NEIGHBOR(i,j,k),FLAG);
}
while (change);
return 1;
}
void takedisplay(void) { initscr(), cbreak(), noecho(), nonl(); }
void help(void) {
move(RWS,1),clrtoeol(), printw("move:hjkl flag:Ff step:Ss other:qd?");
}
void draw(void) {
int i,j,w;
const char*s1 = " 12345678";
move(1,1);
for (i = 1; i < RWS; ++i, addstr("\n "))
for (j = 1; j < CLS; ++j, addch(' ')) {
w = bd[i][j];
if (!DETECT(w,UNKN)) {
w = cnx(i,j,MINE)-cnx(i,j,FLAG);
if (w < 0) attr_on(WA_STANDOUT,NULL), w = -w;
addch(s1[w]);
attr_off(WA_STANDOUT,NULL);
}
else if (DETECT(w,FLAG)) addch('F');
else addch('*');
}
move(row+1,2*col+1);
refresh();
}
void show(int win) {
int i,j,w;
const char*s1 = " 12345678";
move(1,1);
for (i = 1; i < RWS; ++i, addstr("\n "))
for (j = 1; j < CLS; ++j, addch(' ')) {
w = bd[i][j];
if (!DETECT(w,UNKN)) {
w = cnx(i,j,MINE)-cnx(i,j,FLAG);
if (w < 0) attr_on(WA_STANDOUT,NULL), w = -w;
addch(s1[w]);
attr_off(WA_STANDOUT,NULL);
}
else if (DETECT(w,FLAG))
if (DETECT(w,MINE)) addch('F');
else attr_on(WA_STANDOUT,NULL), addch('F'),attr_off(WA_STANDOUT,NULL);
else if (DETECT(w,MINE)) addch('M');
else addch('*');
}
mvaddch(row+1,2*col,'('), mvaddch(row+1,2*(col+1),')');
move(RWS,0);
refresh();
}
#define HINTBIT(W) s3[DETECT(bd[r][c],(W))]
#define NEIGCNT(W) s4[cnx(r,c,(W))]
const char*s3="01", *s4="012345678";
void dbg(int r, int c) {
int i,j,unkns=0,mines=0,flags=0,pct;
char o[6];
static int hint;
for (i = 1; i < RWS; ++i)
for (j = 1; j < CLS; ++j)
unkns += DETECT(bd[i][j],UNKN),
mines += DETECT(bd[i][j],MINE),
flags += DETECT(bd[i][j],FLAG);
move(RWS,1), clrtoeol();
pct = 0.5+100.0*(mines-flags)/MAX(1,unkns-flags);
if (++hint<4)
o[0] = HINTBIT(UNKN), o[1] = HINTBIT(MINE), o[2] = HINTBIT(FLAG),
o[3] = HINTBIT(UNKN), o[4] = NEIGCNT(MINE), o[5] = NEIGCNT(FLAG);
else
memset(o,'?',sizeof(o));
printw("(%c%c%c) u=%c, m=%c, f=%c, %d/%d (%d%%) remain.",
o[0],o[1],o[2],o[3],o[4],o[5],mines-flags,unkns-flags,pct);
}
#undef NEIGCNT
#undef HINTBIT
void toggleflag(void) {
if (DETECT(ME,UNKN))
TGL_BIT(ME,FLAG);
}
int sureflag(void) {
toggleflag();
return autoplay();
}
int play(int*win) {
int c = getch(), d = tolower(c);
if ('q' == d) return 0;
else if ('?' == c) help();
else if ('h' == d) col = MODDEC(col,CLS-1);
else if ('l' == d) col = MODINC(col,CLS-1);
else if ('k' == d) row = MODDEC(row,RWS-1);
else if ('j' == d) row = MODINC(row,RWS-1);
else if ('f' == c) toggleflag();
else if ('s' == c) return *win = step();
else if ('S' == c) return *win = autoplay();
else if ('F' == c) return *win = sureflag();
else if ('d' == d) dbg(row+1,col+1);
return 1;
}
int convert(const char*name,const char*s) {
if (strlen(s) == strspn(s,"0123456789"))
return atoi(s);
fprintf(stderr," use: %s [rows [columns [percentBombs]]]\n",name);
fprintf(stderr,"default: %s 20 30 25\n",name);
exit(EXIT_SUCCESS);
}
void parse_command_line(int ac,char*av[],int*a,int*b,int*c) {
switch (ac) {
default:
case 4: *c = convert(*av,av[3]);
case 3: *b = convert(*av,av[2]);
case 2: *a = convert(*av,av[1]);
case 1: ;
}
}
int main(int ac,char*av[],char*env[]) {
int win = 1, rows = 20, cols = 30, prct = 25;
parse_command_line(ac,av,&rows,&cols,&prct);
populate(rows,cols,prct);
takedisplay();
while(draw(), play(&win));
show(win);
free(bd);
# ifdef __unix__
{
const char*s = "/bin/stty";
execl(s,s,"sane",(const char*)NULL);
}
# endif
return 0;
} |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #FreeBASIC | FreeBASIC | #define limit1 900
#define limit2 18703890759446315
Dim As Ulongint nplus, lenplus, prod
Dim As Boolean plusflag = false, flag
Dim As String pstr
Dim As Integer plus(6) = {297,576,594,891,909,999}
Print !"Minimum positive multiple in base 10 using only 0 and 1:\n"
Print " N * multiplier = B10"
For n As Ulongint = 1 To limit1
If n = 106 Then
plusflag = true
nplus = 0
End If
lenplus = Ubound(plus)
If plusflag = true Then
nplus += 1
If nplus < lenplus+1 Then
n = plus(nplus)
Else
Exit For
End If
End If
For m As Ulongint = 1 To limit2
flag = true
prod = n*m
pstr = Str(prod)
For p As Ulongint = 1 To Len(pstr)
If Not(Mid(pstr,p,1) = "0" Or Mid(pstr,p,1) = "1") Then
flag = false
Exit For
End If
Next p
If flag = true Then
Print Using "### * ################ = &"; n; m; pstr
Exit For
End If
Next m
If n = 10 Then n = 94 : End If
Next n
Sleep |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #FreeBASIC | FreeBASIC |
'From first principles (No external library)
Function _divide(n1 As String,n2 As String,decimal_places As Integer=10,dpflag As String="s") As String
Dim As String number=n1,divisor=n2
dpflag=Lcase(dpflag)
'For MOD
Dim As Integer modstop
If dpflag="mod" Then
If Len(n1)<Len(n2) Then Return n1
If Len(n1)=Len(n2) Then
If n1<n2 Then Return n1
End If
modstop=Len(n1)-Len(n2)+1
End If
If dpflag<>"mod" Then
If dpflag<>"s" Then dpflag="raw"
End If
Dim runcount As Integer
'_______ LOOK UP TABLES ______________
Dim Qmod(0 To 19) As Ubyte
Dim bool(0 To 19) As Ubyte
For z As Integer=0 To 19
Qmod(z)=(z Mod 10+48)
bool(z)=(-(10>z))
Next z
Dim answer As String 'THE ANSWER STRING
'_______ SET THE DECIMAL WHERE IT SHOULD BE AT _______
Dim As String part1,part2
#macro set(decimal)
#macro insert(s,char,position)
If position > 0 And position <=Len(s) Then
part1=Mid(s,1,position-1)
part2=Mid(s,position)
s=part1+char+part2
End If
#endmacro
insert(answer,".",decpos)
answer=thepoint+zeros+answer
If dpflag="raw" Then
answer=Mid(answer,1,decimal_places)
End If
#endmacro
'______________________________________________
'__________ SPLIT A STRING ABOUT A CHARACTRR __________
Dim As String var1,var2
Dim pst As Integer
#macro split(stri,char,var1,var2)
pst=Instr(stri,char)
var1="":var2=""
If pst<>0 Then
var1=Rtrim(Mid(stri,1,pst),".")
var2=Ltrim(Mid(stri,pst),".")
Else
var1=stri
End If
#endmacro
#macro Removepoint(s)
split(s,".",var1,var2)
#endmacro
'__________ GET THE SIGN AND CLEAR THE -ve __________________
Dim sign As String
If Left(number,1)="-" Xor Left (divisor,1)="-" Then sign="-"
If Left(number,1)="-" Then number=Ltrim(number,"-")
If Left (divisor,1)="-" Then divisor=Ltrim(divisor,"-")
'DETERMINE THE DECIMAL POSITION BEFORE THE DIVISION
Dim As Integer lennint,lenddec,lend,lenn,difflen
split(number,".",var1,var2)
lennint=Len(var1)
split(divisor,".",var1,var2)
lenddec=Len(var2)
If Instr(number,".") Then
Removepoint(number)
number=var1+var2
End If
If Instr(divisor,".") Then
Removepoint(divisor)
divisor=var1+var2
End If
Dim As Integer numzeros
numzeros=Len(number)
number=Ltrim(number,"0"):divisor=Ltrim (divisor,"0")
numzeros=numzeros-Len(number)
lend=Len(divisor):lenn=Len(number)
If lend>lenn Then difflen=lend-lenn
Dim decpos As Integer=lenddec+lennint-lend+2-numzeros 'THE POSITION INDICATOR
Dim _sgn As Byte=-Sgn(decpos)
If _sgn=0 Then _sgn=1
Dim As String thepoint=String(_sgn,".") 'DECIMAL AT START (IF)
Dim As String zeros=String(-decpos+1,"0")'ZEROS AT START (IF) e.g. .0009
If dpflag<>"mod" Then
If Len(zeros) =0 Then dpflag="s"
End If
Dim As Integer runlength
If Len(zeros) Then
runlength=decimal_places
answer=String(Len(zeros)+runlength+10,"0")
If dpflag="raw" Then
runlength=1
answer=String(Len(zeros)+runlength+10,"0")
If decimal_places>Len(zeros) Then
runlength=runlength+(decimal_places-Len(zeros))
answer=String(Len(zeros)+runlength+10,"0")
End If
End If
Else
decimal_places=decimal_places+decpos
runlength=decimal_places
answer=String(Len(zeros)+runlength+10,"0")
End If
'___________DECIMAL POSITION DETERMINED _____________
'SET UP THE VARIABLES AND START UP CONDITIONS
number=number+String(difflen+decimal_places,"0")
Dim count As Integer
Dim temp As String
Dim copytemp As String
Dim topstring As String
Dim copytopstring As String
Dim As Integer lenf,lens
Dim As Ubyte takeaway,subtractcarry
Dim As Integer n3,diff
If Ltrim(divisor,"0")="" Then Return "Error :division by zero"
lens=Len(divisor)
topstring=Left(number,lend)
copytopstring=topstring
Do
count=0
Do
count=count+1
copytemp=temp
Do
'___________________ QUICK SUBTRACTION loop _________________
lenf=Len(topstring)
If lens<lenf=0 Then 'not
If Lens>lenf Then
temp= "done"
Exit Do
End If
If divisor>topstring Then
temp= "done"
Exit Do
End If
End If
diff=lenf-lens
temp=topstring
subtractcarry=0
For n3=lenf-1 To diff Step -1
takeaway= topstring[n3]-divisor[n3-diff]+10-subtractcarry
temp[n3]=Qmod(takeaway)
subtractcarry=bool(takeaway)
Next n3
If subtractcarry=0 Then Exit Do
If n3=-1 Then Exit Do
For n3=n3 To 0 Step -1
takeaway= topstring[n3]-38-subtractcarry
temp[n3]=Qmod(takeaway)
subtractcarry=bool(takeaway)
If subtractcarry=0 Then Exit Do
Next n3
Exit Do
Loop 'single run
temp=Ltrim(temp,"0")
If temp="" Then temp= "0"
topstring=temp
Loop Until temp="done"
' INDIVIDUAL CHARACTERS CARVED OFF ________________
runcount=runcount+1
If count=1 Then
topstring=copytopstring+Mid(number,lend+runcount,1)
Else
topstring=copytemp+Mid(number,lend+runcount,1)
End If
copytopstring=topstring
topstring=Ltrim(topstring,"0")
If dpflag="mod" Then
If runcount=modstop Then
If topstring="" Then Return "0"
Return Mid(topstring,1,Len(topstring)-1)
End If
End If
answer[runcount-1]=count+47
If topstring="" And runcount>Len(n1)+1 Then
Exit Do
End If
Loop Until runcount=runlength+1
' END OF RUN TO REQUIRED DECIMAL PLACES
set(decimal) 'PUT IN THE DECIMAL POINT
'THERE IS ALWAYS A DECIMAL POINT SOMEWHERE IN THE ANSWER
'NOW GET RID OF IT IF IT IS REDUNDANT
answer=Rtrim(answer,"0")
answer=Rtrim(answer,".")
answer=Ltrim(answer,"0")
If answer="" Then Return "0"
Return sign+answer
End Function
Dim Shared As Integer _Mod(0 To 99),_Div(0 To 99)
For z As Integer=0 To 99:_Mod(z)=(z Mod 10+48):_Div(z)=z\10:Next
Function Qmult(a As String,b As String) As String
Var flag=0,la = Len(a),lb = Len(b)
If Len(b)>Len(a) Then flag=1:Swap a,b:Swap la,lb
Dim As Ubyte n,carry,ai
Var c =String(la+lb,"0")
For i As Integer =la-1 To 0 Step -1
carry=0:ai=a[i]-48
For j As Integer =lb-1 To 0 Step -1
n = ai * (b[j]-48) + (c[i+j+1]-48) + carry
carry =_Div(n):c[i+j+1]=_Mod(n)
Next j
c[i]+=carry
Next i
If flag Then Swap a,b
Return Ltrim(c,"0")
End Function
'=======================================================================
#define mod_(a,b) _divide((a),(b),,"mod")
#define div_(a,b) iif(len((a))<len((b)),"0",_divide((a),(b),-2))
Function Modular_Exponentiation(base_num As String, exponent As String, modulus As String) As String
Dim b1 As String = base_num
Dim e1 As String = exponent
Dim As String result="1"
b1 = mod_(b1,modulus)
Do While e1 <> "0"
Var L=Len(e1)-1
If e1[L] And 1 Then
result=mod_(Qmult(result,b1),modulus)
End If
b1=mod_(qmult(b1,b1),modulus)
e1=div_(e1,"2")
Loop
Return result
End Function
var base_num="2988348162058574136915891421498819466320163312926952423791023078876139"
var exponent="2351399303373464486466122544523690094744975233415544072992656881240319"
var modulus="10000000000000000000000000000000000000000"
dim as double t=timer
var ans=Modular_Exponentiation(base_num,exponent,modulus)
print "Result:"
Print ans
print "time taken ";(timer-t)*1000;" milliseconds"
Print "Done"
Sleep
|
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.
However, the playing of the sounds should not interfere with the timing of the metronome.
The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.
If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
| #11l | 11l | F main(bpm = 72, bpb = 4)
V t = 60.0 / bpm
V counter = 0
L
counter++
I counter % bpb != 0
print(‘tick’)
E
print(‘TICK’)
sleep(t)
main() |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
| #Ada | Ada | package Semaphores is
protected type Counting_Semaphore(Max : Positive) is
entry Acquire;
procedure Release;
function Count return Natural;
private
Lock_Count : Natural := 0;
end Counting_Semaphore;
end Semaphores; |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #PARI.2FGP | PARI/GP | Mod(3,7)+Mod(4,7) |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #Perl | Perl | use Math::ModInt qw(mod);
sub f { my $x = shift; $x**100 + $x + 1 };
print f mod(10, 13); |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #XPL0 | XPL0 | func SumDigits(N); \Return sum of digits in N
int N, S;
[S:= 0;
while N do
[N:= N/10;
S:= S + rem(0);
];
return S;
];
int C, N, M;
[C:= 0; N:= 1;
repeat M:= 1;
while SumDigits(N*M) # N do M:= M+1;
IntOut(0, M);
C:= C+1;
if rem (C/10) then ChOut(0, 9\tab\) else CrLf(0);
N:= N+1;
until C >= 40+30;
] |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #XPL0 | XPL0 | int MinSteps, \minimal number of steps to get to 1
Subtractor; \1 or 2
char Ns(20000), Ops(20000), MinNs(20000), MinOps(20000);
proc Reduce(N, Step); \Reduce N to 1, recording minimum steps
int N, Step, I;
[if N = 1 then
[if Step < MinSteps then
[for I:= 0 to Step-1 do
[MinOps(I):= Ops(I);
MinNs(I):= Ns(I);
];
MinSteps:= Step;
];
];
if Step >= MinSteps then return; \don't search further
if rem(N/3) = 0 then
[Ops(Step):= 3; Ns(Step):= N/3; Reduce(N/3, Step+1)];
if rem(N/2) = 0 then
[Ops(Step):= 2; Ns(Step):= N/2; Reduce(N/2, Step+1)];
Ops(Step):= -Subtractor; Ns(Step):= N-Subtractor; Reduce(N-Subtractor, Step+1);
]; \Reduce
proc ShowSteps(N); \Show minimal steps and how N steps to 1
int N, I;
[MinSteps:= $7FFF_FFFF;
Reduce(N, 0);
Text(0, "N = "); IntOut(0, N);
Text(0, " takes "); IntOut(0, MinSteps); Text(0, " steps: N ");
for I:= 0 to MinSteps-1 do
[Text(0, if extend(MinOps(I)) < 0 then "-" else "/");
IntOut(0, abs(extend(MinOps(I))));
Text(0, "=>"); IntOut(0, MinNs(I)); Text(0, " ");
];
CrLf(0);
]; \ShowSteps
proc ShowCount(Range); \Show count of maximum minimal steps and their Ns
int Range;
int N, MaxSteps;
[MaxSteps:= 0; \find maximum number of minimum steps
for N:= 1 to Range do
[MinSteps:= $7FFF_FFFF;
Reduce(N, 0);
if MinSteps > MaxSteps then
MaxSteps:= MinSteps;
];
Text(0, "Maximum steps: "); IntOut(0, MaxSteps); Text(0, " for N = ");
for N:= 1 to Range do \show numbers (Ns) for Maximum steps
[MinSteps:= $7FFF_FFFF;
Reduce(N, 0);
if MinSteps = MaxSteps then
[IntOut(0, N); Text(0, " ");
];
];
CrLf(0);
]; \ShowCount
int N;
[Subtractor:= 1; \1.
for N:= 1 to 10 do ShowSteps(N);
ShowCount(2000); \2.
ShowCount(20_000); \2a.
Subtractor:= 2; \3.
for N:= 1 to 10 do ShowSteps(N);
ShowCount(2000); \4.
ShowCount(20_000); \4a.
] |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfectly divided by D, (remainder zero).
OR have one of S subtracted from it, if N is greater than the member of S.
There may be many ways to reduce the initial N down to 1. Your program needs to:
Find the minimum number of steps to reach 1.
Show one way of getting fron N to 1 in those minimum steps.
Examples
No divisors, D. a single subtractor of 1.
Obviousely N will take N-1 subtractions of 1 to reach 1
Single divisor of 2; single subtractor of 1:
N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1
Divisors 2 and 3; subtractor 1:
N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1
Task
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:
1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:
3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000.
Optional stretch goal
2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000
Reference
Learn Dynamic Programming (Memoization & Tabulation) Video of similar task. | #zkl | zkl | var minCache; // (val:(newVal,op,steps))
fcn buildCache(N,D,S){
minCache=Dictionary(1,T(1,"",0));
foreach n in ([2..N]){
ops:=List();
foreach d in (D){ if(n%d==0) ops.append(T(n/d, String("/",d))) }
foreach s in (S){ if(n>s) ops.append(T(n - s,String("-",s))) }
mcv:=fcn(op){ minCache[op[0]][2] }; // !ACK!, dig out steps
v,op := ops.reduce( // find min steps to get to op
'wrap(vo1,vo2){ if(mcv(vo1)<mcv(vo2)) vo1 else vo2 });
minCache[n]=T(v, op, 1 + minCache[v][2]) // this many steps to get to n
}
}
fcn stepsToOne(N){ // D & S are determined by minCache
ops,steps := Sink(String).write(N), minCache[N][2];
do(steps){ v,o,s := minCache[N]; ops.write(" ",o,"-->",N=v); }
return(steps,ops.close())
} |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Xanadu | Xanadu |
int abs(i: int) {
if (i >= 0) return i; else return -i;
}
unit print_dots(n: int) {
while (n > 0) { print_string("."); n = n - 1; }
return;
}
{size:int | 0 < size}
unit print_board (board[size]: int, size: int(size)) {
var: int n, row;;
invariant: [i:nat] (row: int(i))
for (row = 0; row < size; row = row + 1) {
n = board[row];
print_dots(n-1);
print_string("Q");
print_dots(size - n);
print_newline();
}
print_newline();
return;
}
{size:int, j:int | 0 <= j < size}
bool test (j: int(j), board[size]: int) {
var: int diff, i, qi, qj;;
qj = board[j];
invariant: [i:nat] (i: int(i))
for (i = 0; i < j; i = i + 1) {
qi = board[i]; diff = abs (qi - qj);
if (diff == 0) { return false; }
else { if (diff == j - i) return false; }
}
return true;
}
{size:int | 0 < size}
nat queen(size: int(size)) {
var: int board[], next, row; nat count;;
count = 0; row = 0; board = alloc(size, 0);
invariant: [n:nat | n < size] (row: int(n))
while (true) {
next = board[row]; next = next + 1;
if (next > size) {
if (row == 0) break; else { board[row] = 0; row = row - 1; }
} else {
board[row] = next;
if (test(row, board)) {
row = row + 1;
if (row == size) {
count = count + 1;
print_board(board, size);
row = row - 1;
}
}
}
}
return count;
}
int main () {
return queen (8);
} |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Wren | Wren | var M // forward declaration
var F = Fn.new { |n|
if (n == 0) return 1
return n - M.call(F.call(n-1))
}
M = Fn.new { |n|
if (n == 0) return 0
return n - F.call(M.call(n-1))
}
System.write("F(0..20): ")
(0..20).each { |i| System.write("%(F.call(i)) ") }
System.write("\nM(0..20): ")
(0..20).each { |i| System.write("%(M.call(i)) ") }
System.print() |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Picat | Picat | go =>
N=12,
make_table(N),
nl.
%
% Make a table of size N
%
make_table(N) =>
printf(" "),
foreach(I in 1..N) printf("%4w", I) end,
nl,
println(['-' : _ in 1..(N+1)*4+1]),
foreach(I in 1..N)
printf("%2d | ", I),
foreach(J in 1..N)
if J>=I then
printf("%4w", I*J)
else
printf(" ")
end
end,
nl
end,
nl. |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics the steps shown in the video.
1. Cards.
Create a common deck of cards of 52 cards (which are half red, half black).
Give the pack a good shuffle.
2. Deal from the shuffled deck, you'll be creating three piles.
Assemble the cards face down.
Turn up the top card and hold it in your hand.
if the card is black, then add the next card (unseen) to the "black" pile.
If the card is red, then add the next card (unseen) to the "red" pile.
Add the top card that you're holding to the discard pile. (You might optionally show these discarded cards to get an idea of the randomness).
Repeat the above for the rest of the shuffled deck.
3. Choose a random number (call it X) that will be used to swap cards from the "red" and "black" piles.
Randomly choose X cards from the "red" pile (unseen), let's call this the "red" bunch.
Randomly choose X cards from the "black" pile (unseen), let's call this the "black" bunch.
Put the "red" bunch into the "black" pile.
Put the "black" bunch into the "red" pile.
(The above two steps complete the swap of X cards of the "red" and "black" piles.
(Without knowing what those cards are --- they could be red or black, nobody knows).
4. Order from randomness?
Verify (or not) the mathematician's assertion that:
The number of black cards in the "black" pile equals the number of red cards in the "red" pile.
(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)
Show output on this page.
| #AutoHotkey | AutoHotkey | ;==========================================================
; create cards
cards := [], suits := ["♠","♥","♦","♣"], num := 0
for i, v in StrSplit("A,2,3,4,5,6,7,8,9,10,J,Q,K",",")
for i, suit in suits
cards[++num] := v suit
;==========================================================
; create gui
w := 40
Gui, font, S10
Gui, font, S10 CRed
Gui, add, text, w100 , Face Up Red
loop, 26
Gui, add, button, % "x+0 w" w " vFR" A_Index
Gui, add, text, xs w100 , Face Down
loop, 26
Gui, add, button, % "x+0 w" w " vHR" A_Index
Gui, font, S10 CBlack
Gui, add, text, xs w100 , Face Up Black
loop, 26
Gui, add, button, % "x+0 w" w " vFB" A_Index
Gui, add, text, xs w100 , Face Down
loop, 26
Gui, add, button, % "x+0 w" w " vHB" A_Index
Gui, add, button, xs gShuffle , Shuffle
Gui, add, button, x+1 Disabled vDeal gDeal , Deal
Gui, add, button, x+1 Disabled vMove gMove, Move
Gui, add, button, x+1 Disabled vShowAll gShowAll , Show All
Gui, add, button, x+1 Disabled vPeak gPeak, Peak
Gui, add, StatusBar
Gui, show
SB_SetParts(200,200)
SB_SetText("0 Face Down Red Cards", 1)
SB_SetText("0 Face Down Black Cards", 2)
return
;==========================================================
Shuffle:
list := "", shuffled := []
Loop, 52
list .= A_Index ","
list := Trim(list, ",")
Sort, list, Random D,
loop, parse, list, `,
shuffled[A_Index] := cards[A_LoopField]
loop, 26{
GuiControl,, % "FR" A_Index
GuiControl,, % "FB" A_Index
GuiControl,, % "HR" A_Index
GuiControl,, % "HB" A_Index
}
GuiControl, Enable, Deal
GuiControl, Disable, Move
GuiControl, Disable, ShowAll
GuiControl, Enable, Peak
return
;==========================================================
peak:
list := ""
for i, v in shuffled
list .= i ": " v (mod(i,2)?"`t":"`n")
ToolTip , % list, 1000, 0
return
;==========================================================
Deal:
Color := "",
GuiControl, Disable, Deal
FaceRed:= [], FaceBlack := [], HiddenRed := [], HiddenBlack := [], toggle := 0
for i, card in shuffled
if toggle:=!toggle {
if InStr(card, "♥") || InStr(card, "♦") {
Color := "Red"
faceRed.push(card)
GuiControl,, % "FR" faceRed.Count(), % card
}
else if InStr(card, "♠") || InStr(card, "♣") {
Color := "Black"
faceBlack.push(card)
GuiControl,, % "FB" faceBlack.Count(), % card
}
}
else{
Hidden%Color%.push(card)
GuiControl,, % (color="red"?"HR":"HB") Hidden%Color%.Count(), % "?"
Sleep, 50
}
GuiControl, Enable, Move
GuiControl, Enable, ShowAll
return
;==========================================================
Move:
tempR := [], tempB := []
Random, rndcount, 1, % HiddenRed.Count() < HiddenBlack.Count() ? HiddenRed.Count() : HiddenBlack.Count()
loop, % rndcount{
Random, rnd, 1, % HiddenRed.Count()
Random, rnd, 1, % HiddenBlack.Count()
tempR.push(HiddenRed.RemoveAt(rnd))
tempB.push(HiddenBlack.RemoveAt(rnd))
}
list := ""
for i, v in tempR
list .= v "`t" tempB[i] "`n"
MsgBox % "swapping " rndcount " cards between face down Red and face down Black`n" (ShowAll?"Red`tBlack`n" list:"")
for i, v in tempR
HiddenBlack.Push(v)
for i, v in tempB
HiddenRed.push(v)
if ShowAll
gosub, ShowAll
return
;==========================================================
ShowAll:
ShowAll := true, countR := countB := 0
loop, 26{
GuiControl,, % "HR" A_Index
GuiControl,, % "HB" A_Index
}
for i, card in HiddenRed
GuiControl,, % "HR" i, % (card~= "[♥♦]"?"[":"") card (card~= "[♥♦]"?"]":"")
, countR := (card~= "[♥♦]") ? countR+1 : countR
for i, card in HiddenBlack
GuiControl,, % "HB" i, % (card~= "[♠♣]"?"[":"") card (card~= "[♠♣]"?"]":"")
, countB := (card~= "[♠♣]") ? countB+1 : countB
SB_SetText(countR " Face Down Red Cards", 1)
SB_SetText(countB " Face Down Black Cards", 2)
return
;========================================================== |
http://rosettacode.org/wiki/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, for all i and j less than or equal to n.
The Task
Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence.
Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence.
Demonstrating working through the first few terms longhand:
a1 = 1
1 + 1 = 2
Speculatively try a2 = 2
1 + 1 = 2
1 + 2 = 3
2 + 2 = 4
There are no repeated sums so 2 is the next number in the sequence.
Speculatively try a3 = 3
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
2 + 2 = 4
2 + 3 = 5
3 + 3 = 6
Sum of 4 is repeated so 3 is rejected.
Speculatively try a3 = 4
1 + 1 = 2
1 + 2 = 3
1 + 4 = 5
2 + 2 = 4
2 + 4 = 6
4 + 4 = 8
There are no repeated sums so 4 is the next number in the sequence.
And so on...
See also
OEIS:A005282 Mian-Chowla sequence | #ALGOL_68 | ALGOL 68 | # Find Mian-Chowla numbers: an
where: ai = 1,
and: an = smallest integer such that ai + aj is unique
for all i, j in 1 .. n && i <= j
#
BEGIN
INT max mc = 100;
[ max mc ]INT mc;
INT curr size := 0; # initial size of the array #
INT size increment = 10 000; # size to increase the array by #
REF[]BOOL is sum := HEAP[ 1 : 0 ]BOOL;
INT mc count := 1;
FOR i WHILE mc count <= max mc DO
# assume i will be part of the sequence #
mc[ mc count ] := i;
# check the sums #
IF ( 2 * i ) > curr size THEN
# the is sum array is too small - make a larger one #
REF[]BOOL new sum = HEAP[ curr size + size increment ]BOOL;
new sum[ 1 : curr size ] := is sum;
FOR n TO size increment DO new sum[ curr size + n ] := FALSE OD;
curr size +:= size increment;
is sum := new sum
FI;
BOOL is unique := TRUE;
FOR mc pos TO mc count WHILE is unique := NOT is sum[ i + mc[ mc pos ] ] DO SKIP OD;
IF is unique THEN
# i is a sequence element - store the sums #
FOR k TO mc count DO is sum[ i + mc[ k ] ] := TRUE OD;
mc count +:= 1
FI
OD;
# print parts of the sequence #
print( ( "Mian Chowla sequence elements 1..30:", newline ) );
FOR i TO 30 DO print( ( " ", whole( mc[ i ], 0 ) ) ) OD;
print( ( newline ) );
print( ( "Mian Chowla sequence elements 91..100:", newline ) );
FOR i FROM 91 TO 100 DO print( ( " ", whole( mc[ i ], 0 ) ) ) OD
END |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #C.23 | C# | using System;
using System.Drawing;
using System.Windows.Forms;
class MineFieldModel
{
public int RemainingMinesCount{
get{
var count = 0;
ForEachCell((i,j)=>{
if (Mines[i,j] && !Marked[i,j])
count++;
});
return count;
}
}
public bool[,] Mines{get; private set;}
public bool[,] Opened{get;private set;}
public bool[,] Marked{get; private set;}
public int[,] Values{get;private set; }
public int Width{ get{return Mines.GetLength(1);} }
public int Height{ get{return Mines.GetLength(0);} }
public MineFieldModel(bool[,] mines)
{
this.Mines = mines;
this.Opened = new bool[Height, Width]; // filled with 'false' by default
this.Marked = new bool[Height, Width];
this.Values = CalculateValues();
}
private int[,] CalculateValues()
{
int[,] values = new int[Height, Width];
ForEachCell((i,j) =>{
var value = 0;
ForEachNeighbor(i,j, (i1,j1)=>{
if (Mines[i1,j1])
value++;
});
values[i,j] = value;
});
return values;
}
// Helper method for iterating over cells
public void ForEachCell(Action<int,int> action)
{
for (var i = 0; i < Height; i++)
for (var j = 0; j < Width; j++)
action(i,j);
}
// Helper method for iterating over cells' neighbors
public void ForEachNeighbor(int i, int j, Action<int,int> action)
{
for (var i1 = i-1; i1 <= i+1; i1++)
for (var j1 = j-1; j1 <= j+1; j1++)
if (InBounds(j1, i1) && !(i1==i && j1 ==j))
action(i1, j1);
}
private bool InBounds(int x, int y)
{
return y >= 0 && y < Height && x >=0 && x < Width;
}
public event Action Exploded = delegate{};
public event Action Win = delegate{};
public event Action Updated = delegate{};
public void OpenCell(int i, int j){
if(!Opened[i,j]){
if (Mines[i,j])
Exploded();
else{
OpenCellsStartingFrom(i,j);
Updated();
CheckForVictory();
}
}
}
void OpenCellsStartingFrom(int i, int j)
{
Opened[i,j] = true;
ForEachNeighbor(i,j, (i1,j1)=>{
if (!Mines[i1,j1] && !Opened[i1,j1] && !Marked[i1,j1])
OpenCellsStartingFrom(i1, j1);
});
}
void CheckForVictory(){
int notMarked = 0;
int wrongMarked = 0;
ForEachCell((i,j)=>{
if (Mines[i,j] && !Marked[i,j])
notMarked++;
if (!Mines[i,j] && Marked[i,j])
wrongMarked++;
});
if (notMarked == 0 && wrongMarked == 0)
Win();
}
public void Mark(int i, int j){
if (!Opened[i,j])
Marked[i,j] = true;
Updated();
CheckForVictory();
}
}
class MineFieldView: UserControl{
public const int CellSize = 40;
MineFieldModel _model;
public MineFieldModel Model{
get{ return _model; }
set
{
_model = value;
this.Size = new Size(_model.Width * CellSize+1, _model.Height * CellSize+2);
}
}
public MineFieldView(){
//Enable double-buffering to eliminate flicker
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer,true);
this.Font = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);
this.MouseUp += (o,e)=>{
Point cellCoords = GetCell(e.Location);
if (Model != null)
{
if (e.Button == MouseButtons.Left)
Model.OpenCell(cellCoords.Y, cellCoords.X);
else if (e.Button == MouseButtons.Right)
Model.Mark(cellCoords.Y, cellCoords.X);
}
};
}
Point GetCell(Point coords)
{
var rgn = ClientRectangle;
var x = (coords.X - rgn.X)/CellSize;
var y = (coords.Y - rgn.Y)/CellSize;
return new Point(x,y);
}
static readonly Brush MarkBrush = new SolidBrush(Color.Blue);
static readonly Brush ValueBrush = new SolidBrush(Color.Black);
static readonly Brush UnexploredBrush = new SolidBrush(SystemColors.Control);
static readonly Brush OpenBrush = new SolidBrush(SystemColors.ControlDark);
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var g = e.Graphics;
if (Model != null)
{
Model.ForEachCell((i,j)=>
{
var bounds = new Rectangle(j * CellSize, i * CellSize, CellSize, CellSize);
if (Model.Opened[i,j])
{
g.FillRectangle(OpenBrush, bounds);
if (Model.Values[i,j] > 0)
{
DrawStringInCenter(g, Model.Values[i,j].ToString(), ValueBrush, bounds);
}
}
else
{
g.FillRectangle(UnexploredBrush, bounds);
if (Model.Marked[i,j])
{
DrawStringInCenter(g, "?", MarkBrush, bounds);
}
var outlineOffset = 1;
var outline = new Rectangle(bounds.X+outlineOffset, bounds.Y+outlineOffset, bounds.Width-2*outlineOffset, bounds.Height-2*outlineOffset);
g.DrawRectangle(Pens.Gray, outline);
}
g.DrawRectangle(Pens.Black, bounds);
});
}
}
static readonly StringFormat FormatCenter = new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment=StringAlignment.Center
};
void DrawStringInCenter(Graphics g, string s, Brush brush, Rectangle bounds)
{
PointF center = new PointF(bounds.X + bounds.Width/2, bounds.Y + bounds.Height/2);
g.DrawString(s, this.Font, brush, center, FormatCenter);
}
}
class MineSweepForm: Form
{
MineFieldModel CreateField(int width, int height)
{
var field = new bool[height, width];
int mineCount = (int)(0.2 * height * width);
var rnd = new Random();
while(mineCount > 0)
{
var x = rnd.Next(width);
var y = rnd.Next(height);
if (!field[y,x])
{
field[y,x] = true;
mineCount--;
}
}
return new MineFieldModel(field);
}
public MineSweepForm()
{
var model = CreateField(6, 4);
var counter = new Label{ };
counter.Text = model.RemainingMinesCount.ToString();
var view = new MineFieldView
{
Model = model, BorderStyle = BorderStyle.FixedSingle,
};
var stackPanel = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.TopDown,
Controls = {counter, view}
};
this.Controls.Add(stackPanel);
model.Updated += delegate{
view.Invalidate();
counter.Text = model.RemainingMinesCount.ToString();
};
model.Exploded += delegate {
MessageBox.Show("FAIL!");
Close();
};
model.Win += delegate {
MessageBox.Show("WIN!");
view.Enabled = false;
};
}
}
class Program
{
static void Main()
{
Application.Run(new MineSweepForm());
}
} |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #Go | Go | package main
import (
"fmt"
"github.com/shabbyrobe/go-num"
"strings"
"time"
)
func b10(n int64) {
if n == 1 {
fmt.Printf("%4d: %28s %-24d\n", 1, "1", 1)
return
}
n1 := n + 1
pow := make([]int64, n1)
val := make([]int64, n1)
var count, ten, x int64 = 0, 1, 1
for ; x < n1; x++ {
val[x] = ten
for j := int64(0); j < n1; j++ {
if pow[j] != 0 && pow[(j+ten)%n] == 0 && pow[j] != x {
pow[(j+ten)%n] = x
}
}
if pow[ten] == 0 {
pow[ten] = x
}
ten = (10 * ten) % n
if pow[0] != 0 {
break
}
}
x = n
if pow[0] != 0 {
s := ""
for x != 0 {
p := pow[x%n]
if count > p {
s += strings.Repeat("0", int(count-p))
}
count = p - 1
s += "1"
x = (n + x - val[p]) % n
}
if count > 0 {
s += strings.Repeat("0", int(count))
}
mpm := num.MustI128FromString(s)
mul := mpm.Quo64(n)
fmt.Printf("%4d: %28s %-24d\n", n, s, mul)
} else {
fmt.Println("Can't do it!")
}
}
func main() {
start := time.Now()
tests := [][]int64{{1, 10}, {95, 105}, {297}, {576}, {594}, {891}, {909}, {999},
{1998}, {2079}, {2251}, {2277}, {2439}, {2997}, {4878}}
fmt.Println(" n B10 multiplier")
fmt.Println("----------------------------------------------")
for _, test := range tests {
from := test[0]
to := from
if len(test) == 2 {
to = test[1]
}
for n := from; n <= to; n++ {
b10(n)
}
}
fmt.Printf("\nTook %s\n", time.Since(start))
} |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #Frink | Frink | a = 2988348162058574136915891421498819466320163312926952423791023078876139
b = 2351399303373464486466122544523690094744975233415544072992656881240319
println[modPow[a,b,10^40]] |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #GAP | GAP | # Built-in
a := 2988348162058574136915891421498819466320163312926952423791023078876139;
b := 2351399303373464486466122544523690094744975233415544072992656881240319;
PowerModInt(a, b, 10^40);
1527229998585248450016808958343740453059
# Implementation
PowerModAlt := function(a, n, m)
local r;
r := 1;
while n > 0 do
if IsOddInt(n) then
r := RemInt(r*a, m);
fi;
n := QuoInt(n, 2);
a := RemInt(a*a, m);
od;
return r;
end;
PowerModAlt(a, b, 10^40); |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.
However, the playing of the sounds should not interfere with the timing of the metronome.
The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.
If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
--This package is for the delay.
with Ada.Calendar; use Ada.Calendar;
--This package adds sound
with Ada.Characters.Latin_1;
procedure Main is
begin
Put_Line ("Hello, this is 60 BPM");
loop
Ada.Text_IO.Put (Ada.Characters.Latin_1.BEL);
delay 0.9; --Delay in seconds. If you change to 0.0 the program will crash.
end loop;
end Main; |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
| #ALGOL_68 | ALGOL 68 | SEMA sem = LEVEL 1;
PROC job = (INT n)VOID: (
printf(($" Job "d" acquired Semaphore ..."$,n));
TO 10000000 DO SKIP OD;
printf(($" Job "d" releasing Semaphore"l$,n))
);
PAR (
( DOWN sem ; job(1) ; UP sem ) ,
( DOWN sem ; job(2) ; UP sem ) ,
( DOWN sem ; job(3) ; UP sem )
) |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"TIMERLIB"
DIM tID%(6)
REM Two workers may be concurrent
DIM Semaphore%(2)
tID%(6) = FN_ontimer(11, PROCtimer6, 1)
tID%(5) = FN_ontimer(10, PROCtimer5, 1)
tID%(4) = FN_ontimer(11, PROCtimer4, 1)
tID%(3) = FN_ontimer(10, PROCtimer3, 1)
tID%(2) = FN_ontimer(11, PROCtimer2, 1)
tID%(1) = FN_ontimer(10, PROCtimer1, 1)
ON CLOSE PROCcleanup : QUIT
ON ERROR PRINT REPORT$ : PROCcleanup : END
sc% = 0
REPEAT
oldsc% = sc%
sc% = -SUM(Semaphore%())
IF sc%<>oldsc% PRINT "Semaphore count now ";sc%
WAIT 0
UNTIL FALSE
DEF PROCtimer1 : PROCtask(1) : ENDPROC
DEF PROCtimer2 : PROCtask(2) : ENDPROC
DEF PROCtimer3 : PROCtask(3) : ENDPROC
DEF PROCtimer4 : PROCtask(4) : ENDPROC
DEF PROCtimer5 : PROCtask(5) : ENDPROC
DEF PROCtimer6 : PROCtask(6) : ENDPROC
DEF PROCtask(n%)
LOCAL i%, temp%
PRIVATE delay%(), sem%()
DIM delay%(6), sem%(6)
IF delay%(n%) THEN
delay%(n%) -= 1
IF delay%(n%) = 0 THEN
SWAP Semaphore%(sem%(n%)),temp%
delay%(n%) = -1
PRINT "Task " ; n% " released semaphore"
ENDIF
ENDPROC
ENDIF
FOR i% = 1 TO DIM(Semaphore%(),1)
temp% = TRUE
SWAP Semaphore%(i%),temp%
IF NOT temp% EXIT FOR
NEXT
IF temp% THEN ENDPROC : REM Waiting to acquire semaphore
sem%(n%) = i%
delay%(n%) = 200
PRINT "Task "; n% " acquired semaphore"
ENDPROC
DEF PROCcleanup
LOCAL i%
FOR i% = 1 TO 6
PROC_killtimer(tID%(i%))
NEXT
ENDPROC |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #Phix | Phix | type mi(object m)
return sequence(m) and length(m)=2 and integer(m[1]) and integer(m[2])
end type
type mii(object m)
return mi(m) or atom(m)
end type
function mi_one(mii a)
if atom(a) then a=1 else a = {1,a[2]} end if
return a
end function
function mi_add(mii a, mii b)
if atom(a) then
if not atom(b) then throw("error") end if
return a+b
end if
if a[2]!=b[2] then throw("error") end if
a[1] = mod(a[1]+b[1],a[2])
return a
end function
function mi_mul(mii a, mii b)
if atom(a) then
if not atom(b) then throw("error") end if
return a*b
end if
if a[2]!=b[2] then throw("error") end if
a[1] = mod(a[1]*b[1],a[2])
return a
end function
function mi_power(mii x, integer p)
mii res = mi_one(x)
for i=1 to p do
res = mi_mul(res,x)
end for
return res
end function
function mi_print(mii m)
return sprintf(iff(atom(m)?"%g":"modint(%d,%d)"),m)
end function
function f(mii x)
return mi_add(mi_power(x,100),mi_add(x,mi_one(x)))
end function
procedure test(mii x)
printf(1,"x^100 + x + 1 for x == %s is %s\n",{mi_print(x),mi_print(f(x))})
end procedure
test(10)
test({10,13})
|
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #XPL0 | XPL0 | def N=8; \board size (NxN)
int R, C; \row and column of board
char B(N,N); \board
include c:\cxpl\codes;
proc Try; \Try adding a queen to the board
int R; \row, for each level of recursion
func Okay;
\Returns 'true' if no row, column, or diagonal from square R,C has a queen
int I;
[for I:= 0 to N-1 do
[if B(I,C) then return false; \row is occupied
if B(R,I) then return false; \column is occupied
if R+I<N & C+I<N then
if B(R+I, C+I) then return false; \diagonal down right
if R-I>=0 & C-I>=0 then
if B(R-I, C-I) then return false; \diagonal up left
if R-I>=0 & C+I<N then
if B(R-I, C+I) then return false; \diagonal up right
if R+I<N & C-I>=0 then
if B(R+I, C-I) then return false; \diagonal down left
];
return true;
]; \Okay
[ \Try
if C>=N then
[for R:= 0 to N-1 do \display solution
[ChOut(0, ^ ); \(avoids scrolling up a color)
for C:= 0 to N-1 do
[Attrib(if (R|C)&1 then $0F else $4F); \checkerboard pattern
ChOut(6, if B(R,C) then $F2 else ^ ); \cute queen symbol
ChOut(6, if B(R,C) then $F3 else ^ );
];
CrLf(0);
];
exit; \one solution is enough
];
for R:= 0 to N-1 do
[if Okay(R,C) then \a queen can be placed here
[B(R,C):= true; \ so do it
C:= C+1; \move to next column
Try; \ and try from there
C:= C-1; \didn't work: backup
B(R,C):= false; \undo queen placement
];
];
]; \Try
[for R:= 0 to N-1 do \clear the board
for C:= 0 to N-1 do
B(R,C):= false;
C:= 0; \start at left column
Try;
] |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #x86_Assembly | x86 Assembly | global main
extern printf
section .text
func_f
mov eax, [esp+4]
cmp eax, 0
jz f_ret
dec eax
push eax
call func_f
mov [esp+0], eax
call func_m
add esp, 4
mov ebx, [esp+4]
sub ebx, eax
mov eax, ebx
ret
f_ret
mov eax, 1
ret
func_m
mov eax, [esp+4]
cmp eax, 0
jz m_ret
dec eax
push eax
call func_m
mov [esp+0], eax
call func_f
add esp, 4
mov ebx, [esp+4]
sub ebx, eax
mov eax, ebx
ret
m_ret
xor eax, eax
ret
main
mov edx, func_f
call output_res
mov edx, func_m
call output_res
ret
output_res
xor ecx, ecx
loop0
push ecx
call edx
push edx
push eax
push form
call printf
add esp, 8
pop edx
pop ecx
inc ecx
cmp ecx, 20
jnz loop0
push newline
call printf
add esp, 4
ret
section .rodata
form
db '%d ',0
newline
db 10,0
end |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #PicoLisp | PicoLisp | sp>(de mulTable (N)
(space 4)
(for X N
(prin (align 4 X)) )
(prinl)
(prinl)
(for Y N
(prin (align 4 Y))
(space (* (dec Y) 4))
(for (X Y (>= N X) (inc X))
(prin (align 4 (* X Y))) )
(prinl) ) )
(mulTable 12) |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics the steps shown in the video.
1. Cards.
Create a common deck of cards of 52 cards (which are half red, half black).
Give the pack a good shuffle.
2. Deal from the shuffled deck, you'll be creating three piles.
Assemble the cards face down.
Turn up the top card and hold it in your hand.
if the card is black, then add the next card (unseen) to the "black" pile.
If the card is red, then add the next card (unseen) to the "red" pile.
Add the top card that you're holding to the discard pile. (You might optionally show these discarded cards to get an idea of the randomness).
Repeat the above for the rest of the shuffled deck.
3. Choose a random number (call it X) that will be used to swap cards from the "red" and "black" piles.
Randomly choose X cards from the "red" pile (unseen), let's call this the "red" bunch.
Randomly choose X cards from the "black" pile (unseen), let's call this the "black" bunch.
Put the "red" bunch into the "black" pile.
Put the "black" bunch into the "red" pile.
(The above two steps complete the swap of X cards of the "red" and "black" piles.
(Without knowing what those cards are --- they could be red or black, nobody knows).
4. Order from randomness?
Verify (or not) the mathematician's assertion that:
The number of black cards in the "black" pile equals the number of red cards in the "red" pile.
(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)
Show output on this page.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define SIM_N 5 /* Run 5 simulations */
#define PRINT_DISCARDED 1 /* Whether or not to print the discard pile */
#define min(x,y) ((x<y)?(x):(y))
typedef uint8_t card_t;
/* Return a random number from an uniform distribution (0..n-1) */
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
/* Find how many bits to mask off */
while (mask < n) mask = mask<<1 | 1;
/* Generate random number */
do {
out = rand() & mask;
} while (out >= n);
return out;
}
/* Return a random card (0..51) from an uniform distribution */
card_t rand_card() {
return rand_n(52);
}
/* Print a card */
void print_card(card_t card) {
static char *suits = "HCDS"; /* hearts, clubs, diamonds and spades */
static char *cards[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
printf(" %s%c", cards[card>>2], suits[card&3]);
}
/* Shuffle a pack */
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
/* Do the card trick, return whether cards match */
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
/* Create and shuffle a pack */
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
/* Deal cards */
#if PRINT_DISCARDED
printf("Discarded:"); /* Print the discard pile */
#endif
for (card=0; card<52; card += 2) {
top = pack[card]; /* Take card */
if (top & 1) { /* Add next card to black or red pile */
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
#if PRINT_DISCARDED
print_card(top); /* Show which card is discarded */
#endif
}
#if PRINT_DISCARDED
printf("\n");
#endif
/* Swap an amount of cards */
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
/* Pick a random card from the black and red pile to swap */
blacksw = rand_n(blackn);
redsw = rand_n(redn);
/* Swap them */
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
/* Verify the assertion */
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf("The number of black cards in the 'black' pile"
" %s the number of red cards in the 'red' pile.\n",
result? "equals" : "does not equal");
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
/* Seed the RNG with bytes from from /dev/urandom */
if ((r = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, "cannot open /dev/urandom\n");
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, "failed to read from /dev/urandom\n");
return 255;
}
fclose(r);
srand(seed);
/* Do simulations. */
for (i=1; i<=SIM_N; i++) {
printf("Simulation %d\n", i);
successes += trick();
printf("\n");
}
printf("Result: %d successes out of %d simulations\n",
successes, SIM_N);
return 0;
} |
http://rosettacode.org/wiki/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, for all i and j less than or equal to n.
The Task
Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence.
Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence.
Demonstrating working through the first few terms longhand:
a1 = 1
1 + 1 = 2
Speculatively try a2 = 2
1 + 1 = 2
1 + 2 = 3
2 + 2 = 4
There are no repeated sums so 2 is the next number in the sequence.
Speculatively try a3 = 3
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
2 + 2 = 4
2 + 3 = 5
3 + 3 = 6
Sum of 4 is repeated so 3 is rejected.
Speculatively try a3 = 4
1 + 1 = 2
1 + 2 = 3
1 + 4 = 5
2 + 2 = 4
2 + 4 = 6
4 + 4 = 8
There are no repeated sums so 4 is the next number in the sequence.
And so on...
See also
OEIS:A005282 Mian-Chowla sequence | #Arturo | Arturo | mianChowla: function [n][
result: new [1]
sums: new [2]
candidate: 1
while [n > size result][
fit: false
'result ++ 0
while [not? fit][
candidate: candidate + 1
fit: true
result\[dec size result]: candidate
loop result 'val [
if contains? sums val + candidate [
fit: false
break
]
]
]
loop result 'val [
'sums ++ val + candidate
unique 'sums
]
]
return result
]
seq100: mianChowla 100
print "The first 30 terms of the Mian-Chowla sequence are:"
print slice seq100 0 29
print ""
print "Terms 91 to 100 of the sequence are:"
print slice seq100 90 99 |
http://rosettacode.org/wiki/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, for all i and j less than or equal to n.
The Task
Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence.
Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence.
Demonstrating working through the first few terms longhand:
a1 = 1
1 + 1 = 2
Speculatively try a2 = 2
1 + 1 = 2
1 + 2 = 3
2 + 2 = 4
There are no repeated sums so 2 is the next number in the sequence.
Speculatively try a3 = 3
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
2 + 2 = 4
2 + 3 = 5
3 + 3 = 6
Sum of 4 is repeated so 3 is rejected.
Speculatively try a3 = 4
1 + 1 = 2
1 + 2 = 3
1 + 4 = 5
2 + 2 = 4
2 + 4 = 6
4 + 4 = 8
There are no repeated sums so 4 is the next number in the sequence.
And so on...
See also
OEIS:A005282 Mian-Chowla sequence | #AWK | AWK | # Find Mian-Chowla numbers: an
# where: ai = 1,
# and: an = smallest integer such that ai + aj is unique
# for all i, j in 1 .. n && i <= j
#
BEGIN \
{
FALSE = 0;
TRUE = 1;
mcCount = 1;
for( i = 1; mcCount <= 100; i ++ )
{
# assume i will be part of the sequence
mc[ mcCount ] = i;
# check the sums
isUnique = TRUE;
for( mcPos = 1; mcPos <= mcCount && isUnique; mcPos ++ )
{
isUnique = ! ( ( i + mc[ mcPos ] ) in isSum );
} # for j
if( isUnique )
{
# i is a sequence element - store the sums
for( k = 1; k <= mcCount; k ++ )
{
isSum[ i + mc[ k ] ] = TRUE;
} # for k
mcCount ++;
} # if isUnique
} # for i
# print the sequence
printf( "Mian Chowla sequence elements 1..30:\n" );
for( i = 1; i <= 30; i ++ )
{
printf( " %d", mc[ i ] );
} # for i
printf( "\n" );
printf( "Mian Chowla sequence elements 91..100:\n" );
for( i = 91; i <= 100; i ++ )
{
printf( " %d", mc[ i ] );
} # for i
printf( "\n" );
} # BEGIN |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #C.2B.2B | C++ |
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
typedef unsigned char byte;
enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR };
class fieldData
{
public:
fieldData() : value( CLOSED ), open( false ) {}
byte value;
bool open, mine;
};
class game
{
public:
~game()
{ if( field ) delete [] field; }
game( int x, int y )
{
go = false; wid = x; hei = y;
field = new fieldData[x * y];
memset( field, 0, x * y * sizeof( fieldData ) );
oMines = ( ( 22 - rand() % 11 ) * x * y ) / 100;
mMines = 0;
int mx, my, m = 0;
for( ; m < oMines; m++ )
{
do
{ mx = rand() % wid; my = rand() % hei; }
while( field[mx + wid * my].mine );
field[mx + wid * my].mine = true;
}
graphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*';
graphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X';
}
void gameLoop()
{
string c, r, a;
int col, row;
while( !go )
{
drawBoard();
cout << "Enter column, row and an action( c r a ):\nActions: o => open, f => flag, ? => unknown\n";
cin >> c >> r >> a;
if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32;
col = c[0] - 65; row = r[0] - 49;
makeMove( col, row, a );
}
}
private:
void makeMove( int x, int y, string a )
{
fieldData* fd = &field[wid * y + x];
if( fd->open && fd->value < CLOSED )
{
cout << "This cell is already open!";
Sleep( 3000 ); return;
}
if( a[0] == 'O' ) openCell( x, y );
else if( a[0] == 'F' )
{
fd->open = true;
fd->value = FLAG;
mMines++;
checkWin();
}
else
{
fd->open = true;
fd->value = UNKNOWN;
}
}
bool openCell( int x, int y )
{
if( !isInside( x, y ) ) return false;
if( field[x + y * wid].mine ) boom();
else
{
if( field[x + y * wid].value == FLAG )
{
field[x + y * wid].value = CLOSED;
field[x + y * wid].open = false;
mMines--;
}
recOpen( x, y );
checkWin();
}
return true;
}
void drawBoard()
{
system( "cls" );
cout << "Marked mines: " << mMines << " from " << oMines << "\n\n";
for( int x = 0; x < wid; x++ )
cout << " " << ( char )( 65 + x ) << " ";
cout << "\n"; int yy;
for( int y = 0; y < hei; y++ )
{
yy = y * wid;
for( int x = 0; x < wid; x++ )
cout << "+---";
cout << "+\n"; fieldData* fd;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy]; cout<< "| ";
if( !fd->open ) cout << ( char )graphs[1] << " ";
else
{
if( fd->value > 9 )
cout << ( char )graphs[fd->value - 9] << " ";
else
{
if( fd->value < 1 ) cout << " ";
else cout << ( char )(fd->value + 48 ) << " ";
}
}
}
cout << "| " << y + 1 << "\n";
}
for( int x = 0; x < wid; x++ )
cout << "+---";
cout << "+\n\n";
}
void checkWin()
{
int z = wid * hei - oMines, yy;
fieldData* fd;
for( int y = 0; y < hei; y++ )
{
yy = wid * y;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy];
if( fd->open && fd->value != FLAG ) z--;
}
}
if( !z ) lastMsg( "Congratulations, you won the game!");
}
void boom()
{
int yy; fieldData* fd;
for( int y = 0; y < hei; y++ )
{
yy = wid * y;
for( int x = 0; x < wid; x++ )
{
fd = &field[x + yy];
if( fd->value == FLAG )
{
fd->open = true;
fd->value = fd->mine ? MINE : ERR;
}
else if( fd->mine )
{
fd->open = true;
fd->value = MINE;
}
}
}
lastMsg( "B O O O M M M M M !" );
}
void lastMsg( string s )
{
go = true; drawBoard();
cout << s << "\n\n";
}
bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); }
void recOpen( int x, int y )
{
if( !isInside( x, y ) || field[x + y * wid].open ) return;
int bc = getMineCount( x, y );
field[x + y * wid].open = true;
field[x + y * wid].value = bc;
if( bc ) return;
for( int yy = -1; yy < 2; yy++ )
for( int xx = -1; xx < 2; xx++ )
{
if( xx == 0 && yy == 0 ) continue;
recOpen( x + xx, y + yy );
}
}
int getMineCount( int x, int y )
{
int m = 0;
for( int yy = -1; yy < 2; yy++ )
for( int xx = -1; xx < 2; xx++ )
{
if( xx == 0 && yy == 0 ) continue;
if( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++;
}
return m;
}
int wid, hei, mMines, oMines;
fieldData* field; bool go;
int graphs[6];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
game g( 4, 6 ); g.gameLoop();
return system( "pause" );
}
|
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #Haskell | Haskell | import Data.Bifunctor (bimap)
import Data.List (find)
import Data.Maybe (isJust)
-- MINIMUM POSITIVE MULTIPLE IN BASE 10 USING ONLY 0 AND 1
b10 :: Integral a => a -> Integer
b10 n = read (digitMatch rems sums) :: Integer
where
(_, rems, _, Just (_, sums)) =
until
(\(_, _, _, mb) -> isJust mb)
( \(e, rems, ms, _) ->
let m = rem (10 ^ e) n
newSums =
(m, [m]) :
fmap (bimap (m +) (m :)) ms
in ( succ e,
m : rems,
ms <> newSums,
find
( (0 ==) . flip rem n . fst
)
newSums
)
)
(0, [], [], Nothing)
digitMatch :: Eq a => [a] -> [a] -> String
digitMatch [] _ = []
digitMatch xs [] = '0' <$ xs
digitMatch (x : xs) yys@(y : ys)
| x /= y = '0' : digitMatch xs yys
| otherwise = '1' : digitMatch xs ys
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
( putStrLn
. ( \x ->
let b = b10 x
in justifyRight 5 ' ' (show x)
<> " * "
<> justifyLeft 25 ' ' (show $ div b x)
<> " -> "
<> show b
)
)
( [1 .. 10]
<> [95 .. 105]
<> [297, 576, 594, 891, 909, 999]
)
justifyLeft, justifyRight :: Int -> a -> [a] -> [a]
justifyLeft n c s = take n (s <> replicate n c)
justifyRight n c = (drop . length) <*> (replicate n c <>) |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #gnuplot | gnuplot | _powm(b, e, m, r) = (e == 0 ? r : (e % 2 == 1 ? _powm(b * b % m, e / 2, m, r * b % m) : _powm(b * b % m, e / 2, m, r)))
powm(b, e, m) = _powm(b, e, m, 1)
# Usage
print powm(2, 3453, 131)
# Where b is the base, e is the exponent, m is the modulus, i.e.: b^e mod m |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
a, _ := new(big.Int).SetString(
"2988348162058574136915891421498819466320163312926952423791023078876139", 10)
b, _ := new(big.Int).SetString(
"2351399303373464486466122544523690094744975233415544072992656881240319", 10)
m := big.NewInt(10)
r := big.NewInt(40)
m.Exp(m, r, nil)
r.Exp(a, b, m)
fmt.Println(r)
} |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.
However, the playing of the sounds should not interfere with the timing of the metronome.
The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.
If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
| #AppleScript | AppleScript | set bpm to the text returned of (display dialog "How many beats per minute?" default answer 60)
set pauseBetweenBeeps to (60 / bpm)
repeat
beep
delay pauseBetweenBeeps
end repeat |
http://rosettacode.org/wiki/Metronome | Metronome |
The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.
However, the playing of the sounds should not interfere with the timing of the metronome.
The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.
If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
| #Arturo | Arturo | startMetronome: function [bpm,msr][
freq: 60000/bpm
i: 0
while [true][
loop msr-1 'x[
prints "\a"
pause freq
]
inc 'i
print ~"\aAND |i|"
pause freq
]
]
tempo: to :integer arg\0
beats: to :integer arg\1
startMetronome tempo beats |
http://rosettacode.org/wiki/Metered_concurrency | Metered concurrency | The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
| #C | C | #include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
sem_t sem;
int count = 3;
/* the whole point of a semaphore is that you don't count it:
* p/v are atomic. Unless it's locked while you are doing
* something with the count, the value is only informative */
#define getcount() count
void acquire()
{
sem_wait(&sem);
count--;
}
void release()
{
count++;
sem_post(&sem);
}
void* work(void * id)
{
int i = 10;
while (i--) {
acquire();
printf("#%d acquired sema at %d\n", *(int*)id, getcount());
usleep(rand() % 4000000); /* sleep 2 sec on average */
release();
usleep(0); /* effectively yield */
}
return 0;
}
int main()
{
pthread_t th[4];
int i, ids[] = {1, 2, 3, 4};
sem_init(&sem, 0, count);
for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
for (i = 4; i--;) pthread_join(th[i], 0);
printf("all workers done\n");
return sem_destroy(&sem);
} |
http://rosettacode.org/wiki/Modular_arithmetic | Modular arithmetic | Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence.
For any positive integer
p
{\displaystyle p}
called the congruence modulus,
two numbers
a
{\displaystyle a}
and
b
{\displaystyle b}
are said to be congruent modulo p whenever there exists an integer
k
{\displaystyle k}
such that:
a
=
b
+
k
p
{\displaystyle a=b+k\,p}
The corresponding set of equivalence classes forms a ring denoted
Z
p
Z
{\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}
.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetics, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
f
(
x
)
=
x
100
+
x
+
1
{\displaystyle f(x)=x^{100}+x+1}
You will use
13
{\displaystyle 13}
as the congruence modulus and you will compute
f
(
10
)
{\displaystyle f(10)}
.
It is important that the function
f
{\displaystyle f}
is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| #Prolog | Prolog | :- use_module(library(lambda)).
congruence(Congruence, In, Fun, Out) :-
maplist(Congruence +\X^Y^(Y is X mod Congruence), In, In1),
call(Fun, In1, Out1),
maplist(Congruence +\X^Y^(Y is X mod Congruence), Out1, Out).
fun_1([X], [Y]) :-
Y is X^100 + X + 1.
fun_2(L, [R]) :-
sum_list(L, R).
|
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #XSLT | XSLT |
15863724
16837425
... 88 lines omitted ...
83162574
84136275
|
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #XPL0 | XPL0 | code ChOut=8, CrLf=9, IntOut=11;
ffunc M; \forward-referenced function declaration
func F(N);
int N;
return if N=0 then 1 else N - M(F(N-1));
func M(N);
int N;
return if N=0 then 0 else N - F(M(N-1));
int I;
[for I:= 0 to 19 do [IntOut(0, F(I)); ChOut(0, ^ )];
CrLf(0);
for I:= 0 to 19 do [IntOut(0, M(I)); ChOut(0, ^ )];
CrLf(0);
] |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #PL.2FI | PL/I |
/* 12 x 12 multiplication table. */
multiplication_table: procedure options (main);
declare (i, j) fixed decimal (2);
put skip edit ((i do i = 1 to 12)) (X(4), 12 F(4));
put skip edit ( (49)'_') (X(3), A);
do i = 1 to 12;
put skip edit (i, ' |', (i*j do j = i to 12))
(F(2), a, col(i*4+1), 12 F(4));
end;
end multiplication_table;
|
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics the steps shown in the video.
1. Cards.
Create a common deck of cards of 52 cards (which are half red, half black).
Give the pack a good shuffle.
2. Deal from the shuffled deck, you'll be creating three piles.
Assemble the cards face down.
Turn up the top card and hold it in your hand.
if the card is black, then add the next card (unseen) to the "black" pile.
If the card is red, then add the next card (unseen) to the "red" pile.
Add the top card that you're holding to the discard pile. (You might optionally show these discarded cards to get an idea of the randomness).
Repeat the above for the rest of the shuffled deck.
3. Choose a random number (call it X) that will be used to swap cards from the "red" and "black" piles.
Randomly choose X cards from the "red" pile (unseen), let's call this the "red" bunch.
Randomly choose X cards from the "black" pile (unseen), let's call this the "black" bunch.
Put the "red" bunch into the "black" pile.
Put the "black" bunch into the "red" pile.
(The above two steps complete the swap of X cards of the "red" and "black" piles.
(Without knowing what those cards are --- they could be red or black, nobody knows).
4. Order from randomness?
Verify (or not) the mathematician's assertion that:
The number of black cards in the "black" pile equals the number of red cards in the "red" pile.
(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)
Show output on this page.
| #Crystal | Crystal | deck = ([:black, :red] * 26 ).shuffle
black_pile, red_pile, discard = [] of Symbol, [] of Symbol, [] of Symbol
until deck.empty?
discard << deck.pop
discard.last == :black ? black_pile << deck.pop : red_pile << deck.pop
end
x = rand( [black_pile.size, red_pile.size].min )
red_bunch = (0...x).map { red_pile.delete_at( rand( red_pile.size )) }
black_bunch = (0...x).map { black_pile.delete_at( rand( black_pile.size )) }
black_pile += red_bunch
red_pile += black_bunch
puts "The magician predicts there will be #{black_pile.count( :black )} red cards in the other pile.
Drumroll...
There were #{red_pile.count( :red )}!" |
http://rosettacode.org/wiki/Mian-Chowla_sequence | Mian-Chowla sequence | The Mian–Chowla sequence is an integer sequence defined recursively.
Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.
The sequence starts with:
a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
ai + aj
is distinct, for all i and j less than or equal to n.
The Task
Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence.
Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence.
Demonstrating working through the first few terms longhand:
a1 = 1
1 + 1 = 2
Speculatively try a2 = 2
1 + 1 = 2
1 + 2 = 3
2 + 2 = 4
There are no repeated sums so 2 is the next number in the sequence.
Speculatively try a3 = 3
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
2 + 2 = 4
2 + 3 = 5
3 + 3 = 6
Sum of 4 is repeated so 3 is rejected.
Speculatively try a3 = 4
1 + 1 = 2
1 + 2 = 3
1 + 4 = 5
2 + 2 = 4
2 + 4 = 6
4 + 4 = 8
There are no repeated sums so 4 is the next number in the sequence.
And so on...
See also
OEIS:A005282 Mian-Chowla sequence | #C | C | #include <stdio.h>
#include <stdbool.h>
#include <time.h>
#define n 100
#define nn ((n * (n + 1)) >> 1)
bool Contains(int lst[], int item, int size) {
for (int i = size - 1; i >= 0; i--)
if (item == lst[i]) return true;
return false;
}
int * MianChowla()
{
static int mc[n]; mc[0] = 1;
int sums[nn]; sums[0] = 2;
int sum, le, ss = 1;
for (int i = 1; i < n; i++) {
le = ss;
for (int j = mc[i - 1] + 1; ; j++) {
mc[i] = j;
for (int k = 0; k <= i; k++) {
sum = mc[k] + j;
if (Contains(sums, sum, ss)) {
ss = le; goto nxtJ;
}
sums[ss++] = sum;
}
break;
nxtJ:;
}
}
return mc;
}
int main() {
clock_t st = clock(); int * mc; mc = MianChowla();
double et = ((double)(clock() - st)) / CLOCKS_PER_SEC;
printf("The first 30 terms of the Mian-Chowla sequence are:\n");
for (int i = 0; i < 30; i++) printf("%d ", mc[i]);
printf("\n\nTerms 91 to 100 of the Mian-Chowla sequence are:\n");
for (int i = 90; i < 100; i++) printf("%d ", mc[i]);
printf("\n\nComputation time was %f seconds.", et);
} |
http://rosettacode.org/wiki/Metaprogramming | Metaprogramming | Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.
For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
| #ALGOL_68 | ALGOL 68 | # This example uses ALGOL 68 user defined operators to add a COBOL-style #
# "INSPECT statement" to ALGOL 68 #
# #
# The (partial) syntax of the COBOL INSPECT is: #
# INSPECT string-variable REPLACING ALL string BY string #
# or INSPECT string-variable REPLACING LEADING string BY string #
# or INSPECT string-variable REPLACING FIRST string BY string #
# #
# Because "BY" is a reserved bold word in ALGOL 68, we use "WITH" instead #
# #
# We define unary operators INSPECT, ALL, LEADING and FIRST #
# and binary operators REPLACING and WITH #
# We choose the priorities of REPLACING and WITH so that parenthesis is not #
# needed to ensure the correct interpretation of the "statement" #
# #
# We also provide a unary DISPLAY operator for a partial COBOL DISPLAY #
# statement #
# INSPECTEE is returned by the INSPECT unary operator #
MODE INSPECTEE = STRUCT( REF STRING item, INT option );
# INSPECTTOREPLACE is returned by the binary REPLACING operator #
MODE INSPECTTOREPLACE
= STRUCT( REF STRING item, INT option, STRING to replace );
# REPLACEMENT is returned by the unary ALL, LEADING and FIRST operators #
MODE REPLACEMENT = STRUCT( INT option, STRING replace );
# REPLACING option codes, these are the option values for a REPLACEMENT #
INT replace all = 1;
INT replace leading = 2;
INT replace first = 3;
OP INSPECT = ( REF STRING s )INSPECTEE: ( s, 0 );
OP ALL = ( STRING replace )REPLACEMENT: ( replace all, replace );
OP LEADING = ( STRING replace )REPLACEMENT: ( replace leading, replace );
OP FIRST = ( STRING replace )REPLACEMENT: ( replace first, replace );
OP ALL = ( CHAR replace )REPLACEMENT: ( replace all, replace );
OP LEADING = ( CHAR replace )REPLACEMENT: ( replace leading, replace );
OP FIRST = ( CHAR replace )REPLACEMENT: ( replace first, replace );
OP REPLACING = ( INSPECTEE inspected, REPLACEMENT replace )INSPECTTOREPLACE:
( item OF inspected
, option OF replace
, replace OF replace
);
OP WITH = ( INSPECTTOREPLACE inspected, CHAR replace with )REF STRING:
BEGIN
STRING with := replace with;
inspected WITH with
END; # WITH #
OP WITH = ( INSPECTTOREPLACE inspected, STRING replace with )REF STRING:
BEGIN
STRING to replace = to replace OF inspected;
INT pos := 0;
STRING rest := item OF inspected;
STRING result := "";
IF option OF inspected = replace all
THEN
# replace all occurances of "to replace" with "replace with" #
WHILE string in string( to replace, pos, rest )
DO
result +:= rest[ 1 : pos - 1 ] + replace with;
rest := rest[ pos + UPB to replace : ]
OD
ELIF option OF inspected = replace leading
THEN
# replace leading occurances of "to replace" with "replace with" #
WHILE IF string in string( to replace, pos, rest )
THEN
pos = 1
ELSE
FALSE
FI
DO
result +:= replace with;
rest := rest[ 1 + UPB to replace : ]
OD
ELIF option OF inspected = replace first
THEN
# replace first occurance of "to replace" with "replace with" #
IF string in string( to replace, pos, rest )
THEN
result +:= rest[ 1 : pos - 1 ] + replace with;
rest := rest[ pos + UPB to replace : ]
FI
ELSE
# unsupported replace option #
write( ( newline, "*** unsupported INSPECT REPLACING...", newline ) );
stop
FI;
result +:= rest;
item OF inspected := result
END; # WITH #
OP DISPLAY = ( STRING s )VOID: write( ( s, newline ) );
PRIO REPLACING = 2, WITH = 1;
main: (
# test the INSPECT and DISPLAY "verbs" #
STRING text := "some text";
DISPLAY text;
INSPECT text REPLACING FIRST "e" WITH "bbc";
DISPLAY text;
INSPECT text REPLACING ALL "b" WITH "X";
DISPLAY text;
INSPECT text REPLACING ALL "text" WITH "some";
DISPLAY text;
INSPECT text REPLACING LEADING "som" WITH "k";
DISPLAY text
) |
http://rosettacode.org/wiki/Metallic_ratios | Metallic ratios | Many people have heard of the Golden ratio, phi (φ). Phi is just one of a series
of related ratios that are referred to as the "Metallic ratios".
The Golden ratio was discovered and named by ancient civilizations as it was
thought to be the most pure and beautiful (like Gold). The Silver ratio was was
also known to the early Greeks, though was not named so until later as a nod to
the Golden ratio to which it is closely related. The series has been extended to
encompass all of the related ratios and was given the general name Metallic ratios (or Metallic means).
Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold".
Metallic ratios are the real roots of the general form equation:
x2 - bx - 1 = 0
where the integer b determines which specific one it is.
Using the quadratic equation:
( -b ± √(b2 - 4ac) ) / 2a = x
Substitute in (from the top equation) 1 for a, -1 for c, and recognising that -b is negated we get:
( b ± √(b2 + 4) ) ) / 2 = x
We only want the real root:
( b + √(b2 + 4) ) ) / 2 = x
When we set b to 1, we get an irrational number: the Golden ratio.
( 1 + √(12 + 4) ) / 2 = (1 + √5) / 2 = ~1.618033989...
With b set to 2, we get a different irrational number: the Silver ratio.
( 2 + √(22 + 4) ) / 2 = (2 + √8) / 2 = ~2.414213562...
When the ratio b is 3, it is commonly referred to as the Bronze ratio, 4 and 5
are sometimes called the Copper and Nickel ratios, though they aren't as
standard. After that there isn't really any attempt at standardized names. They
are given names here on this page, but consider the names fanciful rather than
canonical.
Note that technically, b can be 0 for a "smaller" ratio than the Golden ratio.
We will refer to it here as the Platinum ratio, though it is kind-of a
degenerate case.
Metallic ratios where b > 0 are also defined by the irrational continued fractions:
[b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...]
So, The first ten Metallic ratios are:
Metallic ratios
Name
b
Equation
Value
Continued fraction
OEIS link
Platinum
0
(0 + √4) / 2
1
-
-
Golden
1
(1 + √5) / 2
1.618033988749895...
[1;1,1,1,1,1,1,1,1,1,1...]
OEIS:A001622
Silver
2
(2 + √8) / 2
2.414213562373095...
[2;2,2,2,2,2,2,2,2,2,2...]
OEIS:A014176
Bronze
3
(3 + √13) / 2
3.302775637731995...
[3;3,3,3,3,3,3,3,3,3,3...]
OEIS:A098316
Copper
4
(4 + √20) / 2
4.23606797749979...
[4;4,4,4,4,4,4,4,4,4,4...]
OEIS:A098317
Nickel
5
(5 + √29) / 2
5.192582403567252...
[5;5,5,5,5,5,5,5,5,5,5...]
OEIS:A098318
Aluminum
6
(6 + √40) / 2
6.16227766016838...
[6;6,6,6,6,6,6,6,6,6,6...]
OEIS:A176398
Iron
7
(7 + √53) / 2
7.140054944640259...
[7;7,7,7,7,7,7,7,7,7,7...]
OEIS:A176439
Tin
8
(8 + √68) / 2
8.123105625617661...
[8;8,8,8,8,8,8,8,8,8,8...]
OEIS:A176458
Lead
9
(9 + √85) / 2
9.109772228646444...
[9;9,9,9,9,9,9,9,9,9,9...]
OEIS:A176522
There are other ways to find the Metallic ratios; one, (the focus of this task)
is through successive approximations of Lucas sequences.
A traditional Lucas sequence is of the form:
xn = P * xn-1 - Q * xn-2
and starts with the first 2 values 0, 1.
For our purposes in this task, to find the metallic ratios we'll use the form:
xn = b * xn-1 + xn-2
( P is set to b and Q is set to -1. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms 1, 1. The initial starting value has very little effect on the final ratio or convergence rate. Perhaps it would be more accurate to call it a Lucas-like sequence.
At any rate, when b = 1 we get:
xn = xn-1 + xn-2
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
more commonly known as the Fibonacci sequence.
When b = 2:
xn = 2 * xn-1 + xn-2
1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...
And so on.
To find the ratio by successive approximations, divide the (n+1)th term by the
nth. As n grows larger, the ratio will approach the b metallic ratio.
For b = 1 (Fibonacci sequence):
1/1 = 1
2/1 = 2
3/2 = 1.5
5/3 = 1.666667
8/5 = 1.6
13/8 = 1.625
21/13 = 1.615385
34/21 = 1.619048
55/34 = 1.617647
89/55 = 1.618182
etc.
It converges, but pretty slowly. In fact, the Golden ratio has the slowest
possible convergence for any irrational number.
Task
For each of the first 10 Metallic ratios; b = 0 through 9:
Generate the corresponding "Lucas" sequence.
Show here, on this page, at least the first 15 elements of the "Lucas" sequence.
Using successive approximations, calculate the value of the ratio accurate to 32 decimal places.
Show the value of the approximation at the required accuracy.
Show the value of n when the approximation reaches the required accuracy (How many iterations did it take?).
Optional, stretch goal - Show the value and number of iterations n, to approximate the Golden ratio to 256 decimal places.
You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.
See also
Wikipedia: Metallic mean
Wikipedia: Lucas sequence | #C.23 | C# | using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static BI IntSqRoot(BI v, BI res) { // res is the initial guess
BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1;
dl = d; d = term - res; } return term; }
static string doOne(int b, int digs) { // calculates result via square root, not iterations
int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)),
bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g);
bs += b * BI.Parse('1' + new string('0', digs));
bs >>= 1; bs += 4; string st = bs.ToString();
return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); }
static string divIt(BI a, BI b, int digs) { // performs division
int al = a.ToString().Length, bl = b.ToString().Length;
a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs);
string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); }
// custom formating
static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
string res = ""; for (int i = 0; i < x.Length; i++) res +=
string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; }
static void Main(string[] args) { // calculates and checks each "metal"
WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc");
int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) {
BI[] lst = new BI[15]; lst[0] = lst[1] = 1;
for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2];
// since all the iterations (except Pt) are > 15, continue iterating from the end of the list of 15
n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j;
on = n; n = b * n + nm1; nm1 = on; }
WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb"
.Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); }
// now calculate and check big one
n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) {
lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j;
on = n; n += nm1; nm1 = on; }
WriteLine("\nAu to 256 digits:"); WriteLine(t);
WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); }
} |
http://rosettacode.org/wiki/Minesweeper_game | Minesweeper game | There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.
Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.
The total number of mines to be found is shown at the beginning of the game.
Each mine occupies a single grid point, and its position is initially unknown to the player
The grid is shown as a rectangle of characters between moves.
You are initially shown all grids as obscured, by a single dot '.'
You may mark what you think is the position of a mine which will show as a '?'
You can mark what you think is free space by entering its coordinates.
If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.
Points marked as a mine show as a '?'.
Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.
Of course you lose if you try to clear space that has a hidden mine.
You win when you have correctly identified all mines.
The Task is to create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.
Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.
C.F: wp:Minesweeper (computer game)
| #Ceylon | Ceylon | import ceylon.random {
DefaultRandom
}
class Cell() {
shared variable Boolean covered = true;
shared variable Boolean flagged = false;
shared variable Boolean mined = false;
shared variable Integer adjacentMines = 0;
string =>
if (covered && !flagged)
then "."
else if (covered && flagged)
then "?"
else if (!covered && mined)
then "X"
else if (!covered && adjacentMines > 0)
then adjacentMines.string
else " ";
}
"The main function of the module. Run this one."
shared void run() {
value random = DefaultRandom();
value chanceOfBomb = 0.2;
value width = 6;
value height = 4;
value grid = Array { for (j in 1..height) Array { for (i in 1..width) Cell() } };
function getCell(Integer x, Integer y) => grid[y]?.get(x);
void initializeGrid() {
for (row in grid) {
for (cell in row) {
cell.covered = true;
cell.flagged = false;
cell.mined = random.nextFloat() < chanceOfBomb;
}
}
function countAdjacentMines(Integer x, Integer y) => count {
for (j in y - 1 .. y + 1)
for (i in x - 1 .. x + 1)
if (exists cell = getCell(i, j))
cell.mined
};
for (j->row in grid.indexed) {
for (i->cell in row.indexed) {
cell.adjacentMines = countAdjacentMines(i, j);
}
}
}
void displayGrid() {
print(" " + "".join(1..width));
print(" " + "-".repeat(width));
for (j->row in grid.indexed) {
print("``j + 1``|``"".join(row)``|``j + 1``");
}
print(" " + "-".repeat(width));
print(" " + "".join(1..width));
}
Boolean won() =>
expand(grid).every((cell) => (cell.flagged && cell.mined) || (!cell.flagged && !cell.mined));
void uncoverNeighbours(Integer x, Integer y) {
for (j in y - 1 .. y + 1) {
for (i in x - 1 .. x + 1) {
if (exists cell = getCell(i, j), cell.covered, !cell.flagged, !cell.mined) {
cell.covered = false;
if (cell.adjacentMines == 0) {
uncoverNeighbours(i, j);
}
}
}
}
}
while (true) {
print("Welcome to minesweeper!
-----------------------");
initializeGrid();
while (true) {
displayGrid();
print("
The number of mines to find is ``count(expand(grid)*.mined)``.
What would you like to do?
[1] reveal a free space (or blow yourself up)
[2] mark (or unmark) a mine");
assert (exists instruction = process.readLine());
print("Please enter the coordinates. eg 2 4");
assert (exists line2 = process.readLine());
value coords = line2.split().map(Integer.parse).narrow<Integer>().sequence();
if (exists x = coords[0], exists y = coords[1], exists cell = getCell(x - 1, y - 1)) {
switch (instruction)
case ("1") {
if (cell.mined) {
print("=================
=== You lose! ===
=================");
expand(grid).each((cell) => cell.covered = false);
displayGrid();
break;
}
else if (cell.covered) {
cell.covered = false;
uncoverNeighbours(x - 1, y - 1);
}
}
case ("2") {
if (cell.covered) {
cell.flagged = !cell.flagged;
}
}
else { print("bad choice"); }
if (won()) {
print("****************
*** You win! ***
****************");
break;
}
}
}
}
} |
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1 | Minimum positive multiple in base 10 using only 0 and 1 | Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "B10".
Task
Write a routine to find the B10 of a given integer.
E.G.
n B10 n × multiplier
1 1 ( 1 × 1 )
2 10 ( 2 × 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the B10 value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find B10 for:
1998, 2079, 2251, 2277
Stretch goal; find B10 for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you do use magic numbers, explain briefly why and what they do for your implementation.
See also
OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
How to find Minimum Positive Multiple in base 10 using only 0 and 1 | #J | J | B10=: {{ NB. https://oeis.org/A004290
next=. {{ {: (u -) 10x^# }}
step=. ([>. [ {~ y|(i.y)+]) next
continue=. 0 = ({~y|]) next
L=.1 0,~^:(y>1) (, step)^:continue^:_ ,:y{.1 1
k=. y|-r=.10x^<:#L
for_j. i.-<:#L do.
if. 0=L{~<k,~j-1 do.
k=. y|k-E=. 10x^j
r=. r+E
end.
end. r assert. 0=y|r
}} |
http://rosettacode.org/wiki/Modular_exponentiation | Modular exponentiation | Find the last 40 decimal digits of
a
b
{\displaystyle a^{b}}
, where
a
=
2988348162058574136915891421498819466320163312926952423791023078876139
{\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}
b
=
2351399303373464486466122544523690094744975233415544072992656881240319
{\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}
A computer is too slow to find the entire value of
a
b
{\displaystyle a^{b}}
.
Instead, the program must use a fast algorithm for modular exponentiation:
a
b
mod
m
{\displaystyle a^{b}\mod m}
.
The algorithm must work for any integers
a
,
b
,
m
{\displaystyle a,b,m}
, where
b
≥
0
{\displaystyle b\geq 0}
and
m
>
0
{\displaystyle m>0}
.
| #Groovy | Groovy | println 2988348162058574136915891421498819466320163312926952423791023078876139.modPow(
2351399303373464486466122544523690094744975233415544072992656881240319,
10000000000000000000000000000000000000000) |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.