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/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 | #Kotlin | Kotlin | import java.math.BigDecimal
import java.math.BigInteger
val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")
fun lucas(b: Long) {
println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
print("First 15 elements: ")
var x0 = 1L
var x1 = 1L
print("$x0, $x1")
for (i in 1..13) {
val x2 = b * x1 + x0
print(", $x2")
x0 = x1
x1 = x2
}
println()
}
fun metallic(b: Long, dp:Int) {
var x0 = BigInteger.ONE
var x1 = BigInteger.ONE
var x2: BigInteger
val bb = BigInteger.valueOf(b)
val ratio = BigDecimal.ONE.setScale(dp)
var iters = 0
var prev = ratio.toString()
while (true) {
iters++
x2 = bb * x1 + x0
val thiz = (x2.toBigDecimal(dp) / x1.toBigDecimal(dp)).toString()
if (prev == thiz) {
var plural = "s"
if (iters == 1) {
plural = ""
}
println("Value after $iters iteration$plural: $thiz\n")
return
}
prev = thiz
x0 = x1
x1 = x2
}
}
fun main() {
for (b in 0L until 10L) {
lucas(b)
metallic(b, 32)
}
println("Golden ration, where b = 1:")
metallic(1, 256)
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #ALGOL_W | ALGOL W | begin
% record structure that will be used to return the middle 3 digits of a number %
% if the middle three digits can't be determined, isOk will be false and message %
% will contain an error message %
% if the middle 3 digts can be determined, middle3 will contain the middle 3 %
% digits and isOk will be true %
record MiddleThreeDigits ( integer middle3; logical isOk; string(80) message );
% finds the middle3 digits of a number or describes why they can't be found %
reference(MiddleThreeDigits) procedure findMiddleThreeDigits ( integer value number ) ;
begin
integer n, digitCount, d;
n := abs( number );
% count the number of digits the number has %
digitCount := if n = 0 then 1 else 0;
d := n;
while d > 0 do begin
digitCount := digitCount + 1;
d := d div 10
end while_d_gt_0 ;
if digitCount < 3 then MiddleThreeDigits( 0, false, "Number must have at least 3 digits" )
else if not odd( digitCount ) then MiddleThreeDigits( 0, false, "Number must have an odd number of digits" )
else begin
% can find the middle three digits %
integer m3;
m3 := n;
for d := 1 until ( digitCount - 3 ) div 2 do m3 := m3 div 10;
MiddleThreeDigits( m3 rem 1000, true, "" )
end
end findMiddleThreeDigits ;
% test the findMiddleThreeDigits procedure %
for n := 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0 do begin
reference(MiddleThreeDigits) m3;
i_w := 10; s_w := 0; % set output formating %
m3 := findMiddleThreeDigits( n );
write( n, ": " );
if not isOk(m3) then writeon( message(m3) )
else begin
% as we return the middle three digits as an integer, we must manually 0 pad %
if middle3(m3) < 100 then writeon( "0" );
if middle3(m3) < 10 then writeon( "0" );
writeon( i_w := 1, middle3(m3) )
end
end for_n
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)
| #Go | Go | package main
import (
"bufio"
"fmt"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type cell struct {
isMine bool
display byte // display character for cell
}
const lMargin = 4
var (
grid [][]cell
mineCount int
minesMarked int
isGameOver bool
)
var scanner = bufio.NewScanner(os.Stdin)
func makeGrid(n, m int) {
if n <= 0 || m <= 0 {
panic("Grid dimensions must be positive.")
}
grid = make([][]cell, n)
for i := 0; i < n; i++ {
grid[i] = make([]cell, m)
for j := 0; j < m; j++ {
grid[i][j].display = '.'
}
}
min := int(math.Round(float64(n*m) * 0.1)) // 10% of tiles
max := int(math.Round(float64(n*m) * 0.2)) // 20% of tiles
mineCount = min + rand.Intn(max-min+1)
rm := mineCount
for rm > 0 {
x, y := rand.Intn(n), rand.Intn(m)
if !grid[x][y].isMine {
rm--
grid[x][y].isMine = true
}
}
minesMarked = 0
isGameOver = false
}
func displayGrid(isEndOfGame bool) {
if !isEndOfGame {
fmt.Println("Grid has", mineCount, "mine(s),", minesMarked, "mine(s) marked.")
}
margin := strings.Repeat(" ", lMargin)
fmt.Print(margin, " ")
for i := 1; i <= len(grid); i++ {
fmt.Print(i)
}
fmt.Println()
fmt.Println(margin, strings.Repeat("-", len(grid)))
for y := 0; y < len(grid[0]); y++ {
fmt.Printf("%*d:", lMargin, y+1)
for x := 0; x < len(grid); x++ {
fmt.Printf("%c", grid[x][y].display)
}
fmt.Println()
}
}
func endGame(msg string) {
isGameOver = true
fmt.Println(msg)
ans := ""
for ans != "y" && ans != "n" {
fmt.Print("Another game (y/n)? : ")
scanner.Scan()
ans = strings.ToLower(scanner.Text())
}
if scanner.Err() != nil || ans == "n" {
return
}
makeGrid(6, 4)
displayGrid(false)
}
func resign() {
found := 0
for y := 0; y < len(grid[0]); y++ {
for x := 0; x < len(grid); x++ {
if grid[x][y].isMine {
if grid[x][y].display == '?' {
grid[x][y].display = 'Y'
found++
} else if grid[x][y].display != 'x' {
grid[x][y].display = 'N'
}
}
}
}
displayGrid(true)
msg := fmt.Sprint("You found ", found, " out of ", mineCount, " mine(s).")
endGame(msg)
}
func usage() {
fmt.Println("h or ? - this help,")
fmt.Println("c x y - clear cell (x,y),")
fmt.Println("m x y - marks (toggles) cell (x,y),")
fmt.Println("n - start a new game,")
fmt.Println("q - quit/resign the game,")
fmt.Println("where x is the (horizontal) column number and y is the (vertical) row number.\n")
}
func markCell(x, y int) {
if grid[x][y].display == '?' {
minesMarked--
grid[x][y].display = '.'
} else if grid[x][y].display == '.' {
minesMarked++
grid[x][y].display = '?'
}
}
func countAdjMines(x, y int) int {
count := 0
for j := y - 1; j <= y+1; j++ {
if j >= 0 && j < len(grid[0]) {
for i := x - 1; i <= x+1; i++ {
if i >= 0 && i < len(grid) {
if grid[i][j].isMine {
count++
}
}
}
}
}
return count
}
func clearCell(x, y int) bool {
if x >= 0 && x < len(grid) && y >= 0 && y < len(grid[0]) {
if grid[x][y].display == '.' {
if !grid[x][y].isMine {
count := countAdjMines(x, y)
if count > 0 {
grid[x][y].display = string(48 + count)[0]
} else {
grid[x][y].display = ' '
clearCell(x+1, y)
clearCell(x+1, y+1)
clearCell(x, y+1)
clearCell(x-1, y+1)
clearCell(x-1, y)
clearCell(x-1, y-1)
clearCell(x, y-1)
clearCell(x+1, y-1)
}
} else {
grid[x][y].display = 'x'
fmt.Println("Kaboom! You lost!")
return false
}
}
}
return true
}
func testForWin() bool {
isCleared := false
if minesMarked == mineCount {
isCleared = true
for x := 0; x < len(grid); x++ {
for y := 0; y < len(grid[0]); y++ {
if grid[x][y].display == '.' {
isCleared = false
}
}
}
}
if isCleared {
fmt.Println("You won!")
}
return isCleared
}
func splitAction(action string) (int, int, bool) {
fields := strings.Fields(action)
if len(fields) != 3 {
return 0, 0, false
}
x, err := strconv.Atoi(fields[1])
if err != nil || x < 1 || x > len(grid) {
return 0, 0, false
}
y, err := strconv.Atoi(fields[2])
if err != nil || y < 1 || y > len(grid[0]) {
return 0, 0, false
}
return x, y, true
}
func main() {
rand.Seed(time.Now().UnixNano())
usage()
makeGrid(6, 4)
displayGrid(false)
for !isGameOver {
fmt.Print("\n>")
scanner.Scan()
action := strings.ToLower(scanner.Text())
if scanner.Err() != nil || len(action) == 0 {
continue
}
switch action[0] {
case 'h', '?':
usage()
case 'n':
makeGrid(6, 4)
displayGrid(false)
case 'c':
x, y, ok := splitAction(action)
if !ok {
continue
}
if clearCell(x-1, y-1) {
displayGrid(false)
if testForWin() {
resign()
}
} else {
resign()
}
case 'm':
x, y, ok := splitAction(action)
if !ok {
continue
}
markCell(x-1, y-1)
displayGrid(false)
if testForWin() {
resign()
}
case 'q':
resign()
}
}
} |
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 | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[B10]
B10[n_Integer] := Module[{i, out},
i = 1;
While[! Divisible[FromDigits[IntegerDigits[i, 2], 10], n],
i++;
];
out = FromDigits[IntegerDigits[i, 2], 10];
Row@{n, " x ", out/n, " = ", out}
]
Table[B10[i], {i, Range[10]}] // Column
Table[B10[i], {i, 95, 105}] // Column
B10[297]
B10[576]
B10[594]
B10[891]
B10[909]
B10[999]
B10[1998]
B10[2079]
B10[2251]
B10[2277]
B10[2439]
B10[2997]
B10[4878] |
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}
.
| #Maxima | Maxima | a: 2988348162058574136915891421498819466320163312926952423791023078876139$
b: 2351399303373464486466122544523690094744975233415544072992656881240319$
power_mod(a, b, 10^40);
/* 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}
.
| #Nim | Nim | import bigints
proc powmod(b, e, m: BigInt): BigInt =
assert e >= 0
var e = e
var b = b
result = initBigInt(1)
while e > 0:
if e mod 2 == 1:
result = (result * b) mod m
e = e div 2
b = (b.pow 2) mod m
var
a = initBigInt("2988348162058574136915891421498819466320163312926952423791023078876139")
b = initBigInt("2351399303373464486466122544523690094744975233415544072992656881240319")
echo powmod(a, b, 10.pow 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.
| #Factor | Factor | USING: accessors calendar circular colors.constants colors.hsv
command-line continuations io kernel math math.parser namespaces
openal.example sequences system timers ui ui.gadgets
ui.pens.solid ;
IN: rosetta-code.metronome
: bpm>duration ( bpm -- duration ) 60 swap / seconds ;
: blink-gadget ( gadget freq -- )
1.0 1.0 1.0 <hsva> <solid> >>interior relayout-1 ;
: blank-gadget ( gadget -- )
COLOR: white <solid> >>interior relayout-1 ;
: play-note ( gadget freq -- )
[ blink-gadget ] [ 0.3 play-sine blank-gadget ] 2bi ;
: metronome-iteration ( gadget circular -- )
[ first play-note ] [ rotate-circular ] bi ;
TUPLE: metronome-gadget < gadget bpm notes timer ;
: <metronome-gadget> ( bpm notes -- gadget )
\ metronome-gadget new swap >>notes swap >>bpm ;
: metronome-quot ( gadget -- quot )
dup notes>> <circular> [ metronome-iteration ] 2curry ;
: metronome-timer ( gadget -- timer )
[ metronome-quot ] [ bpm>> bpm>duration ] bi every ;
M: metronome-gadget graft* ( gadget -- )
[ metronome-timer ] keep timer<< ;
M: metronome-gadget ungraft*
timer>> stop-timer ;
M: metronome-gadget pref-dim* drop { 200 200 } ;
: metronome-defaults ( -- bpm notes ) 60 { 440 220 330 } ;
: metronome-ui ( bpm notes -- ) <metronome-gadget> "Metronome" open-window ;
: metronome-example ( -- ) metronome-defaults metronome-ui ;
: validate-args ( int-args -- )
[ length 2 < ] [ [ 0 <= ] any? ] bi or [ "args error" throw ] when ;
: (metronome-cmdline) ( args -- bpm notes )
[ string>number ] map dup validate-args
unclip swap ;
: metronome-cmdline ( -- bpm notes )
command-line get [ metronome-defaults ] [ (metronome-cmdline) ] if-empty ;
: print-defaults ( -- )
metronome-defaults swap prefix
[ " " write ] [ number>string write ] interleave nl ;
: metronome-usage ( -- )
"Usage: metronome [BPM FREQUENCIES...]" print
"Arguments must be non-zero" print
"Example: metronome " write print-defaults flush ;
: metronome-main ( -- )
[ [ metronome-cmdline metronome-ui ] [ drop metronome-usage 1 exit ] recover ] with-ui ;
MAIN: metronome-main |
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.
| #FreeBASIC | FreeBASIC | REM FreeBASIC no tiene la capacidad de emitir sonido de forma nativa.
REM La función Sound no es mía, incluyo los créditos correspondientes.
' Sound Function v0.3 For DOS/Linux/Win by yetifoot
' Credits:
' http://www.frontiernet.net/~fys/snd.htm
' http://delphi.about.com/cs/adptips2003/a/bltip0303_3.htm
#ifdef __FB_WIN32__
#include Once "windows.bi"
#endif
Sub Sound_DOS_LIN(Byval freq As Uinteger, dur As Uinteger)
Dim t As Double
Dim As Ushort fixed_freq = 1193181 \ freq
Asm
mov dx, &H61 ' turn speaker on
in al, dx
or al, &H03
out dx, al
mov dx, &H43 ' get the timer ready
mov al, &HB6
out dx, al
mov ax, word Ptr [fixed_freq] ' move freq to ax
mov dx, &H42 ' port to out
out dx, al ' out low order
xchg ah, al
out dx, al ' out high order
End Asm
t = Timer
While ((Timer - t) * 1000) < dur ' wait for out specified duration
Sleep(1)
Wend
Asm
mov dx, &H61 ' turn speaker off
in al, dx
and al, &HFC
out dx, al
End Asm
End Sub
Sub Sound(Byval freq As Uinteger, dur As Uinteger)
#ifndef __fb_win32__
' If not windows Then call the asm version.
Sound_DOS_LIN(freq, dur)
#Else
' If Windows
Dim osv As OSVERSIONINFO
osv.dwOSVersionInfoSize = Sizeof(OSVERSIONINFO)
GetVersionEx(@osv)
Select Case osv.dwPlatformId
Case VER_PLATFORM_WIN32_NT
' If NT then use Beep from API
Beep_(freq, dur)
Case Else
' If not on NT then use the same as DOS/Linux
Sound_DOS_LIN(freq, dur)
End Select
#endif
End Sub
'----------
Sub metronome()
Dim As Double bpm = 120.0 ' beats por minuto
Dim As Long retardo = 1000*(60.0 / bpm)
Dim As Integer bpb = 4 ' beats por compás
Dim As Integer counter = 0 ' contador interno
Do
counter += 1
If counter Mod bpb <> 0 Then
Sound(100, 60)
Color 10: Print "tick ";
Else
Sound(119, 60)
Color 11: Print "TICK "
End If
Sleep(retardo)
Loop
End Sub |
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.
| #Go | Go | package main
import (
"log"
"os"
"sync"
"time"
)
// counting semaphore implemented with a buffered channel
type sem chan struct{}
func (s sem) acquire() { s <- struct{}{} }
func (s sem) release() { <-s }
func (s sem) count() int { return cap(s) - len(s) }
// log package serializes output
var fmt = log.New(os.Stdout, "", 0)
// library analogy per WP article
const nRooms = 10
const nStudents = 20
func main() {
rooms := make(sem, nRooms)
// WaitGroup used to wait for all students to have studied
// before terminating program
var studied sync.WaitGroup
studied.Add(nStudents)
// nStudents run concurrently
for i := 0; i < nStudents; i++ {
go student(rooms, &studied)
}
studied.Wait()
}
func student(rooms sem, studied *sync.WaitGroup) {
rooms.acquire()
// report per task descrption. also exercise count operation
fmt.Printf("Room entered. Count is %d. Studying...\n",
rooms.count())
time.Sleep(2 * time.Second) // sleep per task description
rooms.release()
studied.Done() // signal that student is done
} |
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.
| #Swift | Swift | precedencegroup ExponentiationGroup {
higherThan: MultiplicationPrecedence
}
infix operator ** : ExponentiationGroup
protocol Ring {
associatedtype RingType: Numeric
var one: Self { get }
static func +(_ lhs: Self, _ rhs: Self) -> Self
static func *(_ lhs: Self, _ rhs: Self) -> Self
static func **(_ lhs: Self, _ rhs: Int) -> Self
}
extension Ring {
static func **(_ lhs: Self, _ rhs: Int) -> Self {
var ret = lhs.one
for _ in stride(from: rhs, to: 0, by: -1) {
ret = ret * lhs
}
return ret
}
}
struct ModInt: Ring {
typealias RingType = Int
var value: Int
var modulo: Int
var one: ModInt { ModInt(1, modulo: modulo) }
init(_ value: Int, modulo: Int) {
self.value = value
self.modulo = modulo
}
static func +(lhs: ModInt, rhs: ModInt) -> ModInt {
precondition(lhs.modulo == rhs.modulo)
return ModInt((lhs.value + rhs.value) % lhs.modulo, modulo: lhs.modulo)
}
static func *(lhs: ModInt, rhs: ModInt) -> ModInt {
precondition(lhs.modulo == rhs.modulo)
return ModInt((lhs.value * rhs.value) % lhs.modulo, modulo: lhs.modulo)
}
}
func f<T: Ring>(_ x: T) -> T { (x ** 100) + x + x.one }
let x = ModInt(10, modulo: 13)
let y = f(x)
print("x ^ 100 + x + 1 for x = ModInt(10, 13) is \(y)") |
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.
| #Tcl | Tcl | package require Tcl 8.6
package require pt::pgen
###
### A simple expression parser for a subset of Tcl's expression language
###
# Define the grammar of expressions that we want to handle
set grammar {
PEG Calculator (Expression)
Expression <- Term (' '* AddOp ' '* Term)* ;
Term <- Factor (' '* MulOp ' '* Factor)* ;
Fragment <- '(' ' '* Expression ' '* ')' / Number / Var ;
Factor <- Fragment (' '* PowOp ' '* Fragment)* ;
Number <- Sign? Digit+ ;
Var <- '$' ( 'x'/'y'/'z' ) ;
Digit <- '0'/'1'/'2'/'3'/'4'/'5'/'6'/'7'/'8'/'9' ;
Sign <- '-' / '+' ;
MulOp <- '*' / '/' ;
AddOp <- '+' / '-' ;
PowOp <- '**' ;
END;
}
# Instantiate the parser class
catch [pt::pgen peg $grammar snit -class Calculator -name Grammar]
# An engine that compiles an expression into Tcl code
oo::class create CompileAST {
variable sourcecode opns
constructor {semantics} {
set opns $semantics
}
method compile {script} {
# Instantiate the parser
set c [Calculator]
set sourcecode $script
try {
return [my {*}[$c parset $script]]
} finally {
$c destroy
}
}
method Expression-Empty args {}
method Expression-Compound {from to args} {
foreach {o p} [list Expression-Empty {*}$args] {
set o [my {*}$o]; set p [my {*}$p]
set v [expr {$o ne "" ? "$o \[$v\] \[$p\]" : $p}]
}
return $v
}
forward Expression my Expression-Compound
forward Term my Expression-Compound
forward Factor my Expression-Compound
forward Fragment my Expression-Compound
method Expression-Operator {from to args} {
list ${opns} [string range $sourcecode $from $to]
}
forward AddOp my Expression-Operator
forward MulOp my Expression-Operator
forward PowOp my Expression-Operator
method Number {from to args} {
list ${opns} value [string range $sourcecode $from $to]
}
method Var {from to args} {
list ${opns} variable [string range $sourcecode [expr {$from+1}] $to]
}
} |
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.
| #Racket | Racket |
#lang racket
(define (show-line xs)
(for ([x xs]) (display (~a x #:width 4 #:align 'right)))
(newline))
(show-line (cons "" (range 1 13)))
(for ([y (in-range 1 13)])
(show-line (cons y (for/list ([x (in-range 1 13)])
(if (<= y x) (* x y) "")))))
|
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.
| #Perl | Perl | sub trick {
my(@deck) = @_;
my $result .= sprintf "%-28s @deck\n", 'Starting deck:';
my(@discard, @red, @black);
deal(\@deck, \@discard, \@red, \@black);
$result .= sprintf "%-28s @red\n", 'Red pile:';
$result .= sprintf "%-28s @black\n", 'Black pile:';
my $n = int rand(+@red < +@black ? +@red : +@black);
swap(\@red, \@black, $n);
$result .= sprintf "Red pile after %2d swapped: @red\n", $n;
$result .= sprintf "Black pile after %2d swapped: @black\n", $n;
$result .= sprintf "Red in Red, Black in Black: %d = %d\n", (scalar grep {/R/} @red), scalar grep {/B/} @black;
return "$result\n";
}
sub deal {
my($c, $d, $r, $b) = @_;
while (@$c) {
my $top = shift @$c;
if ($top eq 'R') { push @$r, shift @$c }
else { push @$b, shift @$c }
push @$d, $top;
}
}
sub swap {
my($r, $b, $n) = @_;
push @$r, splice @$b, 0, $n;
push @$b, splice @$r, 0, $n;
}
@deck = split '', 'RB' x 26; # alternating red and black
print trick(@deck);
@deck = split '', 'RRBB' x 13; # alternating pairs of reds and blacks
print trick(@deck);
@deck = sort @deck; # all blacks precede reds
print trick(@deck);
@deck = sort { -1 + 2*int(rand 2) } @deck; # poor man's shuffle
print trick(@deck); |
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 | #J | J |
NB. http://rosettacode.org/wiki/Mian-Chowla_sequence
NB. Dreadfully inefficient implementation recomputes all the sums to n-1
NB. and computes the full addition table rather than just a triangular region
NB. However, this implementation is sufficiently quick to meet the requirements.
NB. The vector head is the next speculative value
NB. Beheaded, the vector is Mian-Chowla sequence.
Until =: conjunction def 'u^:(0 = v)^:_'
unique =: -:&# ~. NB. tally of list matches that of set
next_mc =: [: (, {.) (>:@:{. , }.)Until(unique@:((<:/~@i.@# #&, +/~)@:(}. , {.)))
prime_q =: 1&p: NB. for fun look at prime generation suitability
|
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 | #Java | Java |
import java.util.Arrays;
public class MianChowlaSequence {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println("First 30 terms of the Mian–Chowla sequence.");
mianChowla(1, 30);
System.out.println("Terms 91 through 100 of the Mian–Chowla sequence.");
mianChowla(91, 100);
long end = System.currentTimeMillis();
System.out.printf("Elapsed = %d ms%n", (end-start));
}
private static void mianChowla(int minIndex, int maxIndex) {
int [] sums = new int[1];
int [] chowla = new int[maxIndex+1];
sums[0] = 2;
chowla[0] = 0;
chowla[1] = 1;
if ( minIndex == 1 ) {
System.out.printf("%d ", 1);
}
int chowlaLength = 1;
for ( int n = 2 ; n <= maxIndex ; n++ ) {
// Sequence is strictly increasing.
int test = chowla[n - 1];
// Bookkeeping. Generate only new sums.
int[] sumsNew = Arrays.copyOf(sums, sums.length + n);
int sumNewLength = sums.length;
int savedsSumNewLength = sumNewLength;
// Generate test candidates for the next value of the sequence.
boolean found = false;
while ( ! found ) {
test++;
found = true;
sumNewLength = savedsSumNewLength;
// Generate test sums
for ( int j = 0 ; j <= chowlaLength ; j++ ) {
int testSum = (j == 0 ? test : chowla[j]) + test;
boolean duplicate = false;
// Check if test Sum in array
for ( int k = 0 ; k < sumNewLength ; k++ ) {
if ( sumsNew[k] == testSum ) {
duplicate = true;
break;
}
}
if ( ! duplicate ) {
// Add to array
sumsNew[sumNewLength] = testSum;
sumNewLength++;
}
else {
// Duplicate found. Therefore, test candidate of the next value of the sequence is not OK.
found = false;
break;
}
}
}
// Bingo! Now update bookkeeping.
chowla[n] = test;
chowlaLength++;
sums = sumsNew;
if ( n >= minIndex ) {
System.out.printf("%d %s", chowla[n], (n==maxIndex ? "\n" : ""));
}
}
}
}
|
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.
| #J | J | macro dowhile(condition, block)
quote
while true
$(esc(block))
if !$(esc(condition))
break
end
end
end
end
macro dountil(condition, block)
quote
while true
$(esc(block))
if $(esc(condition))
break
end
end
end
end
using Primes
arr = [7, 31]
@dowhile (!isprime(arr[1]) && !isprime(arr[2])) begin
println(arr)
arr .+= 1
end
println("Done.")
@dountil (isprime(arr[1]) || isprime(arr[2])) begin
println(arr)
arr .+= 1
end
println("Done.")
|
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.
| #Julia | Julia | macro dowhile(condition, block)
quote
while true
$(esc(block))
if !$(esc(condition))
break
end
end
end
end
macro dountil(condition, block)
quote
while true
$(esc(block))
if $(esc(condition))
break
end
end
end
end
using Primes
arr = [7, 31]
@dowhile (!isprime(arr[1]) && !isprime(arr[2])) begin
println(arr)
arr .+= 1
end
println("Done.")
@dountil (isprime(arr[1]) || isprime(arr[2])) begin
println(arr)
arr .+= 1
end
println("Done.")
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #AutoHotkey | AutoHotkey | MsgBox % MillerRabin(999983,10) ; 1
MsgBox % MillerRabin(999809,10) ; 1
MsgBox % MillerRabin(999727,10) ; 1
MsgBox % MillerRabin(52633,10) ; 0
MsgBox % MillerRabin(60787,10) ; 0
MsgBox % MillerRabin(999999,10) ; 0
MsgBox % MillerRabin(999995,10) ; 0
MsgBox % MillerRabin(999991,10) ; 0
MillerRabin(n,k) { ; 0: composite, 1: probable prime (n < 2**31)
d := n-1, s := 0
While !(d&1)
d>>=1, s++
Loop %k% {
Random a, 2, n-2 ; if n < 4,759,123,141, it is enough to test a = 2, 7, and 61.
x := PowMod(a,d,n)
If (x=1 || x=n-1)
Continue
Cont := 0
Loop % s-1 {
x := PowMod(x,2,n)
If (x = 1)
Return 0
If (x = n-1) {
Cont = 1
Break
}
}
IfEqual Cont,1, Continue
Return 0
}
Return 1
}
PowMod(x,n,m) { ; x**n mod m
y := 1, i := n, z := x
While i>0
y := i&1 ? mod(y*z,m) : y, z := mod(z*z,m), i >>= 1
Return y
} |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #11l | 11l | V patients_csv =
‘PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz’
V visits_csv =
‘PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3’
F csv2list(s)
[[String]] rows
L(row) s.split("\n")
rows [+]= row.split(‘,’)
R rows
V patients = csv2list(patients_csv)
V visits = csv2list(visits_csv)
V result = copy(patients)
result.sort_range(1..)
result[0].append(‘LAST_VISIT’)
V last = Dict(visits[1..], p_vis -> (p_vis[0], p_vis[1]))
L(record) 1 .< result.len
result[record].append(last.get(result[record][0], ‘’))
result[0] [+]= [‘SCORE_SUM’, ‘SCORE_AVG’]
V n = Dict(patients[1..], p -> (p[0], 0))
V tot = Dict(patients[1..], p -> (p[0], 0.0))
L(record) visits[1..]
V p = record[0]
V score = record[2]
I !score.empty
n[p]++
tot[p] += Float(score)
L(record) 1 .< result.len
V p = result[record][0]
I n[p] != 0
result[record] [+]= [‘#3.1’.format(tot[p]), ‘#2.2’.format(tot[p] / n[p])]
E
result[record] [+]= [‘’, ‘’]
L(record) result
print(‘| ’record.map(r -> r.center(10)).join(‘ | ’)‘ |’) |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| #6502_Assembly | 6502 Assembly | soft_rs232_lo equ $20 ;%87654321
soft_rs232_hi equ $21 ;%-------9 |
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 | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[FindMetallicRatio]
FindMetallicRatio[b_, digits_] :=
Module[{n, m, data, acc, old, done = False},
{n, m} = {1, 1};
old = -100;
data = {};
While[done == False,
{n, m} = {m, b m + n};
AppendTo[data, {m, m/n}];
If[Length[data] > 15,
If[-N[Log10[Abs[data[[-1, 2]] - data[[-2, 2]]]]] > digits,
done = True
]
]
];
acc = -N[Log10[Abs[data[[-1, 2]] - data[[-2, 2]]]]];
<|"sequence" -> Join[{1, 1}, data[[All, 1]]],
"ratio" -> data[[All, 2]], "acc" -> acc,
"steps" -> Length[data]|>
]
Do[
out = FindMetallicRatio[b, 32];
Print["b=", b];
Print["b=", b, " first 15=", Take[out["sequence"], 15]];
Print["b=", b, " ratio=", N[Last[out["ratio"]], {\[Infinity], 33}]];
Print["b=", b, " Number of steps=", out["steps"]];
,
{b, 0, 9}
]
out = FindMetallicRatio[1, 256];
out["steps"]
N[out["ratio"][[-1]], 256] |
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 | #Nim | Nim | import strformat
import bignum
type Metal {.pure.} = enum platinum, golden, silver, bronze, copper, nickel, aluminium, iron, tin, lead
iterator sequence(b: int): Int =
## Yield the successive terms if a “Lucas” sequence.
## The first two terms are ignored.
var x, y = newInt(1)
while true:
x += b * y
swap x, y
yield y
template plural(n: int): string =
if n >= 2: "s" else: ""
proc computeRatio(b: Natural; digits: Positive) =
## Compute the ratio for the given "n" with the required number of digits.
let M = 10^culong(digits)
var niter = 0 # Number of iterations.
var prevN = newInt(1) # Previous value of "n".
var ratio = M # Current value of ratio.
for n in sequence(b):
inc niter
let nextRatio = n * M div prevN
if nextRatio == ratio: break
prevN = n.clone
ratio = nextRatio
var str = $ratio
str.insert(".", 1)
echo &"Value to {digits} decimal places after {niter} iteration{plural(niter)}: ", str
when isMainModule:
for b in 0..9:
echo &"“Lucas” sequence for {Metal(b)} ratio where b = {b}:"
stdout.write "First 15 elements: 1 1"
var count = 2
for n in sequence(b):
stdout.write ' ', n
inc count
if count == 15: break
echo ""
computeRatio(b, 32)
echo ""
echo "Golden ratio where b = 1:"
computeRatio(1, 256) |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #Action.21 | Action! | INCLUDE "H6:LOADPPM5.ACT"
INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit
DEFINE HISTSIZE="256"
PROC PutBigPixel(INT x,y BYTE col)
IF x>=0 AND x<=79 AND y>=0 AND y<=47 THEN
y==LSH 2
col==RSH 4
IF col<0 THEN col=0
ELSEIF col>15 THEN col=15 FI
Color=col
Plot(x,y)
DrawTo(x,y+3)
FI
RETURN
PROC DrawImage(GrayImage POINTER image INT x,y)
INT i,j
BYTE c
FOR j=0 TO image.gh-1
DO
FOR i=0 TO image.gw-1
DO
c=GetGrayPixel(image,i,j)
PutBigPixel(x+i,y+j,c)
OD
OD
RETURN
INT FUNC Clamp(INT x,min,max)
IF x<min THEN
RETURN (min)
ELSEIF x>max THEN
RETURN (max)
FI
RETURN (x)
BYTE FUNC Median(BYTE ARRAY a BYTE len)
SortB(a,len,0)
len==RSH 1
RETURN (a(len))
PROC Median3x3(GrayImage POINTER src,dst)
INT x,y,i,j,ii,jj,index,sum
BYTE ARRAY arr(9)
BYTE c
FOR j=0 TO src.gh-1
DO
FOR i=0 TO src.gw-1
DO
sum=0 index=0
FOR jj=-1 TO 1
DO
y=Clamp(j+jj,0,src.gh-1)
FOR ii=-1 TO 1
DO
x=Clamp(i+ii,0,src.gw-1)
c=GetGrayPixel(src,x,y)
arr(index)=c
index==+1
OD
OD
c=Median(arr,9)
SetGrayPixel(dst,i,j,c)
OD
OD
RETURN
PROC Main()
BYTE CH=$02FC ;Internal hardware value for last key pressed
BYTE ARRAY dataIn(900),dataOut(900)
GrayImage in,out
INT size=[30],x,y
Put(125) PutE() ;clear the screen
InitGrayImage(in,size,size,dataIn)
InitGrayImage(out,size,size,dataOut)
PrintE("Loading source image...")
LoadPPM5(in,"H6:LENA30G.PPM")
PrintE("Median filter...")
Median3x3(in,out)
Graphics(9)
x=(40-size)/2
y=(48-size)/2
DrawImage(in,x,y)
DrawImage(out,x+40,y)
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #AppleScript | AppleScript | on middle3Digits(n)
try
n as number -- Errors if n isn't a number or coercible thereto.
set s to n as text -- Keep for the ouput string.
if (n mod 1 is not 0) then error (s & " isn't an integer value.")
if (n < 0) then set n to -n
if (n < 100) then error (s & " has fewer than three digits.")
-- Coercing large numbers to text may result in E notation, so extract the digit values individually.
set theDigits to {}
repeat until (n = 0)
set beginning of theDigits to n mod 10 as integer
set n to n div 10
end repeat
set c to (count theDigits)
if (c mod 2 is 0) then error (s & " has an even number of digits.")
on error errMsg
return "middle3Digits handler got an error: " & errMsg
end try
set i to (c - 3) div 2 + 1
set {x, y, z} to items i thru (i + 2) of theDigits
return "The middle three digits of " & s & " are " & ((x as text) & y & z & ".")
end middle3Digits
-- Test code:
set testNumbers to {123, 12345, 1234567, "987654321", "987654321" as number, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}
set output to {}
repeat with thisNumber in testNumbers
set end of output to middle3Digits(thisNumber)
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output |
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)
| #Icon_and_Unicon | Icon and Unicon | global DEFARGS,MF
record minefield(mask,grid,rows,cols,mines,density,marked)
$define _DEFAULTS [6, 4, .2, .6] # task defaults
#$define _DEFAULTS [6, 7, .05, .1] # defaults for debugging
$define _INDENT 6
$define _MINE "Y"
$define _TRUEMINE "Y"
$define _FALSEMINE "N"
$define _MASK "."
$define _MARK "?"
$define _TOGGLE1 ".?"
$define _TOGGLE2 "?."
procedure main(arglist) #: play the game
static trace
initial trace := -1
DEFARGS := _DEFAULTS
if *arglist = 0 then arglist := DEFARGS
newgame!arglist
while c := trim(read()) do {
c ? { tab(many(' '))
case move(1) of {
# required commands
"c": clear() & showgrid() # c clear 1 sq and show
"m": mark() # m flag/unflag a mine
"p": showgrid() # p show the mine field
"r": endgame("Resigning.") # r resign this game
# optional commands
"n": newgame!arglist # n new game grid
"k": clearunmarked() & showgrid() # k clears adjecent unmarked cells if #flags = count
"x": clearallunmarked() # x clears every unflagged cell at once win/loose fast
"q": stop("Quitting") # q quit
"t": &trace :=: trace # t toggle tracing for debugging
default: usage()
}}
testforwin(g)
}
end
procedure newgame(r,c,l,h) #: start a new game
local i,j,t
MF := minefield()
MF.rows := 0 < integer(\r) | DEFARGS[1]
MF.cols := 0 < integer(\c) | DEFARGS[2]
every !(MF.mask := list(MF.rows)) := list(MF.cols,_MASK) # set mask
every !(MF.grid := list(MF.rows)) := list(MF.cols,0) # default count
l := 1 > (0 < real(\l)) | DEFARGS[3]
h := 1 > (0 < real(\h)) | DEFARGS[4]
if l > h then l :=: h
until MF.density := l <= ( h >= ?0 ) # random density between l:h
MF.mines := integer(MF.rows * MF.cols * MF.density) # mines needed
MF.marked := 0
write("Creating ",r,"x",c," mine field with ",MF.mines," (",MF.density * 100,"%).")
every 1 to MF.mines do until \MF.grid[r := ?MF.rows, c := ?MF.cols] := &null # set mines
every \MF.grid[i := 1 to MF.rows,j:= 1 to MF.cols] +:= (/MF.grid[i-1 to i+1,j-1 to j+1], 1) # set counts
showgrid()
return
end
procedure usage() #: show usage
return write(
"h or ? - this help\n",
"n - start a new game\n",
"c i j - clears x,y and displays the grid\n",
"m i j - marks (toggles) x,y\n",
"p - displays the grid\n",
"k i j - clears adjecent unmarked cells if #marks = count\n",
"x - clears ALL unmarked flags at once\n",
"r - resign the game\n",
"q - quit the game\n",
"where i is the (vertical) row number and j is the (horizontal) column number." )
end
procedure getn(n) #: command parsing
tab(many(' '))
if n := n >= ( 0 < integer(tab(many(&digits)))) then return n
else write("Invalid or out of bounds grid square.")
end
procedure showgrid() #: show grid
local r,c,x
write(right("",_INDENT)," ",repl("----+----|",MF.cols / 10 + 1)[1+:MF.cols])
every r := 1 to *MF.mask do {
writes(right(r,_INDENT)," : ")
every c := 1 to *MF.mask[r] do
writes( \MF.mask[r,c] | map(\MF.grid[r,c],"0"," ") | _MINE)
write()
}
write(MF.marked," marked mines and ",MF.mines - MF.marked," mines left to be marked.")
end
procedure mark() #: mark/toggle squares
local i,j
if \MF.mask[i := getn(MF.rows), j :=getn(MF.cols)] := map(MF.mask[i,j],_TOGGLE1,_TOGGLE2) then {
case MF.mask[i,j] of {
_MASK : MF.marked -:= 1
_MARK : MF.marked +:= 1
}
}
end
procedure clear() #: clear a square
local i,j
if ( i := getn(MF.rows) ) & ( j :=getn(MF.cols) ) then
if /MF.mask[i,j] then
write(i," ",j," was already clear")
else if /MF.grid[i,j] then endgame("KABOOM! You lost.")
else return revealclearing(i,j)
end
procedure revealclearing(i,j) #: reaveal any clearing
if \MF.mask[i,j] := &null then {
if MF.grid[i,j] = 0 then
every revealclearing(i-1 to i+1,j-1 to j+1)
return
}
end
procedure clearunmarked() #: clears adjecent unmarked cells if #flags = count
local i,j,k,m,n
if ( i := getn(MF.rows) ) & ( j :=getn(MF.cols) ) then
if /MF.mask[i,j] & ( k := 0 < MF.grid[i,j] ) then {
every (\MF.mask[i-1 to i+1,j-1 to j+1] == _MARK) & ( k -:= 1)
if k = 0 then {
every (m := i-1 to i+1) & ( n := j-1 to j+1) do
if \MF.mask[m,n] == _MASK then MF.mask[m,n] := &null
revealclearing(i,j)
return
}
else
write("Marked squares must match adjacent mine count.")
}
else write("Must be adjecent to one or more marks to clear surrounding squares.")
end
procedure clearallunmarked() #: fast win or loose
local i,j,k
every (i := 1 to MF.rows) & (j := 1 to MF.cols) do {
if \MF.mask[i,j] == _MASK then {
MF.mask[i,j] := &null
if /MF.grid[i,j] then k := 1
}
}
if \k then endgame("Kaboom - you loose.")
end
procedure testforwin() #: win when rows*cols-#_MARK-#_MASK are clear and no Kaboom
local t,x
t := MF.rows * MF.cols - MF.mines
every x := !!MF.mask do if /x then t -:= 1
if t = 0 then endgame("You won!")
end
procedure endgame(tag) #: end the game
local i,j,m
every !(m := list(MF.rows)) := list(MF.cols) # new mask
every (i := 1 to MF.rows) & (j := 1 to MF.cols) do
if \MF.mask[i,j] == _MARK then
m[i,j] := if /MF.grid[i,j] then _TRUEMINE else _FALSEMINE
MF.mask := m
write(tag) & showgrid()
end |
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 | #Modula-2 | Modula-2 |
DEFINITION MODULE B10AsBin;
(* Returns a number representing the B10 of the passed-in number N.
The result has the same binary digits as B10 has decimal digits,
e.g. N = 7 returns 9 = 1001 binary, representing 1001 decimal.
Returns 0 if the procedure fails.
In TopSpeed Modula-2, CARDINAL is unsigned 16-bit, LONGCARD is unsigned 32-bit.
*)
PROCEDURE CalcB10AsBinary( N : CARDINAL) : LONGCARD;
END B10AsBin.
|
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}
.
| #OCaml | OCaml |
let a = Z.of_string "2988348162058574136915891421498819466320163312926952423791023078876139" in
let b = Z.of_string "2351399303373464486466122544523690094744975233415544072992656881240319" in
let m = Z.pow (Z.of_int 10) 40 in
Z.powm a b m
|> Z.to_string
|> print_endline |
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}
.
| #Oforth | Oforth | : powmod(base, exponent, modulus)
1 exponent dup ifZero: [ return ]
while ( dup 0 > ) [
dup isEven ifFalse: [ swap base * modulus mod swap ]
2 / base sq modulus mod ->base
] drop ; |
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.
| #Go | Go | package main
import (
"fmt"
"time"
)
func main() {
var bpm = 72.0 // Beats Per Minute
var bpb = 4 // Beats Per Bar
d := time.Duration(float64(time.Minute) / bpm)
fmt.Println("Delay:", d)
t := time.NewTicker(d)
i := 1
for _ = range t.C {
i--
if i == 0 {
i = bpb
fmt.Printf("\nTICK ")
} else {
fmt.Printf("tick ")
}
}
} |
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.
| #Groovy | Groovy | class CountingSemaphore {
private int count = 0
private final int max
CountingSemaphore(int max) { this.max = max }
synchronized int acquire() {
while (count >= max) { wait() }
++count
}
synchronized int release() {
if (count) { count--; notifyAll() }
count
}
synchronized int getCount() { count }
} |
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.
| #Haskell | Haskell | import Control.Concurrent
( newQSem,
signalQSem,
waitQSem,
threadDelay,
forkIO,
newEmptyMVar,
putMVar,
takeMVar,
QSem,
MVar )
import Control.Monad ( replicateM_ )
worker :: QSem -> MVar String -> Int -> IO ()
worker q m n = do
waitQSem q
putMVar m $ "Worker " <> show n <> " has acquired the lock."
threadDelay 2000000 -- microseconds!
signalQSem q
putMVar m $ "Worker " <> show n <> " has released the lock."
main :: IO ()
main = do
q <- newQSem 3
m <- newEmptyMVar
let workers = 5
prints = 2 * workers
mapM_ (forkIO . worker q m) [1 .. workers]
replicateM_ prints $ takeMVar m >>= putStrLn |
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.
| #VBA | VBA | Option Base 1
Private Function mi_one(ByVal a As Variant) As Variant
If IsArray(a) Then
a(1) = 1
Else
a = 1
End If
mi_one = a
End Function
Private Function mi_add(ByVal a As Variant, b As Variant) As Variant
If IsArray(a) Then
If IsArray(b) Then
If a(2) <> b(2) Then
mi_add = CVErr(2019)
Else
a(1) = (a(1) + b(1)) Mod a(2)
mi_add = a
End If
Else
mi_add = CVErr(2018)
End If
Else
If IsArray(b) Then
mi_add = CVErr(2018)
Else
a = a + b
mi_add = a
End If
End If
End Function
Private Function mi_mul(ByVal a As Variant, b As Variant) As Variant
If IsArray(a) Then
If IsArray(b) Then
If a(2) <> b(2) Then
mi_mul = CVErr(2019)
Else
a(1) = (a(1) * b(1)) Mod a(2)
mi_mul = a
End If
Else
mi_mul = CVErr(2018)
End If
Else
If IsArray(b) Then
mi_mul = CVErr(2018)
Else
a = a * b
mi_mul = a
End If
End If
End Function
Private Function mi_power(x As Variant, p As Integer) As Variant
res = mi_one(x)
For i = 1 To p
res = mi_mul(res, x)
Next i
mi_power = res
End Function
Private Function mi_print(m As Variant) As Variant
If IsArray(m) Then
s = "modint(" & m(1) & "," & m(2) & ")"
Else
s = CStr(m)
End If
mi_print = s
End Function
Private Function f(x As Variant) As Variant
f = mi_add(mi_power(x, 100), mi_add(x, mi_one(x)))
End Function
Private Sub test(x As Variant)
Debug.Print "x^100 + x + 1 for x == " & mi_print(x) & " is " & mi_print(f(x))
End Sub
Public Sub main()
test 10
test [{10,13}]
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.
| #Raku | Raku | my $max = 12;
my $width = chars $max**2;
my $f = "%{$width}s";
say 'x'.fmt($f), '│ ', (1..$max).fmt($f);
say '─' x $width, '┼', '─' x $max*$width + $max;
for 1..$max -> $i {
say $i.fmt($f), '│ ', (
for 1..$max -> $j {
$i <= $j ?? $i*$j !! '';
}
).fmt($f);
} |
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.
| #Phix | Phix | with javascript_semantics
constant n = 52,
pack = shuffle(repeat('r',n/2)&repeat('b',n/2))
string black = "", red = "", discard = ""
for i=1 to length(pack) by 2 do
integer top = pack[i],
next = pack[i+1]
if top=='b' then
black &= next
else
red &= next
end if
discard &= top
end for
black = shuffle(black); red = shuffle(red) -- (optional)
--printf(1,"Discards : %s\n",{discard})
printf(1,"Reds : %s\nBlacks : %s\n\n",{red,black})
integer lb = length(black), lr = length(red),
ns = rand(min(lb,lr))
printf(1,"Swap %d cards:\n\n", ns)
string b1ns = black[1..ns],
r1ns = red[1..ns]
black[1..ns] = r1ns
red[1..ns] = b1ns
printf(1,"Reds : %s\nBlacks : %s\n\n",{red,black})
integer nb = sum(sq_eq(black,'b')),
nr = sum(sq_eq(red,'r'))
string correct = iff(nr==nb?"correct":"**INCORRECT**")
printf(1,"%d r in red, %d b in black - assertion %s\n",{nr,nb,correct})
|
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 | #JavaScript | JavaScript | (() => {
'use strict';
// main :: IO ()
const main = () => {
const genMianChowla = mianChowlas();
console.log([
'Mian-Chowla terms 1-30:',
take(30)(
genMianChowla
),
'\nMian-Chowla terms 91-100:',
(
drop(60)(genMianChowla),
take(10)(
genMianChowla
)
)
].join('\n') + '\n');
};
// mianChowlas :: Gen [Int]
function* mianChowlas() {
let
mcs = [1],
sumSet = new Set([2]),
x = 1;
while (true) {
yield x;
[sumSet, mcs, x] = nextMC(sumSet, mcs, x);
}
}
// nextMC :: Set Int -> [Int] -> Int -> (Set Int, [Int], Int)
const nextMC = (setSums, mcs, n) => {
// Set of sums -> Series up to n -> Next term in series
const valid = x => {
for (const m of mcs) {
if (setSums.has(x + m)) return false;
}
return true;
};
const x = until(valid)(x => 1 + x)(n);
return [
sumList(mcs)(x)
.reduce(
(a, n) => (a.add(n), a),
setSums
),
mcs.concat(x),
x
];
};
// sumList :: [Int] -> Int -> [Int]
const sumList = xs =>
// Series so far -> additional term -> new sums
n => [2 * n].concat(xs.map(x => n + x));
// ---------------- GENERIC FUNCTIONS ----------------
// drop :: Int -> [a] -> [a]
// drop :: Int -> Generator [a] -> Generator [a]
// drop :: Int -> String -> String
const drop = n =>
xs => Infinity > length(xs) ? (
xs.slice(n)
) : (take(n)(xs), xs);
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
'GeneratorFunction' !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = p =>
f => x => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// MAIN ---
return main();
})(); |
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.
| #Kotlin | Kotlin | // version 1.0.6
infix fun Double.pwr(exp: Double) = Math.pow(this, exp)
fun main(args: Array<String>) {
val d = 2.0 pwr 8.0
println(d)
} |
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.
| #Lingo | Lingo | r = RETURN
str = "on halt"&r&"--do nothing"&r&"end"
new(#script).scripttext = str |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #bc | bc | seed = 1 /* seed of the random number generator */
scale = 0
/* Random number from 0 to 32767. */
define rand() {
/* Cheap formula (from POSIX) for random numbers of low quality. */
seed = (seed * 1103515245 + 12345) % 4294967296
return ((seed / 65536) % 32768)
}
/* Random number in range [from, to]. */
define rangerand(from, to) {
auto b, h, i, m, n, r
m = to - from + 1
h = length(m) / 2 + 1 /* want h iterations of rand() % 100 */
b = 100 ^ h % m /* want n >= b */
while (1) {
n = 0 /* pick n in range [b, 100 ^ h) */
for (i = h; i > 0; i--) {
r = rand()
while (r < 68) { r = rand(); } /* loop if the modulo bias */
n = (n * 100) + (r % 100) /* append 2 digits to n */
}
if (n >= b) { break; } /* break unless the modulo bias */
}
return (from + (n % m))
}
/* n is probably prime? */
define miller_rabin_test(n, k) {
auto d, r, a, x, s
if (n <= 3) { return (1); }
if ((n % 2) == 0) { return (0); }
/* find s and d so that d * 2^s = n - 1 */
d = n - 1
s = 0
while((d % 2) == 0) {
d /= 2
s += 1
}
while (k-- > 0) {
a = rangerand(2, n - 2)
x = (a ^ d) % n
if (x != 1) {
for (r = 0; r < s; r++) {
if (x == (n - 1)) { break; }
x = (x * x) % n
}
if (x != (n - 1)) {
return (0)
}
}
}
return (1)
}
for (i = 1; i < 1000; i++) {
if (miller_rabin_test(i, 10) == 1) {
i
}
}
quit |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #AutoHotkey | AutoHotkey | Merge_and_aggregate(patients, visits){
ID := [], LAST_VISIT := [], SCORE_SUM := [], VISIT := []
for i, line in StrSplit(patients, "`n", "`r"){
if (i=1)
continue
x := StrSplit(line, ",")
ID[x.1] := x.2
}
for i, line in StrSplit(visits, "`n", "`r"){
if (i=1)
continue
x := StrSplit(line, ",")
LAST_VISIT[x.1] := x.2 > LAST_VISIT[x.1] ? x.2 : LAST_VISIT[x.1]
SCORE_SUM[x.1] := (SCORE_SUM[x.1] ? SCORE_SUM[x.1] : 0) + (x.3 ? x.3 : 0)
if x.3
VISIT[x.1] := (VISIT[x.1] ? VISIT[x.1] : 0) + 1
}
output := "PATIENT_ID`tLASTNAME`tLAST_VISIT`tSCORE_SUM`tSCORE_AVG`n"
for id, name in ID
output .= ID "`t" name "`t" LAST_VISIT[id] "`t" SCORE_SUM[id] "`t" SCORE_SUM[id]/VISIT[id] "`n"
return output
} |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| #Ada | Ada | type Bit is mod 2;
type Rs_232_Layout is record
Carrier_Detect : Bit;
Received_Data : Bit;
Transmitted_Data : Bit;
Data_Terminal_ready : Bit;
Signal_Ground : Bit;
Data_Set_Ready : Bit;
Request_To_Send : Bit;
Clear_To_Send : Bit;
Ring_Indicator : Bit;
end record;
for Rs_232_Layout use record
Carrier_Detect at 0 range 0..0;
Received_Data at 0 range 1..1;
Transmitted_Data at 0 range 2..2;
Data_Terminal_Ready at 0 range 3..3;
Signal_Ground at 0 range 4..4;
Data_Set_Ready at 0 range 5..5;
Request_To_Send at 0 range 6..6;
Clear_To_Send at 0 range 7..7;
Ring_Indicator at 0 range 8..8;
end record; |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| #ALGOL_68 | ALGOL 68 | MODE RSTWOTHREETWO = BITS;
INT ofs = bits width - 9;
INT
lwb rs232 = ofs + 1,
carrier detect = ofs + 1,
received data = ofs + 2,
transmitted data = ofs + 3,
data terminal ready = ofs + 4,
signal ground = ofs + 5,
data set ready = ofs + 6,
request to send = ofs + 7,
clear to send = ofs + 8,
ring indicator = ofs + 9,
upb rs232 = ofs + 9;
RSTWOTHREETWO rs232 bits := 2r10000000; # up to bits width, OR #
print(("received data: ",received data ELEM rs232bits, new line));
rs232 bits := bits pack((FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE));
print(("received data: ",received data ELEM rs232bits, new line)) |
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 | #Perl | Perl | use strict;
use warnings;
use feature qw(say state);
use Math::AnyNum qw<:overload as_dec>;
sub gen_lucas {
my $b = shift;
my $i = 0;
return sub {
state @seq = (state $v1 = 1, state $v2 = 1);
($v2, $v1) = ($v1, $v2 + $b*$v1) and push(@seq, $v1) unless defined $seq[$i+1];
return $seq[$i++];
}
}
sub metallic {
my $lucas = shift;
my $places = shift || 32;
my $n = my $last = 0;
my @seq = $lucas->();
while (1) {
push @seq, $lucas->();
my $this = as_dec( $seq[-1]/$seq[-2], $places+1 );
last if $this eq $last;
$last = $this;
$n++;
}
$last, $n
}
my @name = <Platinum Golden Silver Bronze Copper Nickel Aluminum Iron Tin Lead>;
for my $b (0..$#name) {
my $lucas = gen_lucas($b);
printf "\n'Lucas' sequence for $name[$b] ratio, where b = $b:\nFirst 15 elements: " . join ', ', map { $lucas->() } 1..15;
printf "Approximated value %s reached after %d iterations\n", metallic(gen_lucas($b));
}
printf "\nGolden ratio to 256 decimal places %s reached after %d iterations", metallic(gen_lucas(1),256); |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #Ada | Ada | function Median (Picture : Image; Radius : Positive) return Image is
type Extended_Luminance is range 0..10_000_000;
type VRGB is record
Color : Pixel;
Value : Luminance;
end record;
Width : constant Positive := 2*Radius*(Radius+1);
type Window is array (-Width..Width) of VRGB;
Sorted : Window;
Next : Integer;
procedure Put (Color : Pixel) is -- Sort using binary search
pragma Inline (Put);
This : constant Luminance :=
Luminance
( ( 2_126 * Extended_Luminance (Color.R)
+ 7_152 * Extended_Luminance (Color.G)
+ 722 * Extended_Luminance (Color.B)
)
/ 10_000
);
That : Luminance;
Low : Integer := Window'First;
High : Integer := Next - 1;
Middle : Integer := (Low + High) / 2;
begin
while Low <= High loop
That := Sorted (Middle).Value;
if That > This then
High := Middle - 1;
elsif That < This then
Low := Middle + 1;
else
exit;
end if;
Middle := (Low + High) / 2;
end loop;
Sorted (Middle + 1..Next) := Sorted (Middle..Next - 1);
Sorted (Middle) := (Color, This);
Next := Next + 1;
end Put;
Result : Image (Picture'Range (1), Picture'Range (2));
begin
for I in Picture'Range (1) loop
for J in Picture'Range (2) loop
Next := Window'First;
for X in I - Radius .. I + Radius loop
for Y in J - Radius .. J + Radius loop
Put
( Picture
( Integer'Min (Picture'Last (1), Integer'Max (Picture'First (1), X)),
Integer'Min (Picture'Last (2), Integer'Max (Picture'First (2), Y))
) );
end loop;
end loop;
Result (I, J) := Sorted (0).Color;
end loop;
end loop;
return Result;
end Median; |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #Arturo | Arturo | middleThree: function [num][
n: to :string abs num
if 3 > size n -> return "Number must have at least three digits"
if even? size n -> return "Number must have an odd number of digits"
middle: ((size n)/2)- 1
return slice n middle middle+2
]
samples: @[
123, 12345, 1234567, 987654321, 10001, neg 10001, neg 123, neg 100, 100, neg 12345,
1, 2, neg 1, neg 10, 2002, neg 2002, 0
]
loop samples 's [
print [pad to :string s 10 ":" middleThree s]
] |
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)
| #Haskell | Haskell | {-# LANGUAGE TemplateHaskell #-}
module MineSweeper
( Board
, Cell(..)
, CellState(..)
, Pos
-- lenses / prisms
, pos
, coveredLens
, coveredFlaggedLens
, coveredMinedLens
, xCoordLens
, yCoordLens
-- Functions
, emptyBoard
, groupedByRows
, displayCell
, isLoss
, isWin
, exposeMines
, openCell
, flagCell
, mineBoard
, totalRows
, totalCols )
where
import Control.Lens ((%~), (&), (.~), (^.), (^?), Lens', Traversal', _1, _2,
anyOf, filtered, folded, lengthOf, makeLenses, makePrisms,
preview, to, view)
import Data.List (find, groupBy, nub, delete, sortBy)
import Data.Maybe (isJust)
import System.Random (getStdGen, getStdRandom, randomR, randomRs)
type Pos = (Int, Int)
type Board = [Cell]
data CellState = Covered { _mined :: Bool, _flagged :: Bool }
| UnCovered { _mined :: Bool }
deriving (Show, Eq)
data Cell = Cell
{ _pos :: Pos
, _state :: CellState
, _cellId :: Int
, _adjacentMines :: Int }
deriving (Show, Eq)
makePrisms ''CellState
makeLenses ''CellState
makeLenses ''Cell
-- Re-useable lens.
coveredLens :: Traversal' Cell (Bool, Bool) --'
coveredLens = state . _Covered
coveredMinedLens, coveredFlaggedLens, unCoveredLens :: Traversal' Cell Bool --'
coveredMinedLens = coveredLens . _1
coveredFlaggedLens = coveredLens . _2
unCoveredLens = state . _UnCovered
xCoordLens, yCoordLens :: Lens' Cell Int --'
xCoordLens = pos . _1
yCoordLens = pos . _2
-- Adjust row and column size to your preference.
totalRows, totalCols :: Int
totalRows = 4
totalCols = 6
emptyBoard :: Board
emptyBoard = (\(n, p) -> Cell { _pos = p
, _state = Covered False False
, _adjacentMines = 0
, _cellId = n }) <$> zip [1..] positions
where
positions = (,) <$> [1..totalCols] <*> [1..totalRows]
updateCell :: Cell -> Board -> Board
updateCell cell = fmap (\c -> if cell ^. cellId == c ^. cellId then cell else c)
updateBoard :: Board -> [Cell] -> Board
updateBoard = foldr updateCell
okToOpen :: [Cell] -> [Cell]
okToOpen = filter (\c -> c ^? coveredLens == Just (False, False))
openUnMined :: Cell -> Cell
openUnMined = state .~ UnCovered False
openCell :: Pos -> Board -> Board
openCell p b = f $ find (\c -> c ^. pos == p) b
where
f (Just c)
| c ^? coveredFlaggedLens == Just True = b
| c ^? coveredMinedLens == Just True = updateCell
(c & state .~ UnCovered True)
b
| isCovered c = if c ^. adjacentMines == 0 && not (isFirstMove b)
then updateCell (openUnMined c) $ expandEmptyCells b c
else updateCell (openUnMined c) b
| otherwise = b
f Nothing = b
isCovered = isJust . preview coveredLens
expandEmptyCells :: Board -> Cell -> Board
expandEmptyCells board cell
| null openedCells = board
| otherwise = foldr (flip expandEmptyCells) updatedBoard (zeroAdjacent openedCells)
where
findMore _ [] = []
findMore exclude (c : xs)
| c `elem` exclude = findMore exclude xs
| c ^. adjacentMines == 0 = c : adjacent c <>
findMore (c : exclude <> adjacent c) xs
| otherwise = c : findMore (c : exclude) xs
adjacent = okToOpen . flip adjacentCells board
openedCells = openUnMined <$> nub (findMore [cell] (adjacent cell))
zeroAdjacent = filter (view (adjacentMines . to (== 0)))
updatedBoard = updateBoard board openedCells
flagCell :: Pos -> Board -> Board
flagCell p board = case find ((== p) . view pos) board of
Just c -> updateCell (c & state . flagged %~ not) board
Nothing -> board
adjacentCells :: Cell -> Board -> [Cell]
adjacentCells Cell {_pos = c@(x1, y1)} = filter (\c -> c ^. pos `elem` positions)
where
f n = [pred n, n, succ n]
positions = delete c $ [(x, y) | x <- f x1, x > 0, y <- f y1, y > 0]
isLoss, isWin, allUnMinedOpen, allMinesFlagged, isFirstMove :: Board -> Bool
isLoss = anyOf (traverse . unCoveredLens) (== True)
isWin b = allUnMinedOpen b || allMinesFlagged b
allUnMinedOpen = (== 0) . lengthOf (traverse . coveredMinedLens . filtered (== False))
allMinesFlagged b = minedCount b == flaggedMineCount b
where
minedCount = lengthOf (traverse . coveredMinedLens . filtered (== True))
flaggedMineCount = lengthOf (traverse . coveredLens . filtered (== (True, True)))
isFirstMove = (== totalCols * totalRows) . lengthOf (folded . coveredFlaggedLens . filtered (== False))
groupedByRows :: Board -> [Board]
groupedByRows = groupBy (\c1 c2 -> yAxis c1 == yAxis c2)
. sortBy (\c1 c2 -> yAxis c1 `compare` yAxis c2)
where
yAxis = view yCoordLens
displayCell :: Cell -> String
displayCell c
| c ^? unCoveredLens == Just True = "X"
| c ^? coveredFlaggedLens == Just True = "?"
| c ^? (unCoveredLens . to not) == Just True =
if c ^. adjacentMines > 0 then show $ c ^. adjacentMines else "▢"
| otherwise = "."
exposeMines :: Board -> Board
exposeMines = fmap (\c -> c & state . filtered (\s -> s ^? _Covered . _1 == Just True) .~ UnCovered True)
updateMineCount :: Board -> Board
updateMineCount b = go b
where
go [] = []
go (x : xs) = (x & adjacentMines .~ totalAdjacentMines b) : go xs
where
totalAdjacentMines =
foldr (\c acc -> if c ^. (state . mined) then succ acc else acc) 0 . adjacentCells x
-- IO
mineBoard :: Pos -> Board -> IO Board
mineBoard p board = do
totalMines <- randomMinedCount
minedBoard totalMines >>= \mb -> pure $ updateMineCount mb
where
mines n = take n <$> randomCellIds
minedBoard n = (\m ->
fmap (\c -> if c ^. cellId `elem` m then c & state . mined .~ True else c)
board) . filter (\c -> openedCell ^. cellId /= c)
<$> mines n
openedCell = head $ filter (\c -> c ^. pos == p) board
randomCellIds :: IO [Int]
randomCellIds = randomRs (1, totalCols * totalRows) <$> getStdGen
randomMinedCount :: IO Int
randomMinedCount = getStdRandom $ randomR (minMinedCells, maxMinedCells)
where
maxMinedCells = floor $ realToFrac (totalCols * totalRows) * 0.2
minMinedCells = floor $ realToFrac (totalCols * totalRows) * 0.1 |
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 | #Nim | Nim | import sequtils, strformat, strutils, times
import bignum
func b10(n: int64): string =
doAssert n > 0, "Argument must be positive."
if n == 1: return "1"
var pow, val = newSeq[int64](n + 1)
var ten = 1i64
for x in 1i64..val.high:
val[x] = ten
for i in 0..n:
if pow[i] != 0 and pow[i] != x:
let k = (ten + i) mod n
if pow[k] == 0: pow[k] = x
if pow[ten] == 0: pow[ten] = x
ten = 10 * ten mod n
if pow[0] != 0: break
if pow[0] == 0:
raise newException(ValueError, "Can’t do it!")
# Build result string.
var x = n
var count = 0'i64
while x != 0:
let pm = pow[x mod n]
if count > pm:
result.add repeat('0', count - pm)
count = pm - 1
result.add '1'
x = (n + x - val[pm]) mod n
result.add repeat('0', count)
const Data = toSeq(1..10) & toSeq(95..105) &
@[297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878]
let t0 = cpuTime()
for val in Data:
let res = b10(val)
let m = newInt(res)
if m mod val != 0: echo &"Wrong result for {val}."
else: echo &"{val:4} × {m div val:<24} = {res}"
echo &"Time: {cpuTime() - t0:.3f} s" |
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 | #Pascal | Pascal | program B10_num;
//numbers having only digits 0 and 1 in their decimal representation
//see https://oeis.org/A004290
//Limit of n= 2^19
{$IFDEF FPC} //fpc 3.0.4
{$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$codealign proc=16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils,gmp; //Format
const
Limit = 256*256*8;//8+8+3 Bits aka 19 digits
B10_4 = 10*10*10*10;
B10_5 = 10*B10_4;
B10_9 = B10_5*B10_4;
HexB10 : array[0..15] of NativeUint = (0000,0001,0010,0011,0100,0101,0110,0111,
1000,1001,1010,1011,1100,1101,1110,1111);
var
ModToIdx : array[0..Limit] of Int32;
B10ModN : array[0..limit-1] of Uint32;
B10 : array of Uint64;
procedure OutOfRange(n:NativeUint);
Begin
Writeln(n:7,' -- out of range --');
end;
function ConvB10(n: Uint32):Uint64;
//Convert n from binary as if it is Base 10
//limited for Uint64 to 2^20-1= 1048575 ala 19 digits
var
fac_B10 : Uint64;
Begin
fac_B10 := 1;
result := 0;
repeat
result += fac_B10*HexB10[n AND 15];
n := n DIV 16;
fac_B10 *=B10_4;
until n = 0;
end;
procedure InitB10;
var
i : NativeUint;
Begin
setlength(B10,Limit);
For i := 0 to Limit do
b10[i]:= ConvB10(i);
end;
procedure Out_Big(n,h,l:NativeUint);
var
num,rest : MPInteger;
Begin
//For Windows gmp ui is Uint32 :-(
z_init_set_ui(num,Hi(B10[h]));
z_mul_2exp(num,num,32);
z_add_ui(num,num,Lo(B10[h]));
z_mul_ui(num,num,B10_5);z_mul_ui(num,num,B10_5);
z_mul_ui(num,num,B10_5);z_mul_ui(num,num,B10_4);
z_init_set_ui(rest,Hi(B10[l]));
z_mul_2exp(rest,rest,32);
z_add_ui(rest,rest,Lo(B10[l]));
z_add(num,num,rest);
write(Format('%7d %19u%.19u ',[n,B10[h],B10[l]]));
IF z_divisible_ui_p(num,n) then
Begin
z_cdiv_q_ui(num, num,n);
write(z_get_str(10,num));
end;
writeln;
z_clear(rest);
z_clear(num);
end;
procedure Out_Small(i,n: NativeUint);
var
value,Mul : Uint64;
Begin
value := B10[i];
mul := value div n;
IF mul = 1 then
mul := n;
writeln(n:7,value:39,' ',mul);
end;
procedure CheckBig_B10(n:NativeUint);
var
h,BigMod,h_mod:NativeUint;
l : NativeInt;
Begin
BigMod :=(sqr(B10_9)*10) MOD n;
For h := Low(B10ModN)+1 to High(B10ModN) do
Begin
//h_mod+l_mod == n => n- h_mod = l_mod
h_mod := n-(BigMod*B10ModN[h])MOD n;
l := ModToIdx[h_mod];
if l>= 0 then
Begin
Out_Big(n,h,l);
EXIT;
end;
end;
OutOfRange(n);
end;
procedure Check_B10(n:NativeUint);
var
pB10 : pUint64;
i,value : NativeUint;
begin
B10ModN[0] := 0;
//set all modulus n => 0..N-1 to -1
fillchar(ModToIdx,n*SizeOf(ModToIdx[0]),#255);
ModToIdx[0] := 0;
pB10 := @B10[0];
i := 1;
repeat
value := Uint64(pB10[i]) MOD n;
If value = 0 then
Break;
B10ModN[i] := value;
//memorize the first occurrence
if ModToIdx[value] < 0 then
ModToIdx[value]:= i;
inc(i);
until i > High(B10ModN);
IF i < High(B10ModN) then
Out_Small(i,n)
else
CheckBig_B10(n);
end;
var
n : Uint32;
Begin
InitB10;
writeln('Number':7,'B10':39,' Multiplier');
For n := 1 to 10 do
Check_B10(n);
For n := 95 to 105 do
Check_B10(n);
Check_B10(297); Check_B10(576); Check_B10(891); Check_B10(909);
Check_B10( 999); Check_B10(1998); Check_B10(2079); Check_B10(2251);
Check_B10(2277); Check_B10(2439); Check_B10(2997); Check_B10(4878);
check_B10(9999);
check_B10(2*9999); //real 0m0,077s :-)
end. |
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}
.
| #ooRexx | ooRexx | /* Modular exponentiation */
numeric digits 100
say powerMod(,
2988348162058574136915891421498819466320163312926952423791023078876139,,
2351399303373464486466122544523690094744975233415544072992656881240319,,
1e40)
exit
powerMod: procedure
use strict arg base, exponent, modulus
exponent=exponent~d2x~x2b~strip('L','0')
result=1
base = base // modulus
do exponentPos=exponent~length to 1 by -1
if (exponent~subChar(exponentPos) == '1')
then result = (result * base) // modulus
base = (base * base) // modulus
end
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}
.
| #PARI.2FGP | PARI/GP | a=2988348162058574136915891421498819466320163312926952423791023078876139;
b=2351399303373464486466122544523690094744975233415544072992656881240319;
lift(Mod(a,10^40)^b) |
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.
| #Haskell | Haskell | import Control.Concurrent
import Control.Concurrent.MVar
import System.Process (runCommand)
-- This program works only on the GHC compiler because of the use of
-- threadDelay
data Beep = Stop | Hi | Low
type Pattern = [Beep]
type BeatsPerMinute = Int
minute = 60000000 -- 1 minute = 60,000,000 microseconds
-- give one of the following example patterns to the metronome function
pattern4_4 = [Hi, Low, Low, Low]
pattern2_4 = [Hi, Low]
pattern3_4 = [Hi, Low, Low]
pattern6_8 = [Hi, Low, Low, Low, Low, Low]
-- use this version if you can't play audio, use Windows or don't
-- have audio files to play
-- beep :: Beep -> IO ()
-- beep Stop = return ()
-- beep Hi = putChar 'H'
-- beep Low = putChar 'L'
-- use this version if you can and want to play audio on Linux using
-- Alsa. Change the name of the files to those of your choice
beep Stop = return ()
beep Hi = putChar 'H' >> runCommand "aplay hi.wav &> /dev/null" >> return ()
beep Low = putChar 'L' >> runCommand "aplay low.wav &> /dev/null" >> return ()
tick :: MVar Pattern -> BeatsPerMinute -> IO ()
tick b i = do
t <- readMVar b
case t of
[Stop] -> return ()
x -> do
mapM_ (\v -> forkIO (beep v) >> threadDelay (minute `div` i)) t
tick b i
metronome :: Pattern -> BeatsPerMinute -> IO ()
metronome p i = do
putStrLn "Press any key to stop the metronome."
b <- newMVar p
_ <- forkIO $ tick b i
_ <- getChar
putMVar b [Stop] |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
n := integer(A[1] | 3) # Max. number of active tasks
m := integer(A[2] | 2) # Number of visits by each task
k := integer(A[3] | 5) # Number of tasks
sem := [: |mutex([])\n :]
every put(threads := [], (i := 1 to k, thread
every 1 to m do {
write("unit ",i," ready")
until flag := trylock(!sem)
write("unit ",i," running")
delay(2000)
write("unit ",i," done")
unlock(flag)
}))
every wait(!threads)
end |
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.
| #J | J | metcon=: {{
sleep=: 6!:3
task=: {{
11 T. lock NB. wait
sleep 2
echo 'Task ',y,&":' has the semaphore'
13 T. lock NB. release
}}
lock=: 10 T. 0
0&T.@'' each i.0>.4-1 T.'' NB. ensure at least four threads
> task t.''"0 i.10 NB. dispatch and wait for 10 tasks
14 T. lock NB. discard lock
}} |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Interface IAddition(Of T)
Function Add(rhs As T) As T
End Interface
Interface IMultiplication(Of T)
Function Multiply(rhs As T) As T
End Interface
Interface IPower(Of T)
Function Power(pow As Integer) As T
End Interface
Interface IOne(Of T)
Function One() As T
End Interface
Class ModInt
Implements IAddition(Of ModInt), IMultiplication(Of ModInt), IPower(Of ModInt), IOne(Of ModInt)
Sub New(value As Integer, modulo As Integer)
Me.Value = value
Me.Modulo = modulo
End Sub
ReadOnly Property Value As Integer
ReadOnly Property Modulo As Integer
Public Function Add(rhs As ModInt) As ModInt Implements IAddition(Of ModInt).Add
Return Me + rhs
End Function
Public Function Multiply(rhs As ModInt) As ModInt Implements IMultiplication(Of ModInt).Multiply
Return Me * rhs
End Function
Public Function Power(pow_ As Integer) As ModInt Implements IPower(Of ModInt).Power
Return Pow(Me, pow_)
End Function
Public Function One() As ModInt Implements IOne(Of ModInt).One
Return New ModInt(1, Modulo)
End Function
Public Overrides Function ToString() As String
Return String.Format("ModInt({0}, {1})", Value, Modulo)
End Function
Public Shared Operator +(lhs As ModInt, rhs As ModInt) As ModInt
If lhs.Modulo <> rhs.Modulo Then
Throw New ArgumentException("Cannot add rings with different modulus")
End If
Return New ModInt((lhs.Value + rhs.Value) Mod lhs.Modulo, lhs.Modulo)
End Operator
Public Shared Operator *(lhs As ModInt, rhs As ModInt) As ModInt
If lhs.Modulo <> rhs.Modulo Then
Throw New ArgumentException("Cannot multiply rings with different modulus")
End If
Return New ModInt((lhs.Value * rhs.Value) Mod lhs.Modulo, lhs.Modulo)
End Operator
Public Shared Function Pow(self As ModInt, p As Integer) As ModInt
If p < 0 Then
Throw New ArgumentException("p must be zero or greater")
End If
Dim pp = p
Dim pwr = self.One()
While pp > 0
pp -= 1
pwr *= self
End While
Return pwr
End Function
End Class
Function F(Of T As {IAddition(Of T), IMultiplication(Of T), IPower(Of T), IOne(Of T)})(x As T) As T
Return x.Power(100).Add(x).Add(x.One)
End Function
Sub Main()
Dim x As New ModInt(10, 13)
Dim y = F(x)
Console.WriteLine("x ^ 100 + x + 1 for x = {0} is {1}", x, y)
End Sub
End Module |
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.
| #REBOL | REBOL | rebol [
Title: "12x12 Multiplication Table"
URL: http://rosettacode.org/wiki/Print_a_Multiplication_Table
]
size: 12
; Because of REBOL's GUI focus, it doesn't really do pictured output,
; so I roll my own. See Formatted_Numeric_Output for more
; comprehensive version:
pad: func [pad n][
n: to-string n
insert/dup n " " (pad - length? n)
n
]
p3: func [v][pad 3 v] ; A shortcut, I hate to type...
--: has [x][repeat x size + 1 [prin "+---"] print "+"] ; Special chars OK.
.row: func [label y /local row x][
row: reduce ["|" label "|"]
repeat x size [append row reduce [either x < y [" "][p3 x * y] "|"]]
print rejoin row
]
-- .row " x " 1 -- repeat y size [.row p3 y y] --
print rejoin [ crlf "What about " size: 5 "?" crlf ]
-- .row " x " 1 -- repeat y size [.row p3 y y] --
print rejoin [ crlf "How about " size: 20 "?" crlf ]
-- .row " x " 1 -- repeat y size [.row p3 y y] -- |
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.
| #Python | Python | import random
## 1. Cards
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
# Give the pack a good shuffle.
random.shuffle(pack)
## 2. Deal from the randomised pack into three stacks
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.append(pack.pop())
discard.append(top)
print('(Discards:', ' '.join(d[0] for d in discard), ')\n')
## 3. Swap the same, random, number of cards between the two stacks.
# We can't swap more than the number of cards in a stack.
max_swaps = min(len(black_stack), len(red_stack))
# Randomly choose the number of cards to swap.
swap_count = random.randint(0, max_swaps)
print('Swapping', swap_count)
# Randomly choose that number of cards out of each stack to swap.
def random_partition(stack, count):
"Partition the stack into 'count' randomly selected members and the rest"
sample = random.sample(stack, count)
rest = stack[::]
for card in sample:
rest.remove(card)
return rest, sample
black_stack, black_swap = random_partition(black_stack, swap_count)
red_stack, red_swap = random_partition(red_stack, swap_count)
# Perform the swap.
black_stack += red_swap
red_stack += black_swap
## 4. Order from randomness?
if black_stack.count(Black) == red_stack.count(Red):
print('Yeha! The mathematicians assertion is correct.')
else:
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 | #jq | jq |
# Input: a bag-of-words (bow)
# Output: either an augmented bow, or nothing if a duplicate is found
def augment_while_unique(stream):
label $out
| foreach ((stream|tostring), null) as $word (.;
if $word == null then .
elif has($word) then break $out
else .[$word] = 1
end;
select($word == null) );
# For speedup, store "sums" as a hash
def mian_chowlas:
{m:[1], sums: {"1":1}}
| recurse(
.m as $m
| .sums as $sums
| first(range(1+$m[-1]; infinite) as $i
| $sums
| augment_while_unique( ($m[] | (.+$i)), (2*$i))
| [$i, .] ) as [$i, $sums]
| {m: ($m + [$i]), $sums} )
| .m[-1] ; |
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 | #Julia | Julia | function mianchowla(n)
seq = ones(Int, n)
sums = Dict{Int,Int}()
tempsums = Dict{Int,Int}()
for i in 2:n
seq[i] = seq[i - 1] + 1
incrementing = true
while incrementing
for j in 1:i
tsum = seq[j] + seq[i]
if haskey(sums, tsum)
seq[i] += 1
empty!(tempsums)
break
else
tempsums[tsum] = 0
if j == i
merge!(sums, tempsums)
empty!(tempsums)
incrementing = false
end
end
end
end
end
seq
end
function testmianchowla()
println("The first 30 terms of the Mian-Chowla sequence are $(mianchowla(30)).")
println("The 91st through 100th terms of the Mian-Chowla sequence are $(mianchowla(100)[91:100]).")
end
testmianchowla()
@time testmianchowla()
|
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.
| #Lua | Lua |
class "foo" : inherits "bar"
{
}
|
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Meta {
FunName$="Alfa"
Code1$=FunName$+"=lambda (X)->{"
Code2$={
=x**2
}
Code3$="}"
Inline code1$+code2$+code3$
Print Function(FunName$, 4)=16
}
Meta
|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #BQN | BQN | _modMul ← { n _𝕣: n|× }
MillerRabin ← { 𝕊n: 10𝕊n ; iter 𝕊 n: !2|n
# n = 1 + d×2⋆s
s ← 0 {𝕨 2⊸|◶⟨+⟜1𝕊2⌊∘÷˜⊢,⊣⟩ 𝕩} n-1
d ← (n-1) ÷ 2⋆s
# Arithmetic mod n
Mul ← n _modMul
Pow ← Mul{𝔽´𝔽˜⍟(/2|⌊∘÷⟜2⍟(↕1+·⌊2⋆⁼⊢)𝕩)𝕨}
# Miller-Rabin test
MR ← {
1 =𝕩 ? 𝕨≠s ;
(n-1)=𝕩 ? 0 ;
𝕨≤1 ? 1 ;
(𝕨-1) 𝕊 Mul˜𝕩
}
C ← { 𝕊a: s MR a Pow d } # Is composite
{0:1; C •rand.Range⌾(-⟜2) n ? 0; 𝕊𝕩-1} iter
} |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #11l | 11l | V items = [‘fee fie’, ‘huff and puff’, ‘mirror mirror’, ‘tick tock’]
L
L(item) items
print(‘#2. #.’.format(L.index + 1, item))
V reply = input(‘Which is from the three pigs: ’).trim(‘ ’)
I !reply.is_digit()
L.continue
I Int(reply) C 1..items.len
print(‘You chose: ’items[Int(reply) - 1])
L.break |
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #AWK | AWK |
# syntax: GAWK -f MERGE_AND_AGGREGATE_DATASETS.AWK RC-PATIENTS.CSV RC-VISITS.CSV
# files may appear in any order
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
{ # printf("%s %s\n",FILENAME,$0) # print input
split($0,arr,",")
if (FNR == 1) {
file = (arr[2] == "LASTNAME") ? "patients" : "visits"
next
}
patient_id_arr[key] = key = arr[1]
if (file == "patients") {
lastname_arr[key] = arr[2]
}
else if (file == "visits") {
if (arr[2] > visit_date_arr[key]) {
visit_date_arr[key] = arr[2]
}
if (arr[3] != "") {
score_arr[key] += arr[3]
score_count_arr[key]++
}
}
}
END {
print("")
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
fmt = "%-10s %-10s %-10s %9s %9s %6s\n"
printf(fmt,"patient_id","lastname","last_visit","score_sum","score_avg","scores")
for (i in patient_id_arr) {
avg = (score_count_arr[i] > 0) ? score_arr[i] / score_count_arr[i] : ""
printf(fmt,patient_id_arr[i],lastname_arr[i],visit_date_arr[i],score_arr[i],avg,score_count_arr[i]+0)
}
exit(0)
}
|
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| #C.2FC.2B.2B | C/C++ | struct RS232_data
{
unsigned carrier_detect : 1;
unsigned received_data : 1;
unsigned transmitted_data : 1;
unsigned data_terminal_ready : 1;
unsigned signal_ground : 1;
unsigned data_set_ready : 1;
unsigned request_to_send : 1;
unsigned clear_to_send : 1;
unsigned ring_indicator : 1;
}; |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| #D | D | module controlFieldsInStruct;
import tango.core.BitArray;
import tango.io.Stdout;
import tango.text.convert.Integer;
class RS232Wrapper(int Length = 9)
{
static assert(Length == 9 || Length == 25, "ERROR, wrong type");
BitArray ba;
static uint[char[]] _map;
public:
static if (Length == 9) {
static this() {
_map = [ cast(char[])
"CD" : 1, "RD" : 2, "TD" : 3, "DTR" : 4, "SG" : 5,
"DSR" : 6, "RTS" : 7, "CTS" : 8, "RI" : 9
];
}
} else {
static this() {
_map = [ cast(char[])
"PG" : 1u, "TD" : 2, "RD" : 3, "RTS" : 4, "CTS" : 5,
"DSR" : 6, "SG" : 7, "CD" : 8, "+" : 9, "-" : 10,
"SCD" : 12, "SCS" : 13, "STD" : 14, "TC" : 15, "SRD" : 16,
"RC" : 17, "SRS" : 19, "DTR" : 20, "SQD" : 21, "RI" : 22,
"DRS" : 23, "XTC" : 24
];
}
}
this() {
ba.length = Length;
}
bool opIndex(uint pos) { return ba[pos]; }
bool opIndexAssign(bool b, uint pos) { return (ba[pos] = b); }
bool opIndex(char[] name) {
assert (name in _map, "don't know that plug: " ~ name);
return opIndex(_map[name]);
}
bool opIndexAssign(bool b, char[] name) {
assert (name in _map, "don't know that plug: " ~ name);
return opIndexAssign(b, _map[name]);
}
void opSliceAssign(bool b) { foreach (ref r; ba) r = b; }
char[] toString() {
char[] ret = "[";
foreach (name, value; _map)
ret ~= name ~ ":" ~ (ba[value]?"1":"0") ~", ";
ret ~= "]";
return ret;
}
}
int main(char[][] args)
{
auto ba = new RS232Wrapper!(25);
// set all bits
ba[] = 1;
ba["RD"] = 0;
ba[5] = 0;
Stdout (ba).newline;
return 0;
} |
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 | #Phix | Phix | with javascript_semantics
include mpfr.e
constant names = {"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
procedure lucas(integer b)
printf(1,"Lucas sequence for %s ratio, where b = %d:\n", {names[b+1], b})
atom x0 = 1, x1 = 1, x2
printf(1,"First 15 elements: %d, %d", {x0, x1})
for i=1 to 13 do
x2 = b*x1 + x0
printf(1,", %d", x2)
x0 = x1
x1 = x2
end for
printf(1,"\n")
end procedure
procedure metallic(integer b, dp)
mpz {x0, x1, x2, bb} = mpz_inits(4,{1,1,0,b})
mpfr ratio = mpfr_init(1,-(dp+2))
integer iterations = 0
string prev = mpfr_get_fixed(ratio,dp)
while true do
iterations += 1
mpz_mul(x2,bb,x1)
mpz_add(x2,x2,x0)
mpfr_set_z(ratio,x2)
mpfr_div_z(ratio,ratio,x1)
string curr = mpfr_get_fixed(ratio,dp)
if prev == curr then
string plural = iff(iterations=1?"":"s")
curr = shorten(curr)
printf(1,"Value to %d dp after %2d iteration%s: %s\n\n", {dp, iterations, plural, curr})
exit
end if
prev = curr
mpz_set(x0,x1)
mpz_set(x1,x2)
end while
end procedure
procedure main()
for b=0 to 9 do
lucas(b)
metallic(b, 32)
end for
printf(1,"Golden ratio, where b = 1:\n")
metallic(1, 256)
end procedure
main()
|
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0)
Width% = 200
Height% = 200
DIM out&(Width%-1, Height%-1)
VDU 23,22,Width%;Height%;8,16,16,128
*DISPLAY Lenagrey
OFF
REM Do the median filtering:
DIM pix&(24)
C% = 25
FOR Y% = 2 TO Height%-3
FOR X% = 2 TO Width%-3
P% = 0
FOR I% = -2 TO 2
FOR J% = -2 TO 2
pix&(P%) = TINT((X%+I%)*2, (Y%+J%)*2) AND &FF
P% += 1
NEXT
NEXT
CALL Sort%, pix&(0)
out&(X%, Y%) = pix&(12)
NEXT
NEXT Y%
REM Display:
GCOL 1
FOR Y% = 0 TO Height%-1
FOR X% = 0 TO Width%-1
COLOUR 1, out&(X%,Y%), out&(X%,Y%), out&(X%,Y%)
LINE X%*2,Y%*2,X%*2,Y%*2
NEXT
NEXT Y%
REPEAT
WAIT 1
UNTIL FALSE |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
typedef struct { unsigned char r, g, b; } rgb_t;
typedef struct {
int w, h;
rgb_t **pix;
} image_t, *image;
typedef struct {
int r[256], g[256], b[256];
int n;
} color_histo_t;
int write_ppm(image im, char *fn)
{
FILE *fp = fopen(fn, "w");
if (!fp) return 0;
fprintf(fp, "P6\n%d %d\n255\n", im->w, im->h);
fwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);
fclose(fp);
return 1;
}
image img_new(int w, int h)
{
int i;
image im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)
+ sizeof(rgb_t) * w * h);
im->w = w; im->h = h;
im->pix = (rgb_t**)(im + 1);
for (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)
im->pix[i] = im->pix[i - 1] + w;
return im;
}
int read_num(FILE *f)
{
int n;
while (!fscanf(f, "%d ", &n)) {
if ((n = fgetc(f)) == '#') {
while ((n = fgetc(f)) != '\n')
if (n == EOF) break;
if (n == '\n') continue;
} else return 0;
}
return n;
}
image read_ppm(char *fn)
{
FILE *fp = fopen(fn, "r");
int w, h, maxval;
image im = 0;
if (!fp) return 0;
if (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))
goto bail;
w = read_num(fp);
h = read_num(fp);
maxval = read_num(fp);
if (!w || !h || !maxval) goto bail;
im = img_new(w, h);
fread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);
bail:
if (fp) fclose(fp);
return im;
}
void del_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]--;
h->g[pix->g]--;
h->b[pix->b]--;
h->n--;
}
}
void add_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]++;
h->g[pix->g]++;
h->b[pix->b]++;
h->n++;
}
}
void init_histo(image im, int row, int size, color_histo_t*h)
{
int j;
memset(h, 0, sizeof(color_histo_t));
for (j = 0; j < size && j < im->w; j++)
add_pixels(im, row, j, size, h);
}
int median(const int *x, int n)
{
int i;
for (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);
return i;
}
void median_color(rgb_t *pix, const color_histo_t *h)
{
pix->r = median(h->r, h->n);
pix->g = median(h->g, h->n);
pix->b = median(h->b, h->n);
}
image median_filter(image in, int size)
{
int row, col;
image out = img_new(in->w, in->h);
color_histo_t h;
for (row = 0; row < in->h; row ++) {
for (col = 0; col < in->w; col++) {
if (!col) init_histo(in, row, size, &h);
else {
del_pixels(in, row, col - size, size, &h);
add_pixels(in, row, col + size, size, &h);
}
median_color(out->pix[row] + col, &h);
}
}
return out;
}
int main(int c, char **v)
{
int size;
image in, out;
if (c <= 3) {
printf("Usage: %s size ppm_in ppm_out\n", v[0]);
return 0;
}
size = atoi(v[1]);
printf("filter size %d\n", size);
if (size < 0) size = 1;
in = read_ppm(v[2]);
out = median_filter(in, size);
write_ppm(out, v[3]);
free(in);
free(out);
return 0;
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
extern
fun
int2digits(x: int): list0(int)
//
(* ****** ****** *)
implement
int2digits(x) =
loop(x, list0_nil) where
{
//
fun
loop
(
x: int, res: list0(int)
) : list0(int) =
if x > 0 then loop(x/10, list0_cons(x%10, res)) else res
//
} (* end of [int2digits] *)
(* ****** ****** *)
extern
fun
Middle_three_digits(x: int): void
(* ****** ****** *)
implement
Middle_three_digits
(x0) = let
//
val x1 =
(
if x0 >= 0 then x0 else ~x0
) : int
//
fun
skip
(
ds: list0(int), k: int
) : list0(int) =
if k > 0 then skip(ds.tail(), k-1) else ds
//
val ds =
int2digits(x1)
//
val n0 = length(ds)
//
in
//
if
(n0 <= 2)
then
(
println! ("Middle-three-digits(", x0, "): Too small!")
)
else
(
if
(n0 % 2 = 0)
then
(
println!
(
"Middle-three-digits(", x0, "): Even number of digits!"
)
)
else let
val ds =
skip(ds, (n0-3)/2)
val-list0_cons(d1, ds) = ds
val-list0_cons(d2, ds) = ds
val-list0_cons(d3, ds) = ds
in
println! ("Middle-three-digits(", x0, "): ", d1, d2, d3)
end // end of [else]
)
//
end // end of [Middle_three_digits]
(* ****** ****** *)
implement
main0() =
{
//
val
thePassing =
g0ofg1
(
$list{int}
(
123
, 12345
, 1234567
, 987654321
, 10001, ~10001
, ~123, ~100, 100, ~12345
)
)
val
theFailing =
g0ofg1($list{int}(1, 2, ~1, ~10, 2002, ~2002, 0))
//
val () = thePassing.foreach()(lam x => Middle_three_digits(x))
val () = theFailing.foreach()(lam x => Middle_three_digits(x))
//
} (* end of [main0] *)
(* ****** ****** *)
|
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)
| #J | J | NB. minefield.ijs script
NB. =========================================================
NB. Game engine
NB.require 'guid'
NB.([ 9!:1) _2 (3!:4) , guids 1 NB. randomly set initial random seed
coclass 'mineswpeng'
newMinefield=: 3 : 0
if. 0=#y do. y=. 9 9 end.
Marked=: Cleared=: y$0
NMines=: <. */(0.01*10+?20),y NB. 10..20% of tiles are mines
mines=. (i. e. NMines ? */) y NB. place mines
Map=: (9*mines) >. y{. (1,:3 3) +/@,;.3 (-1+y){.mines
)
markTiles=: 3 : 0
Marked=: (<"1 <:y) (-.@{)`[`]} Marked NB. toggle marked state of cell(s)
)
clearTiles=: clearcell@:<: NB. decrement coords - J arrays are 0-based
clearcell=: verb define
if. #y do.
free=. (#~ (Cleared < 0 = Map) {~ <"1) y
Cleared=: 1 (<"1 y)} Cleared NB. set cell(s) as cleared
if. #free do.
clearcell (#~ Cleared -.@{~ <"1) ~. (<:$Map) (<."1) 0 >. getNbrs free
end.
end.
)
getNbrs=: [: ,/^:(3=#@$) +"1/&(<: 3 3#: i.9)
eval=: verb define
if. 9 e. Cleared #&, Map do. NB. cleared mine(s)?
1; 'KABOOM!!'
elseif. *./ 9 = (-.Cleared) #&, Map do. NB. all cleared except mines?
1; 'Minefield cleared.'
elseif. do. NB. else...
0; (": +/, Marked>Cleared),' of ',(":NMines),' mines marked.'
end. NB. result: isEnd; message
)
showField=: 4 : 0
idx=. y{ (2 <. Marked + +:Cleared) ,: 2
|: idx} (11&{ , 12&{ ,: Map&{) x NB. transpose result - J arrays are row,column
)
NB. =========================================================
NB. User interface
Minesweeper_z_=: conew&'mineswp'
coclass 'mineswp'
coinsert 'mineswpeng' NB. insert game engine locale in copath
Tiles=: ' 12345678**.?'
create=: verb define
smoutput Instructions
startgame y
)
destroy=: codestroy
quit=: destroy
startgame=: update@newMinefield
clear=: update@clearTiles
mark=: update@markTiles
update=: 3 : 0
'isend msg'=. eval ''
smoutput msg
smoutput < Tiles showField isend
if. isend do.
msg=. ('K'={.msg) {:: 'won';'lost'
smoutput 'You ',msg,'! Try again?'
destroy ''
end.
empty''
)
Instructions=: 0 : 0
=== MineSweeper ===
Object:
Uncover (clear) all the tiles that are not mines.
How to play:
- the left, top tile is: 1 1
- clear an uncleared tile (.) using the command:
clear__fld <column index> <row index>
- mark and uncleared tile (?) as a suspected mine using the command:
mark__fld <column index> <row index>
- if you uncover a number, that is the number of mines adjacent
to the tile
- if you uncover a mine (*) the game ends (you lose)
- if you uncover all tiles that are not mines the game ends (you win).
- quit a game before winning or losing using the command:
quit__fld ''
- start a new game using the command:
fld=: MineSweeper <num columns> <num rows>
) |
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 | #Perl | Perl | use strict;
use warnings;
use Math::AnyNum qw(:overload as_bin digits2num);
for my $x (1..10, 95..105, 297, 576, 594, 891, 909, 999) {
my $y;
if ($x =~ /^9+$/) { $y = digits2num([(1) x (9 * length $x)],2) } # all 9's implies all 1's
else { while (1) { last unless as_bin(++$y) % $x } }
printf "%4d: %28s %s\n", $x, as_bin($y), as_bin($y)/$x;
} |
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}
.
| #Pascal | Pascal | Program ModularExponentiation(output);
uses
gmp;
var
a, b, m, r: mpz_t;
fmt: pchar;
begin
mpz_init_set_str(a, '2988348162058574136915891421498819466320163312926952423791023078876139', 10);
mpz_init_set_str(b, '2351399303373464486466122544523690094744975233415544072992656881240319', 10);
mpz_init(m);
mpz_ui_pow_ui(m, 10, 40);
mpz_init(r);
mpz_powm(r, a, b, m);
fmt := '%Zd' + chr(13) + chr(10);
mp_printf(fmt, @r); (* ...16808958343740453059 *)
mpz_clear(a);
mpz_clear(b);
mpz_clear(m);
mpz_clear(r);
end. |
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}
.
| #Perl | Perl | use bigint;
sub expmod {
my($a, $b, $n) = @_;
my $c = 1;
do {
($c *= $a) %= $n if $b % 2;
($a *= $a) %= $n;
} while ($b = int $b/2);
$c;
}
my $a = 2988348162058574136915891421498819466320163312926952423791023078876139;
my $b = 2351399303373464486466122544523690094744975233415544072992656881240319;
my $m = 10 ** 40;
print expmod($a, $b, $m), "\n";
print $a->bmodpow($b, $m), "\n"; |
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.
| #J | J |
MET=: _ _&$: :(4 : 0)
'BEL BS LF CR'=. 7 8 10 13 { a.
'`print stime delay'=. 1!:2&4`(6!:1)`(6!:3)
ticker=. 2 2$'\ /'
'small large'=. (BEL,2#BS) ; 5#BS
clrln=. CR,(79#' '),CR
x=. 2 ({.,) x
y=. _1 |.&.> 2 ({.,) y
'i j'=. 0
print 'bpb \ bpm \ ' , 2#BS
delay 1
x=. ({. , ('ti t'=. stime'') + {:) x
while. x *./@:> i,t do.
'bpb bpm'=. {.@> y=. 1 |.&.> y
dl=. 60 % bpm
print clrln,(":bpb),' ',(ticker {~ 2 | i=. >: i),' ',(":bpm),' '
for. i. bpb do.
print small ,~ ticker {~ 2 | j=. >: j
delay 0 >. (t=. t + dl) - stime ''
end.
end.
print clrln
i , j , t - ti
)
NB. Basic tacit version; this is probably considered bad coding style. At least I removed the "magic constants". Sort of.
NB. The above version is by far superior.
'BEL BS LF'=: 7 8 10 { a.
'`print delay'=: 1!:2&4`(6!:3)
met=: _&$: :((] ({:@] [ LF print@[ (-.@{.@] [ delay@[ print@] (BEL,2#BS) , (2 2$'\ /') {~ {.@])^:({:@])) 1 , <.@%) 60&% [ print@('\ '"_))
|
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.
| #Java | Java | public class CountingSemaphore{
private int lockCount = 0;
private int maxCount;
CountingSemaphore(int Max){
maxCount = Max;
}
public synchronized void acquire() throws InterruptedException{
while( lockCount >= maxCount){
wait();
}
lockCount++;
}
public synchronized void release(){
if (lockCount > 0)
{
lockCount--;
notifyAll();
}
}
public synchronized int getCount(){
return lockCount;
}
}
public class Worker extends Thread{
private CountingSemaphore lock;
private int id;
Worker(CountingSemaphore coordinator, int num){
lock = coordinator;
id = num;
}
Worker(){
}
public void run(){
try{
lock.acquire();
System.out.println("Worker " + id + " has acquired the lock.");
sleep(2000);
}
catch (InterruptedException e){
}
finally{
lock.release();
}
}
public static void main(String[] args){
CountingSemaphore lock = new CountingSemaphore(3);
Worker crew[];
crew = new Worker[5];
for (int i = 0; i < 5; i++){
crew[i] = new Worker(lock, i);
crew[i].start();
}
}
} |
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.
| #Wren | Wren | // Semi-abstract though we can define a 'pow' method in terms of the other operations.
class Ring {
+(other) {}
*(other) {}
one {}
pow(p) {
if (p.type != Num || !p.isInteger || p < 0) {
Fiber.abort("Argument must be non-negative integer.")
}
var pwr = one
while (p > 0) {
pwr = pwr * this
p = p - 1
}
return pwr
}
}
class ModInt is Ring {
construct new(value, modulo) {
_value = value
_modulo = modulo
}
value { _value }
modulo { _modulo }
+(other) {
if (other.type != ModInt || _modulo != other.modulo) {
Fiber.abort("Argument must be a ModInt with the same modulus.")
}
return ModInt.new((_value + other.value) % _modulo, _modulo)
}
*(other) {
if (other.type != ModInt || _modulo != other.modulo) {
Fiber.abort("Argument must be a ModInt with the same modulus.")
}
return ModInt.new((_value * other.value) % _modulo, _modulo)
}
one { ModInt.new(1, _modulo) }
toString { "Modint(%(_value), %(_modulo))" }
}
var f = Fn.new { |x|
if (!(x is Ring)) Fiber.abort("Argument must be a Ring.")
return x.pow(100) + x + x.one
}
var x = ModInt.new(10, 13)
System.print("x^100 + x + 1 for x = %(x) is %(f.call(x))") |
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.
| #REXX | REXX | /*REXX program displays a NxN multiplication table (in a boxed grid) to the terminal.*/
parse arg sz . /*obtain optional argument from the CL.*/
if sz=='' | sz=="," then sz= 12 /*Not specified? Then use the default.*/
w= max(3, length(sz**2) ); __= copies('─', w) /*calculate the width of the table cell*/
___= __'──' /*literals used in the subroutines. */
do r=1 for sz /*calculate & format a row of the table*/
if r==1 then call top left('│(x)', w+1) /*show title of multiplication table. */
$= '│'center(r"x", w)"│" /*index for a multiplication table row.*/
do c=1 for sz; prod= /*build a row of multiplication table. */
if r<=c then prod= r * c /*only display when the row ≤ column. */
$= $ || right(prod, w+1) '|' /*append product to a cell in the row. */
end /*k*/
say $ /*show a row of multiplication table. */
if r\==sz then call sep /*show a separator except for last row.*/
end /*j*/
call bot /*show the bottom line of the table. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
hdr: $= ?'│'; do i=1 for sz; $=$ || right(i"x|", w+3); end; say $; call sep; return
dap: $= left($, length($) - 1)arg(1); return
top: $= '┌'__"┬"copies(___'┬', sz); call dap "┐"; ?= arg(1); say $; call hdr; return
sep: $= '├'__"┼"copies(___'┼', sz); call dap "┤"; say $; return
bot: $= '└'__"┴"copies(___'┴', sz); call dap "┘"; say $; return |
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.
| #Quackery | Quackery | [ stack ] is discards ( --> s )
[ stack ] is red-card ( --> s )
[ stack ] is black-card ( --> s )
[ dup take rot join swap put ] is to-pile ( n s --> )
[ $ "" discards put
$ "" red-card put
$ "" black-card put
char R 26 of
char B 26 of join shuffle
26 times
[ behead tuck discards to-pile
behead rot char R =
iff red-card else black-card
to-pile ]
drop
discards take witheach
[ emit sp ] cr
red-card take shuffle
black-card take shuffle
over size over size min random
say "Swapping " dup echo
say " cards." cr
dup dip [ split rot ] split
dip join rot join
0 swap witheach
[ char R = + ]
0 rot witheach
[ char B = + ]
say "The assertion is "
= iff [ say "true." ]
else [ say "false." ] cr cr ] is task ( --> )
5 times task |
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.
| #R | R |
magictrick<-function(){
deck=c(rep("B",26),rep("R",26))
deck=sample(deck,52)
blackpile=character(0)
redpile=character(0)
discardpile=character(0)
while(length(deck)>0){
if(deck[1]=="B"){
blackpile=c(blackpile,deck[2])
deck=deck[-2]
}else{
redpile=c(redpile,deck[2])
deck=deck[-2]
}
discardpile=c(discardpile,deck[1])
deck=deck[-1]
}
cat("After the deal the state of the piles is:","\n",
"Black pile:",blackpile,"\n","Red pile:",redpile,"\n",
"Discard pile:",discardpile,"\n","\n")
X=sample(1:min(length(redpile),length(blackpile)),1)
if(X==1){s=" is"}else{s="s are"}
cat(X," card",s," being swapped.","\n","\n",sep="")
redindex=sample(1:length(redpile),X)
blackindex=sample(1:length(blackpile),X)
redbunch=redpile[redindex]
redpile=redpile[-redindex]
blackbunch=blackpile[blackindex]
blackpile=blackpile[-blackindex]
redpile=c(redpile,blackbunch)
blackpile=c(blackpile,redbunch)
cat("After the swap the state of the piles is:","\n",
"Black pile:",blackpile,"\n","Red pile:",redpile,"\n","\n")
cat("There are ", length(which(blackpile=="B")), " black cards in the black pile.","\n",
"There are ", length(which(redpile=="R")), " red cards in the red pile.","\n",sep="")
if(length(which(blackpile=="B"))==length(which(redpile=="R"))){
cat("The assertion is true!")
}
}
|
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 | #Kotlin | Kotlin | // Version 1.3.21
fun mianChowla(n: Int): List<Int> {
val mc = MutableList(n) { 0 }
mc[0] = 1
val hs = HashSet<Int>(n * (n + 1) / 2)
hs.add(2)
val hsx = mutableListOf<Int>()
for (i in 1 until n) {
hsx.clear()
var j = mc[i - 1]
outer@ while (true) {
j++
mc[i] = j
for (k in 0..i) {
val sum = mc[k] + j
if (hs.contains(sum)) {
hsx.clear()
continue@outer
}
hsx.add(sum)
}
hs.addAll(hsx)
break
}
}
return mc
}
fun main() {
val mc = mianChowla(100)
println("The first 30 terms of the Mian-Chowla sequence are:")
println(mc.subList(0, 30))
println("\nTerms 91 to 100 of the Mian-Chowla sequence are:")
println(mc.subList(90, 100))
} |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | CircleTimes[x_, y_] := Mod[x, 10] Mod[y, 10]
14\[CircleTimes]13 |
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.
| #Nemerle | Nemerle | proc `^`*[T: SomeInteger](base, exp: T): T =
var (base, exp) = (base, exp)
result = 1
while exp != 0:
if (exp and 1) != 0:
result *= base
exp = exp shr 1
base *= base
echo 2 ^ 10 # 1024 |
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Bracmat | Bracmat | ( 1:?seed
& ( rand
=
. mod$(!seed*1103515245+12345.4294967296):?seed
& mod$(div$(!seed.65536).32768)
)
& ( rangerand
= from to b h i m n r length
. !arg:(?from,?to)
& !to+-1*!from+1:?m
& @(!m:? [?length)
& div$(!length+1.2)+1:?h
& 100^mod$(!h.!m):?b
& whl
' ( 0:?n
& !h+1:?i
& whl
' ( !i+-1:>0:?i
& rand$:?r
& whl'(!r:<68&rand$:?r)
& !n*100+mod$(!r.100):?n
)
& !n:>!b
)
& !from+mod$(!n.!m)
)
& ( miller-rabin-test
= n k d r a x s return
. !arg:(?n,?k)
& ( !n:~>3&1
| mod$(!n.2):0
| !n+-1:?d
& 0:?s
& whl
' ( mod$(!d.2):0
& !d*1/2:?d
& 1+!s:?s
)
& 1:?return
& whl
' ( !k+-1:?k:~<0
& rangerand$(2,!n+-2):?a
& mod$(!a^!d.!n):?x
& ( !x:1
| 0:?r
& whl
' ( !r+1:~>!s:?r
& !n+-1:~!x
& mod$(!x*!x.!n):?x
)
& ( !n+-1:!x
| 0:?return&~
)
)
)
& !return
)
)
& 0:?i
& :?primes
& whl
' ( 1+!i:<1000:?i
& ( miller-rabin-test$(!i,10):1
& !primes !i:?primes
|
)
)
& !primes:? [-11 ?last
& out$!last
); |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #Action.21 | Action! | DEFINE PTR="CARD"
BYTE FUNC Init(PTR ARRAY items)
items(0)="fee fie"
items(1)="huff and puff"
items(2)="mirror mirror"
items(3)="tick tock"
RETURN (4)
PROC ShowMenu(PTR ARRAY items BYTE count)
BYTE i
FOR i=1 TO count
DO
PrintF("(%B) %S%E",i,items(i-1))
OD
RETURN
BYTE FUNC GetMenuItem(PTR ARRAY items BYTE count)
BYTE res
DO
ShowMenu(items,count) PutE()
Print("Make your choise: ")
res=InputB()
UNTIL res>=1 AND res<=count
OD
RETURN (res-1)
PROC Main()
PTR ARRAY items(10)
BYTE count,res
count=Init(items)
res=GetMenuItem(items,count)
PrintF("You have chosen: %S%E",items(res))
RETURN |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #360_Assembly | 360 Assembly |
* Request to Get Storage Managed by "GETMAIN" Supervisor Call (SVC 4)
LA 1,PLIST Point Reg 1 to GETMAIN/FREEMAIN Parm List
SVC 4 Issue GETMAIN SVC
LTR 15,15 Register 15 = 0?
BZ GOTSTG Yes: Got Storage
* [...] No: Handle GETMAIN Failure
GOTSTG L 2,STG@ Load Reg (any Reg) with Addr of Aquired Stg
* [...] Continue
* Request to Free Storage Managed by "FREEMAIN" Supervisor Call (SVC 5)
LA 1,PLIST Point Reg 1 to GETMAIN/FREEMAIN Parm List
SVC 5 Issue FREEMAIN SVC
LTR 15,15 Register 15 = 0?
BZ STGFRE Yes: Storage Freed
* [...] No: Handle FREEMAIN Failure
STGFRE EQU * Storage Freed
* [...] Continue
*
STG@ DS A Address of Stg Area (Aquired or to be Freed)
PLIST EQU * 10-Byte GETMAIN/FREEMAIN Parameter List
DC A(256) Number of Bytes; Max=16777208 ((2**24)-8)
DC A(STG@) Pointer to Address of Storage Area
DC X'0000' (Unconditional Request; Subpool 0)
|
http://rosettacode.org/wiki/Merge_and_aggregate_datasets | Merge and aggregate datasets | Merge and aggregate datasets
Task
Merge and aggregate two datasets as provided in .csv files into a new resulting dataset.
Use the appropriate methods and data structures depending on the programming language.
Use the most common libraries only when built-in functionality is not sufficient.
Note
Either load the data from the .csv files or create the required data structures hard-coded.
patients.csv file contents:
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz
visits.csv file contents:
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3
Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.
Merge and group per patient id and last name, get the maximum visit date, and get the sum and average of the scores per patient to get the resulting dataset.
Note that the visit date is purposefully provided as ISO format, so that it could also be processed as text and sorted alphabetically to determine the maximum date.
| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |
| 1001 | Hopper | 2020-11-19 | 17.4 | 5.80 |
| 2002 | Gosling | 2020-10-08 | 6.8 | 6.80 |
| 3003 | Kemeny | 2020-11-12 | | |
| 4004 | Wirth | 2020-11-05 | 15.4 | 7.70 |
| 5005 | Kurtz | | | |
Note
This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.
Related tasks
CSV data manipulation
CSV to HTML translation
Read entire file
Read a file line by line
| #C.2B.2B | C++ | #include <iostream>
#include <optional>
#include <ranges>
#include <string>
#include <vector>
using namespace std;
struct Patient
{
string ID;
string LastName;
};
struct Visit
{
string PatientID;
string Date;
optional<float> Score;
};
int main(void)
{
auto patients = vector<Patient> {
{"1001", "Hopper"},
{"4004", "Wirth"},
{"3003", "Kemeny"},
{"2002", "Gosling"},
{"5005", "Kurtz"}};
auto visits = vector<Visit> {
{"2002", "2020-09-10", 6.8},
{"1001", "2020-09-17", 5.5},
{"4004", "2020-09-24", 8.4},
{"2002", "2020-10-08", },
{"1001", "" , 6.6},
{"3003", "2020-11-12", },
{"4004", "2020-11-05", 7.0},
{"1001", "2020-11-19", 5.3}};
// sort the patients by ID
sort(patients.begin(), patients.end(),
[](const auto& a, const auto&b){ return a.ID < b.ID;});
cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n";
for(const auto& patient : patients)
{
// loop over all of the patients and determine the fields
string lastVisit;
float sum = 0;
int numScores = 0;
// use C++20 ranges to filter the visits by patients
auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};
for(const auto& visit : visits | views::filter( patientFilter ))
{
if(visit.Score)
{
sum += *visit.Score;
numScores++;
}
lastVisit = max(lastVisit, visit.Date);
}
// format the output
cout << "| " << patient.ID << " | ";
cout.width(8); cout << patient.LastName << " | ";
cout.width(10); cout << lastVisit << " | ";
if(numScores > 0)
{
cout.width(9); cout << sum << " | ";
cout.width(9); cout << (sum / float(numScores));
}
else cout << " | ";
cout << " |\n";
}
} |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| #Forth | Forth | : masks ( n -- ) 0 do 1 i lshift constant loop ;
9 masks DCD RxD TxD DTR SG DSR RTS CTS RI |
http://rosettacode.org/wiki/Memory_layout_of_a_data_structure | Memory layout of a data structure | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| #Fortran | Fortran | TYPE RS232PIN9
LOGICAL CARRIER_DETECT !1
LOGICAL RECEIVED_DATA !2
LOGICAL TRANSMITTED_DATA !3
LOGICAL DATA_TERMINAL_READY !4
LOGICAL SIGNAL_GROUND !5
LOGICAL DATA_SET_READY !6
LOGICAL REQUEST_TO_SEND !7
LOGICAL CLEAR_TO_SEND !8
LOGICAL RING_INDICATOR !9
END TYPE RS232PIN9 |
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 | #Python | Python | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256) |
http://rosettacode.org/wiki/Median_filter | Median filter | The median filter takes in the neighbourhood the median color (see Median filter)
(to test the function below, you can use these input and output solutions)
| #D | D | import grayscale_image;
Image!Color medianFilter(uint radius=10, Color)(in Image!Color img)
pure nothrow @safe if (radius > 0) in {
assert(img.nx >= radius && img.ny >= radius);
} body {
alias Hist = uint[256];
static ubyte median(uint no)(in ref Hist cumulative)
pure nothrow @safe @nogc {
size_t localSum = 0;
foreach (immutable k, immutable v; cumulative)
if (v) {
localSum += v;
if (localSum > no / 2)
return k;
}
return 0;
}
// Copy image borders in the result image.
auto result = new Image!Color(img.nx, img.ny);
foreach (immutable y; 0 .. img.ny)
foreach (immutable x; 0 .. img.nx)
if (x < radius || x > img.nx - radius - 1 ||
y < radius || y > img.ny - radius - 1)
result[x, y] = img[x, y];
enum edge = 2 * radius + 1;
auto hCol = new Hist[img.nx];
// Create histogram columns.
foreach (immutable y; 0 .. edge - 1)
foreach (immutable x, ref hx; hCol)
hx[img[x, y]]++;
foreach (immutable y; radius .. img.ny - radius) {
// Add to each histogram column lower pixel.
foreach (immutable x, ref hx; hCol)
hx[img[x, y + radius]]++;
// Calculate main Histogram using first edge-1 columns.
Hist H;
foreach (immutable x; 0 .. edge - 1)
foreach (immutable k, immutable v; hCol[x])
if (v)
H[k] += v;
foreach (immutable x; radius .. img.nx - radius) {
// Add right-most column.
foreach (immutable k, immutable v; hCol[x + radius])
if (v)
H[k] += v;
result[x, y] = Color(median!(edge ^^ 2)(H));
// Drop left-most column.
foreach (immutable k, immutable v; hCol[x - radius])
if (v)
H[k] -= v;
}
// Substract the upper pixels.
foreach (immutable x, ref hx; hCol)
hx[img[x, y - radius]]--;
}
return result;
}
version (median_filter_main)
void main() { // Demo.
loadPGM!Gray(null, "lena.pgm").
medianFilter!10
.savePGM("lena_median_r10.pgm");
} |
http://rosettacode.org/wiki/Middle_three_digits | Middle three digits | Task
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #AutoHotkey | AutoHotkey | Numbers:="123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0"
Loop, parse, Numbers, `,
{
if A_LoopField is not number
log := log . A_LoopField . "`t: Not a valid number`n"
else if((d:=StrLen(n:=RegExReplace(A_LoopField,"\D")))<3)
log := log . A_LoopField . "`t: Too short`n"
else if(!Mod(d,2))
log := log . A_LoopField . "`t: Not an odd number of digits`n"
else
log := log . A_LoopField . "`t: " . SubStr(n,((d-3)//2)+1,3) . "`n"
}
MsgBox % log |
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)
| #Java | Java |
--------------------------------- START of Main.java ---------------------------------
//By xykmz. Enjoy!
import java.util.Scanner;
public class Main {
static int intErrorTrap (int x, int y){
int max, min;
if (x < y) {
min = x;
max = y;
} else {
min = y;
max = x;
}
int input;
boolean loopEnd;
do {
System.out.println("Please enter an integer between " + min + " to " + max + ".");
Scanner userInput = new Scanner(System.in); //Player inputs a guess
try
{
input = userInput.nextInt();
if(input > max) //Input is too high
{
loopEnd = false;
System.out.println("Input is invalid.");
return -1;
}
else if(input < min) //Input is too low
{
loopEnd = false;
System.out.println("Input is invalid.");
return -1;
}
else //Input is within acceptable range
{
loopEnd = true;
System.out.println(input + " is a valid input.");
return input;
}
}
catch (Exception e)
{
loopEnd = false;
userInput.next();
System.out.println("Input is invalid.");
return 0;
}
} while (loopEnd == false);
}
public static void main(String[] args) {
System.out.println ("Enter width.");
int x = intErrorTrap (0,60);
System.out.println ("Enter height.");
int y = intErrorTrap (0,30);
System.out.println ("Enter difficulty.");
int d = intErrorTrap (0,100);
new Minesweeper(x, y, d); //Suggested: (60, 30, 15)
}
}
//--------------------------------- END of Main.java ---------------------------------
//--------------------------------- START of Cell.java ---------------------------------
public class Cell{ //This entire class is quite self-explanatory. All we're really doing is setting booleans.
private boolean isMine, isFlagged, isCovered;
private int number;
public Cell(){
isMine = false;
isFlagged = false;
isCovered = true;
number = 0;
}
public void flag(){
isFlagged = true;
}
public void unflag(){
isFlagged = false;
}
public void setMine(){
isMine = true;
}
public boolean isMine(){
return isMine;
}
public void reveal(){
isCovered = false;
}
public void setNumber(int i){ //Set the number of the cell
number = i;
}
public int getNumber(){ //Request the program for the number of the cell
return number;
}
public boolean isFlagged(){
return isFlagged;
}
public boolean isCovered(){
return isCovered;
}
}
//--------------------------------- END of Cell.java ---------------------------------
//--------------------------------- START of Board.java ---------------------------------
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Board extends JPanel{
private static final long serialVersionUID = 1L; //Guarantees consistent serialVersionUID value across different java compiler implementations,
//Auto-generated value might screw things up
private Minesweeper mine;
private Cell[][] cells;
public void paintComponent(Graphics g){
cells = mine.getCells();
for (int i = 0; i < mine.getx(); i++){
for (int j = 0; j < mine.gety(); j++){
Cell current = cells[i][j];
//Flagged cells
if (current.isFlagged()){
if (current.isMine() && mine.isFinished()){
g.setColor(Color.ORANGE); //Let's the player know which mines they got right when the game is finished.
g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
g.setColor(Color.BLACK);
g.drawLine(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
g.drawLine(i * 20, j * 20 + 20, i * 20 + 20, j * 20);
}
else if (mine.isFinished()){ //Shows cells that the player incorrectly identified as mines.
g.setColor(Color.YELLOW);
g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
g.setColor(Color.BLACK);
}
else{
g.setColor(Color.GREEN); //Flagging a mine.
g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
g.setColor(Color.BLACK);
}
}
//Unflagged cells
else if (current.isCovered()){ //Covered cells
g.setColor(Color.DARK_GRAY);
g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
g.setColor(Color.BLACK);
}
else if (current.isMine()){ //Incorrect cells are shown when the game is over.=
g.setColor(Color.RED);
g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
g.setColor(Color.BLACK);
g.drawLine(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
g.drawLine(i * 20, j * 20 + 20, i * 20 + 20, j * 20);
}
else{ //Empty cells or numbered cells
g.setColor(Color.LIGHT_GRAY);
g.fillRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
g.setColor(Color.BLACK);
}
//The following part is very self explanatory - drawing the numbers.
//Not very interesting work.
//Not a fun time.
//Rating: 0/10. Would not recommend.
if (!current.isCovered()){
if (current.getNumber() == 1){
g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3
g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6
}
else if (current.getNumber() == 2){
g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2
g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3
g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4
g.drawLine(i * 20 + 7, j * 20 + 11, i * 20 + 7, j * 20 + 15); //5
g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7
}
else if (current.getNumber() == 3){
g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2
g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3
g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4
g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6
g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7
}
else if (current.getNumber() == 4){
g.drawLine(i * 20 + 7, j * 20 + 5, i * 20 + 7, j * 20 + 9); //1
g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3
g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4
g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6
}
else if (current.getNumber() == 5){
g.drawLine(i * 20 + 7, j * 20 + 5, i * 20 + 7, j * 20 + 9); //1
g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2
g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4
g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6
g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7
}
else if (current.getNumber() == 6){
g.drawLine(i * 20 + 7, j * 20 + 5, i * 20 + 7, j * 20 + 9); //1
g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2
g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4
g.drawLine(i * 20 + 7, j * 20 + 11, i * 20 + 7, j * 20 + 15); //5
g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6
g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7
}
else if (current.getNumber() == 7){
g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2
g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3
g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6
}
else if (current.getNumber() == 8){
g.drawLine(i * 20 + 7, j * 20 + 5, i * 20 + 7, j * 20 + 9); //1
g.drawLine(i * 20 + 8, j * 20 + 4, i * 20 + 12, j * 20 + 4); //2
g.drawLine(i * 20 + 13, j * 20 + 5, i * 20 + 13, j * 20 + 9); //3
g.drawLine(i * 20 + 8, j * 20 + 10, i * 20 + 12, j * 20 + 10); //4
g.drawLine(i * 20 + 7, j * 20 + 11, i * 20 + 7, j * 20 + 15); //5
g.drawLine(i * 20 + 13, j * 20 + 11, i * 20 + 13, j * 20 + 15); //6
g.drawLine(i * 20 + 8, j * 20 + 16, i * 20 + 12, j * 20 + 16); //7
}
}
g.setColor(Color.BLACK);
g.drawRect(i * 20, j * 20, i * 20 + 20, j * 20 + 20);
}
}
}
public Board(Minesweeper m){ //Creating a new game so we can draw a board for it
mine = m;
cells = mine.getCells();
addMouseListener(new Actions(mine));
setPreferredSize(new Dimension(mine.getx() * 20, mine.gety() * 20));
}
}
//--------------------------------- END of Board.java ---------------------------------
//--------------------------------- START of Actions.java ---------------------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Actions implements ActionListener, MouseListener{
private Minesweeper mine;
//These following four are not important. We simply tell the machine to pay no mind when mouse is pressed, released, etc.
//If these weren't here the computer would freak out and panic over what to do because no instructions were given.
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
//Where the fun begins
public Actions(Minesweeper m){
mine = m;
}
//Any time an action is performed, redraw the board and keep it up to date.
public void actionPerformed(ActionEvent e){
mine.reset();
mine.refresh();
}
//Mouse clicky clicky
public void mouseClicked(MouseEvent e){
//Left click - opens mine
if (e.getButton() == 1)
{
int x = e.getX() / 20;
int y = e.getY() / 20;
mine.select(x, y);
}
//Right click - marks mine
if (e.getButton() == 3)
{
int x = e.getX() / 20;
int y = e.getY() / 20;
mine.mark(x, y);
}
mine.refresh(); //Gotta keep it fresh
}
}
//--------------------------------- END of Actions.java ---------------------------------
//--------------------------------- START of Minesweeper.java ---------------------------------
import java.awt.BorderLayout;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Minesweeper extends JFrame
{
private static final long serialVersionUID = 1L;
private int width, height;
private int difficulty;
private Cell[][] cells;
private Board board;
private JButton reset;
private boolean finished;
public void select(int x, int y){ //Select a mine on the board
if (cells[x][y].isFlagged()) //Is the mine flagged?
return;
cells[x][y].reveal(); //Reveal the cell
resetMarks(); //Reset marks and redraw board
refresh();
if (cells[x][y].isMine()) //If a mine is revealed, you lose.
{
lose();
}
else if (won()) //If the game has been won, you win. Hahahahahaha.
{
win();
}
}
private void setNumbers(){ //For each cell, count the amount of mines in surrounding squares.
//Because the board is modeled as a 2D array, this is relatively easy - simply check the surrounding addresses for mines.
//If there's a mine, add to the count.
for (int i = 0; i < width; i++){
for (int j = 0; j < height; j++){
int count = 0;
if (i > 0 && j > 0 && cells[i - 1][j - 1].isMine())
count++;
if (j > 0 && cells[i][j - 1].isMine())
count++;
if (i < width - 1 && j > 0 && cells[i + 1][j - 1].isMine())
count++;
if (i > 0 && cells[i - 1][j].isMine())
count++;
if (i < width - 1 && cells[i + 1][j].isMine())
count++;
if (i > 0 && j < height - 1 && cells[i - 1][j + 1].isMine())
count++;
if (j < height - 1 && cells[i] [j + 1].isMine())
count++;
if (i < width - 1 && j < height - 1 && cells[i + 1][j + 1].isMine())
count++;
cells[i][j].setNumber(count);
if (cells[i][j].isMine())
cells[i][j].setNumber(-1);
if (cells[i][j].getNumber() == 0)
cells[i][j].reveal();
}
}
for (int i = 0; i < width; i++){ //This is for the beginning of the game.
//If the 8 cells around certain cell have no mines beside them (hence getNumber() = 0) beside them, this cell is empty.
for (int j = 0; j < height; j++){
if (i > 0 && j > 0 && cells[i - 1][j - 1].getNumber() == 0)
cells[i][j].reveal();
if (j > 0 && cells[i][j - 1].getNumber() == 0)
cells[i][j].reveal();
if (i < width - 1 && j > 0 && cells[i + 1][j - 1].getNumber() == 0)
cells[i][j].reveal();
if (i > 0 && cells[i - 1][j].getNumber() == 0)
cells[i][j].reveal();
if (i < width - 1 && cells[i + 1][j].getNumber() == 0)
cells[i][j].reveal();
if (i > 0 && j < height - 1 && cells[i - 1][j + 1].getNumber() == 0)
cells[i][j].reveal();
if (j < height - 1 && cells[i][j + 1].getNumber() == 0)
cells[i][j].reveal();
if (i < width - 1 && j < height - 1 && cells[i + 1][j + 1].getNumber() == 0)
cells[i][j].reveal();
}
}
}
public void mark(int x, int y){ //When a player wants to flag/unflag a cell
if (cells[x][y].isFlagged()) //If the cell is already flagged, unflag it.
cells[x][y].unflag();
else if (cells[x][y].isCovered()) //If the cell has nothing on it and is covered, flag it.
cells[x][y].flag();
resetMarks();
}
private void resetMarks(){ //If a cell is not covered, then it cannot be flagged.
//Every time a player does something, this should be called to redraw the board.
for (int i = 0; i < width; i++){
for (int j = 0; j < height; j++){
if (!cells[i][j].isCovered())
cells[i][j].unflag();
}
}
}
public void reset(){ //Reset the positions of the mines on the board
//If randomly generated number from 0 to 100 is less than the chosen difficulty, a mine is placed down.
//This will somewhat accurately reflect the mine percentage that the user requested - the more cells, the more accurate.
Random random = new Random();
finished = false;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
Cell c = new Cell();
cells[i][j] = c;
int r = random.nextInt(100);
if (r < difficulty)
{
cells[i][j].setMine(); //Put down a mine.
}
}
}
setNumbers(); //Set the numbers after mines have been put down.
}
public int getx() {
return width;
}
public int gety() {
return height;
}
public Cell[][] getCells() {
return cells;
}
public void refresh(){ //Refresh the drawing of the board
board.repaint();
}
private void win(){ //Winning a game
finished = true;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
cells[i][j].reveal();//Reveal all cells
if (!cells[i][j].isMine())
cells[i][j].unflag();
}
}
refresh();
JOptionPane.showMessageDialog(null, "Congratulations! You won!"); //Tell the user they won. They probably deserve to know.
reset();
}
private void lose(){ //Losing a game...basically the same as above.
finished = true;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
if (!cells[i][j].isCovered())
cells[i][j].unflag();
cells[i][j].reveal();
}
}
refresh();
JOptionPane.showMessageDialog(null, "GAME OVER."); //Dialogue window letting the user know that they lost.
reset();
}
private boolean won(){ //Check if the game has been won
for (int i = 0; i < width; i++){
for (int j = 0; j < height; j++){
if (cells[i][j].isCovered() && !cells[i][j].isMine())
{
return false;
}
}
}
return true;
}
public boolean isFinished(){ //Extremely self-explanatory.
return finished;
}
public Minesweeper(int x, int y, int d){
width = x; //Width of the board
height = y; //Height of the board
difficulty = d; //Percentage of mines in the board
cells = new Cell[width][height];
reset(); //Set mines on the board
board = new Board(this); //Create new board
reset = new JButton("Reset"); //Reset button
add(board, BorderLayout.CENTER); //Put board in the center
add(reset, BorderLayout.SOUTH); //IT'S A BUTTON! AND IT WORKS! VERY COOL
reset.addActionListener(new Actions(this)); //ActionListener to watch for mouse actions
//GUI window settings
setTitle("Minesweeper");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
pack();
setVisible(true);
}
}
//--------------------------------- END of Minesweeper.java ---------------------------------
|
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 | #Phix | Phix | with javascript_semantics
function b10(integer n)
if n=1 then return "1" end if
integer NUM = n+1, count = 0, ten = 1, x
sequence val = repeat(0,NUM),
pow = repeat(0,NUM)
--
-- Calculate each 10^k mod n, along with all possible sums that can be
-- made from it and the things we've seen before, until we get a 0, eg:
--
-- ten/val[] (for n==7) See pow[], for k
-- 10^0 = 1 mod 7 = 1. Possible sums: 1
-- 10^1 = 10 mod 7 = 3. Possible sums: 1 3 4
-- 10^2 = 10*3 = 30 mod 7 = 2. Possible sums: 1 2 3 4 5 6
-- 10^3 = 10*2 = 20 mod 7 = 6. STOP (6+1 = 7 mod 7 = 0)
--
-- ie since 10^3 mod 7 + 10^0 mod 7 == (6+1) mod 7 == 0, we know that
-- 1001 mod 7 == 0, and we have found that w/o checking every interim
-- value from 11 to 1000 (aside: use binary if counting that range).
--
-- Another example is 10^k mod 9 is 1 for all k. Hence we need to find
-- 9 different ways to generate a 1, before we get a sum (mod 9) of 0,
-- and hence b10(9) is 111111111, ie 10^8+10^7+..+10^0, and obviously
-- 9 iterations is somewhat less than all interims 11..111111110.
--
for x=1 to n do
val[x+1] = ten
for j=1 to NUM do
if pow[j] and pow[j]!=x then -- (j seen, in a prior iteration)
integer k = mod(j-1+ten,n)+1
if not pow[k] then
pow[k] = x -- (k was seen in this iteration)
end if
end if
end for
if not pow[ten+1] then pow[ten+1] = x end if
ten = mod(10*ten,n)
if pow[1] then exit end if
end for
if pow[1]=0 then crash("Can't do it!") end if
--
-- Fairly obviously (for b10(7)) we need the 10^3, then we will need
-- a sum of 1, which first appeared for 10^0, after which we are done.
-- The required answer is therefore 1001, ie 10^3 + 10^0.
--
string res = ""
x = n
while x do
integer pm = pow[mod(x,n)+1]
if count>pm then res &= repeat('0',count-pm) end if
count = pm-1;
res &= '1'
x = mod(n+x-val[pm+1],n)
end while
res &= repeat('0',count)
return res
end function
constant tests = tagset(10)&tagset(105,95)&{297, 576, 891, 909,
999, 1998, 2079, 2251, 2277, 2439, 2997, 4878}
include mpfr.e
mpz m10 = mpz_init()
atom t0 = time()
for i=1 to length(tests) do
integer ti = tests[i]
string r10 = b10(ti)
mpz_set_str(m10,r10,10)
if mpz_fdiv_q_ui(m10,m10,ti)!=0 then r10 &= " ??" end if
printf(1,"%4d * %-24s = %s\n",{ti,mpz_get_str(m10),r10})
end for
?elapsed(time()-t0)
|
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}
.
| #Phix | Phix | with javascript_semantics
include mpfr.e
procedure mpz_mod_exp(mpz base, exponent, modulus, result)
if mpz_cmp_si(exponent,1)=0 then
mpz_set(result,base)
else
mpz _exp = mpz_init_set(exponent) -- (use a copy)
bool odd = mpz_odd(_exp)
if odd then
mpz_sub_ui(_exp,_exp,1)
end if
mpz_fdiv_q_2exp(_exp,_exp,1)
mpz_mod_exp(base,_exp,modulus,result)
_exp = mpz_free(_exp)
mpz_mul(result,result,result)
if odd then
mpz_mul(result,result,base)
end if
end if
mpz_mod(result,result,modulus)
end procedure
mpz base = mpz_init("2988348162058574136915891421498819466320163312926952423791023078876139"),
exponent = mpz_init("2351399303373464486466122544523690094744975233415544072992656881240319"),
modulus = mpz_init("1"&repeat('0',40)),
result = mpz_init()
mpz_mod_exp(base,exponent,modulus,result)
?mpz_get_str(result)
-- check against the builtin:
mpz_powm(result,base,exponent,modulus)
?mpz_get_str(result)
|
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.
| #Java | Java |
class Metronome{
double bpm;
int measure, counter;
public Metronome(double bpm, int measure){
this.bpm = bpm;
this.measure = measure;
}
public void start(){
while(true){
try {
Thread.sleep((long)(1000*(60.0/bpm)));
}catch(InterruptedException e) {
e.printStackTrace();
}
counter++;
if (counter%measure==0){
System.out.println("TICK");
}else{
System.out.println("TOCK");
}
}
}
}
public class test {
public static void main(String[] args) {
Metronome metronome1 = new Metronome(120,4);
metronome1.start();
}
}
|
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.
| #Julia | Julia |
function acquire(num, sem)
sleep(rand())
println("Task $num waiting for semaphore")
lock(sem)
println("Task $num has acquired semaphore")
sleep(rand())
unlock(sem)
end
function runsem(numtasks)
println("Sleeping and running $numtasks tasks.")
sem = Base.Threads.RecursiveSpinLock()
@sync(
for i in 1:numtasks
@async acquire(i, sem)
end)
println("Done.")
end
runsem(4)
|
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.
| #Kotlin | Kotlin | // version 1.1.51
import java.util.concurrent.Semaphore
import kotlin.concurrent.thread
fun main(args: Array<String>) {
val numPermits = 4
val numThreads = 9
val semaphore = Semaphore(numPermits)
for (i in 1..numThreads) {
thread {
val name = "Unit #$i"
semaphore.acquire()
println("$name has acquired the semaphore")
Thread.sleep(2000)
semaphore.release()
println("$name has released the semaphore")
}
}
} |
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.
| #zkl | zkl | class MC{
fcn init(n,mod){ var N=n,M=mod; }
fcn toString { String(N.divr(M)[1],"M",M) }
fcn pow(p) { self( N.pow(p).divr(M)[1], M ) }
fcn __opAdd(mc){
if(mc.isType(Int)) z:=N+mc; else z:=N*M + mc.N*mc.M;
self(z.divr(M)[1],M)
}
} |
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.
| #Ring | Ring |
multiplication_table(12)
func multiplication_table n
nSize = 4 See " | "
for t = 1 to n see fsize(t, nSize) next
see nl + "----+-" + copy("-", nSize*n) + nl
for t1 = 1 to n
see fsize(t1, nSize) + "| "
for t2 = 1 to n if t2 >= t1 see fsize(t1*t2,nSize) else see copy(" ", nSize) ok next
see nl
next
func fsize x,n return string(x) + copy(" ",n-len(string(x)))
|
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.
| #Raku | Raku | # Generate a shuffled deck
my @deck = shuffle;
put 'Shuffled deck: ', @deck;
my (@discard, @red, @black);
# Deal cards following task description
deal(@deck, @discard, @red, @black);
put 'Discard pile: ', @discard;
put '"Red" pile: ', @red;
put '"Black" pile: ', @black;
# swap the same random number of random
# cards between the red and black piles
my $amount = ^(+@red min +@black) .roll;
put 'Number of cards to swap: ', $amount;
swap(@red, @black, $amount);
put 'Red pile after swaps: ', @red;
put 'Black pile after swaps: ', @black;
say 'Number of Red cards in the Red pile: ', +@red.grep('R');
say 'Number of Black cards in the Black pile: ', +@black.grep('B');
sub shuffle { (flat 'R' xx 26, 'B' xx 26).pick: * }
sub deal (@deck, @d, @r, @b) {
while @deck.elems {
my $top = @deck.shift;
if $top eq 'R' {
@r.push: @deck.shift;
}
else {
@b.push: @deck.shift;
}
@d.push: $top;
}
}
sub swap (@r, @b, $a) {
my @ri = ^@r .pick($a);
my @bi = ^@b .pick($a);
my @rs = @r[@ri];
my @bs = @b[@bi];
@r[@ri] = @bs;
@b[@bi] = @rs;
} |
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 | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | n = {m} = {1};
tmp = {2};
Do[
m++;
While[ContainsAny[tmp, m + n],
m++
];
tmp = Join[tmp, n + m];
AppendTo[tmp, 2 m];
AppendTo[n, m]
,
{99}
]
Row[Take[n, 30], ","]
Row[Take[n, {91, 100}], ","] |
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.