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/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #REXX | REXX | /*REXX program shows mutual recursion (via the Hofstadter Male and Female sequences). */
parse arg lim .; if lim='' then lim= 40; w= length(lim); pad= left('', 20)
do j=0 for lim+1; jj= right(j, w); ff= right(F(j), w); mm= right(M(j), w)
say pad 'F('jj") =" f... |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Ruby | Ruby | require 'win32/sound'
class MorseCode
MORSE = {
"!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.",
"(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--",
"-" => "-....-", "." => ".-.-.-", "/" => "-..-.", "0" => "-----",
"1" => ".----", "2" => "..---", "3" => "...-... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Python | Python | '''
I could understand the explanation of the Monty Hall problem
but needed some more evidence
References:
http://www.bbc.co.uk/dna/h2g2/A1054306
http://en.wikipedia.org/wiki/Monty_Hall_problem especially:
http://en.wikipedia.org/wiki/Monty_Hall_problem#Increasing_the_number_of_doors
'''
from random import rand... |
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.
| #Java | Java | public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 12; i++)
System.out.print("\t" + i);
System.out.println();
for (int i = 0; i < 100; i++)
System.out.print("-");
System.out.println();
for (int i = 1; i <... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Run_BASIC | Run BASIC | [loop]
input "How many queens (N>=4)";n
if n < 4 then
print "Must be greater than 4"
goto [loop]
end if
dim plot$(100,100)
dim q(n+20)
dim e(n+20)
dim o(n+20)
r=n mod 6
if r<>2 and r<>3 then
gosub [samp]
goto [shoBoard]
end if
for i=1 to int(n/2)
e(i) = 2 * i
next
for i=1 to int((n/2)+.5)
o(i) = 2 *i-1
next... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Ring | Ring |
see "F sequence : "
for i = 0 to 20
see "" + f(i) + " "
next
see nl
see "M sequence : "
for i = 0 to 20
see "" + m(i) + " "
next
func f n
fr = 1
if n != 0 fr = n - m(f(n - 1)) ok
return fr
func m n
mr = 0
if n != 0 mr = n - f(m(n - 1)) ok
return mr
|
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Rust | Rust |
//!
//! morse_code/src/main.rs
//!
//! Michael G. Cummings
//! 2019-08-26
//!
//! Since Rust doesn't have build-in audio support text output is used.
//!
use std::process;
use structopt::StructOpt;
use morse_code::{Config, Opt, run};
/// Core of the command-line binary.
///
/// By default expects input from stdin... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ 0 ( number of cars when not changing choice )
0 ( number of cars when changing choice )
rot times
[ 3 random ( door with goat )
3 random ( contestant's choice ... |
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.
| #JavaScript | JavaScript | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>12 times table</title>
<script type='text/javascript'>
function multiplication_table(n, target) {
var table = document.createElement(... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Rust | Rust | const N: usize = 8;
fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) {
if row == N {
*count += 1;
for r in board.iter() {
println!("{}", r.iter().map(|&x| if x {"x"} else {"."}.to_string()).collect::<Vec<String>>().join(" "))
}
println!("");
retu... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Ruby | Ruby | def F(n)
n == 0 ? 1 : n - M(F(n-1))
end
def M(n)
n == 0 ? 0 : n - F(M(n-1))
end
p (Array.new(20) {|n| F(n) })
p (Array.new(20) {|n| M(n) }) |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Scala | Scala | object MorseCode extends App {
private val code = Map(
('A', ".- "), ('B', "-... "), ('C', "-.-. "), ('D', "-.. "),
('E', ". "), ('F', "..-. "), ('G', "--. "), ('H', ".... "),
('I', ".. "), ('J', ".--- "), ('K', "-.- "), ('L', ".-.. "),
('M', "-- "), ('N', "-. ... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #R | R | set.seed(19771025) # set the seed to set the same results as this code
N <- 10000 # trials
true_answers <- sample(1:3, N, replace=TRUE)
# We can assme that the contestant always choose door 1 without any loss of
# generality, by equivalence. That is, we can always relabel the doors
# to make the user-chose... |
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.
| #Jsish | Jsish | /* Multiplication tables, is Jsish */
var m, n, tableSize = 12;
if (console.args.length > 0) tableSize = parseInt(console.args[0]);
if (tableSize < 1 || tableSize > 20) tableSize = 12;
var width = String(tableSize * tableSize).length;
var spaces = ' '.repeat(width+1);
printf(spaces);
for (m = 1; m <= tableSize; m... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #SAS | SAS | /* Store all 92 permutations in a SAS dataset. Translation of Fortran 77 */
data queens;
array a{8} p1-p8;
array s{8};
array u{30};
n=8;
do i=1 to n;
a(i)=i;
end;
do i=1 to 4*n-2;
u(i)=0;
end;
m=0;
i=1;
r=2*n-1;
goto L40;
L30:
s(i)=j;
u(p)=1;
u(q+r)=1;
i=i+1;
L40:
if i>n then goto L80;
j=i;
L50:
z=a(i);
y=a(j);
p=i-y+n... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Run_BASIC | Run BASIC | print "F sequence:";
for i = 0 to 20
print f(i);" ";
next i
print :print "M sequence:";
for i = 0 to 20
print m(i);" ";
next i
end
function f(n)
f = 1
if n <> 0 then f = n - m(f(n - 1))
end function
function m(n)
m = 0
if n <> 0 then m = n - f(m(n - 1))
end function |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #sed | sed | #!/bin/sed -rf
# Convert to uppercase
s/.*/\U&/
# Add lookup table
s/$/\nA.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--../
# Main loop
:a
s/([A-Z])([^\n]*\n.*\1([-.]+))/\3 \2/
ta
# Remove lookup table
s/\n.*// |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Racket | Racket |
#lang racket
(define (get-last-door a b) ; assumes a != b
(vector-ref '#(- 2 1
2 - 0
1 0 -)
(+ a (* 3 b))))
(define (run-game strategy)
(define car-door (random 3))
(define first-choice (random 3))
(define revealed-goat
(if (= car-door first-choice)
... |
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.
| #Julia | Julia | using Printf
println(" X | 1 2 3 4 5 6 7 8 9 10 11 12")
println("---+------------------------------------------------")
for i=1:12, j=0:12
if j == 0
@printf("%2d | ", i)
elseif i <= j
@printf("%3d%c", i * j, j == 12 ? '\n' : ' ')
else
print(" ")
end
en... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Scala | Scala |
object NQueens {
private implicit class RichPair[T](
pair: (T,T))(
implicit num: Numeric[T]
) {
import num._
def safe(x: T, y: T): Boolean =
pair._1 - pair._2 != abs(x - y)
}
def solve(n: Int): Iterator[Seq[Int]] = {
(0 to n-1)
.permutations
.filter { v =>
(... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Rust | Rust | fn f(n: u32) -> u32 {
match n {
0 => 1,
_ => n - m(f(n - 1))
}
}
fn m(n: u32) -> u32 {
match n {
0 => 0,
_ => n - f(m(n - 1))
}
}
fn main() {
for i in (0..20).map(f) {
print!("{} ", i);
}
println!("");
for i in (0..20).map(m) {
print!... |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Tcl | Tcl | # This uses the GUI-free part of the Snack library
package require sound
# A simple pause while running the event loop, in terms of basic time units
proc pause n {
global t
after [expr {$t * $n}] set ok 1
vwait ok
}
# Generate using a sine-wave filter
proc beep n {
global frequency
set f [snack::f... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Raku | Raku | enum Prize <Car Goat>;
enum Strategy <Stay Switch>;
sub play (Strategy $strategy, Int :$doors = 3) returns Prize {
# Call the door with a car behind it door 0. Number the
# remaining doors starting from 1.
my Prize @doors = flat Car, Goat xx $doors - 1;
# The player chooses a door.
my Prize $i... |
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.
| #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
print(" x|")
for (i in 1..12) print("%4d".format(i))
println("\n---+${"-".repeat(48)}")
for (i in 1..12) {
print("%3d".format(i) +"|${" ".repeat(4 * i - 4)}")
for (j in i..12) print("%4d".format(i * j))
println()
}
} |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Scheme | Scheme |
(import (scheme base)
(scheme write)
(srfi 1))
;; return list of solutions to n-queens problem
(define (n-queens n) ; breadth-first solution
(define (place-initial-row) ; puts a queen on each column of row 0
(list-tabulate n (lambda (col) (list (cons 0 col)))))
(define (place-on-row soln-so-... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #S-lang | S-lang | % Forward definitions: [also deletes any existing definition]
define f();
define m();
define f(n) {
if (n == 0) return 1;
else if (n < 0) error("oops");
return n - m(f(n - 1));
}
define m(n) {
if (n == 0) return 0;
else if (n < 0) error("oops");
return n - f(m(n - 1));
}
foreach $1 ([0:19])
() = pri... |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
MODE DATA
$$ BUILD X_TABLE alfabet2moco =*
"!"---."\".-..-."$"...-..-"'".----."
"("-.--.")"-.--.-"+".-.-.","--..--"
"-"-....-".".-.-.-"/"-..-."
"0"-----"1".----"2"..---"3"...--"
"4"....-"5"....."6"-...."7"--..."
"8"---.."9"----."
":"---...";"-.-.-."="-...-"?"..--.."
"@".--.-."
"A".-"B"-..."C"-.-."D"-... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #REXX | REXX | /* REXX ***************************************************************
* 30.08.2013 Walter Pachl derived from Java
**********************************************************************/
Call time 'R'
switchWins = 0;
stayWins = 0
Do plays = 1 To 1000000
doors.=0
r=r3()
doors.r=1
choice = r3()
Do Until shown<... |
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.
| #Lambdatalk | Lambdatalk |
{def format
{lambda {:w :c}
{@ style="width::wpx;
color::c;
text-align:right;"
}}}
-> format
{def operation
{lambda {:op :i :j}
{if {and {= :i 0} {= :j 0}} // left top cell
then {format 30 #fff} // is empty
else {if {= :i 0} ... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Scilab | Scilab | //Length of board side
Board_size = 8;
function flag_out = no_attack(side, board, pos)
//Evaluates (pos(1),pos(2)) in board if it's not on any queen attacking range
//side (scalar): board's side length
//board (sidexside matrix): matrix of 0s and 1s representing queens on a board
//pos (1x2 matrix): p... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Sather | Sather | class MAIN is
f(n:INT):INT
pre n >= 0
is
if n = 0 then return 1; end;
return n - m(f(n-1));
end;
m(n:INT):INT
pre n >= 0
is
if n = 0 then return 0; end;
return n - f(m(n-1));
end;
main is
loop i ::= 0.upto!(19);
#OUT + #FMT("%2d ", f(i));
end;
#OUT + "\n";
... |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Ursa | Ursa | decl ursa.util.sound snd
decl string<> chars
decl string<> morse
append "!" "\"" "$" "'" "(" ")" "+" chars
append "---." ".-..-." "...-..-" ".----." "-.--." "-.--.-" ".-.-." morse
append "," "-" "." "/" "0" "1" "2" chars
append "--..--" "-....-" ".-.-.-" ... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Ring | Ring |
total = 10000
swapper = 0
sticker = 0
revealdoor = 0
for trial = 1 to total
prizedoor = random(3) + 1
guessdoor = random(3) + 1
if prizedoor = guessdoor
revealdoor = random(2) + 1
if prizedoor = 1 revealdoor += 1 ok
if (prizedoor = 2 and revealdoor = 2) revealdoor = 3 ok
else
... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Ruby | Ruby | n = 10_000 #number of times to play
stay = switch = 0 #sum of each strategy's wins
n.times do #play the game n times
#the doors reveal 2 goats and a car
doors = [ :goat, :goat, :car ].shuffle
#random guess
guess = rand(3)
#random door shown, but it is neit... |
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.
| #Lasso | Lasso | define printTimesTables(max::integer) => {
local(result) = ``
local(padSize) = string(#max*#max)->size + 1
// Print header row
#result->append((' ' * #padSize) + '|')
loop(#max) => {
#result->append(loop_count->asString(-padding=#padSize))
}
#result->append("\n" + (`-` * #padSize)... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
var array integer: board is 8 times 0;
var integer: solutionNum is 0;
const func boolean: safe (in integer: y) is func
result
var boolean: safe is TRUE;
local
var integer: i is 1;
begin
while i < y and safe do
safe := board[y - i] <> board[y] and
board... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Scala | Scala | def F(n:Int):Int =
if (n == 0) 1 else n - M(F(n-1))
def M(n:Int):Int =
if (n == 0) 0 else n - F(M(n-1))
println((0 until 20).map(F).mkString(", "))
println((0 until 20).map(M).mkString(", ")) |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #VBA | VBA | Option Explicit
Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Run_BASIC | Run BASIC | ' adapted from BASIC solution
input "Number of tries;";tries ' gimme the number of iterations
FOR plays = 1 TO tries
winner = INT(RND(1) * 3) + 1
doors(winner) = 1 'put a winner in a random door
choice = INT(RND(1) * 3) + 1 'pick a door please
[DO] shown = INT(RND(1) * 3) + 1
' --------------------... |
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.
| #Liberty_BASIC | Liberty BASIC | Print " | 1 2 3 4 5 6 7 8 9 10 11 12"
Print "--+------------------------------------------------------------"
For i = 1 To 12
nums$ = Right$(" " + str$(i), 2) + "|"
For ii = 1 To 12
If i <= ii Then
If ii >= 1 Then
nums$ = nums$ + Left$(" ... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Sidef | Sidef | func N_queens_solution(N = 8) {
func collision(field, row) {
for i in (^row) {
var distance = (field[i] - field[row])
distance ~~ [0, row-i, i-row] && return true
}
return false
}
func search(field, row) {
row == N && return field
for i in ... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Scheme | Scheme | (define (F n)
(if (= n 0) 1
(- n (M (F (- n 1))))))
(define (M n)
(if (= n 0) 0
(- n (F (M (- n 1)))))) |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Visual_Basic | Visual Basic | Module Module1
Sub Main()
Dim word = "sos"
Dim codes As New Dictionary(Of String, String) From {
{"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "},
{"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "},
{"i", ".. "}, {"j", ".--- "}, {"k",... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Rust | Rust | extern crate rand;
use rand::Rng;
use rand::seq::SliceRandom;
#[derive(Clone, Copy, PartialEq)]
enum Prize {Goat , Car}
const GAMES: usize = 3_000_000;
fn main() {
let mut switch_wins = 0;
let mut rng = rand::thread_rng();
for _ in 0..GAMES {
let mut doors = [Prize::Goat; 3];
*doors.ch... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Scala | Scala | import scala.util.Random
object MontyHallSimulation {
def main(args: Array[String]) {
val samples = if (args.size == 1 && (args(0) matches "\\d+")) args(0).toInt else 1000
val doors = Set(0, 1, 2)
var stayStrategyWins = 0
var switchStrategyWins = 0
1 to samples foreach { _ =>
val prizeDo... |
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.
| #Logo | Logo | to mult.table :n
type "| | for [i 2 :n] [type form :i 4 0] (print)
(print)
for [i 2 :n] [
type form :i 2 0
for [j 2 :n] [
type ifelse :i > :j ["| |] [form :i*:j 4 0]
]
(print)
]
end
mult.table 12
|
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #SNOBOL4 | SNOBOL4 |
* N queens problem
* Set N to the desired number. The program prints out all solution boards.
N = 5
NM1 = N - 1; NP1 = N + 1; NSZ = N * NP1; &STLIMIT = 10 ** 9; &ANCHOR = 1
DEFINE('SOLVE(B)I')
* This pattern tests if the first queen attacks any of the others:
TEST = BREAK('Q') 'Q' (ARBNO(LEN(N) '-') LEN(N) 'Q'
+... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: m (in integer: n) is forward;
const func integer: f (in integer: n) is func
result
var integer: res is 0;
begin
if n = 0 then
res := 1;
else
res := n - m(f(n - 1));
end if;
end func;
const func integer: m (in integer: n) is func
res... |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Dim word = "sos"
Dim codes As New Dictionary(Of String, String) From {
{"a", ".- "}, {"b", "-... "}, {"c", "-.-. "}, {"d", "-.. "},
{"e", ". "}, {"f", "..-. "}, {"g", "--. "}, {"h", ".... "},
{"i", ".. "}, {"j", ".--- "}, {"k",... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Scheme | Scheme | (define (random-from-list list) (list-ref list (random (length list))))
(define (random-permutation list)
(if (null? list)
'()
(let* ((car (random-from-list list))
(cdr (random-permutation (remove car list))))
(cons car cdr))))
(define (random-configuration) (random-permutation '(goat... |
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.
| #Lua | Lua | io.write( " |" )
for i = 1, 12 do
io.write( string.format( "%#5d", i ) )
end
io.write( "\n", string.rep( "-", 12*5+4 ), "\n" )
for i = 1, 12 do
io.write( string.format( "%#2d |", i ) )
for j = 1, 12 do
if j < i then
io.write( " " )
else
io.write( string.form... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #11l | 11l | F modifier(Float x) -> Float
R I x < 0.5 {2 * (.5 - x)} E 2 * (x - .5)
F modified_random_distribution((Float -> Float) modifier, Int n) -> [Float]
[Float] d
L d.len < n
V prob = random:()
I random:() < modifier(prob)
d.append(prob)
R d
V data = modified_random_distribution(modifier,... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Sparkling | Sparkling | let print_table = function (pos) {
pos.foreach(function (_, i) {
stdout.printf(" %c", 'a' + i);
});
stdout.write("\n");
pos.foreach(function (col, row) {
stdout.printf("%d", row + 1);
stdout.printf("%s #\n", range(col).reduce("", function (s, t) {
return s .. " ";
}));
});
stdout.write("\n\n")... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #11l | 11l | -V MAXITER = 151
F minkowski(x) -> Float
I x > 1 | x < 0
R floor(x) + minkowski(x - floor(x))
V p = Int(x)
V q = 1
V r = p + 1
V s = 1
V d = 1.0
V y = Float(p)
L
d /= 2
I y + d == y
L.break
V m = p + r
I m < 0 | p < 0
L.break
V n = ... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Sidef | Sidef | func F(){}
func M(){}
F = func(n) { n > 0 ? (n - M(F(n-1))) : 1 }
M = func(n) { n > 0 ? (n - F(M(n-1))) : 0 }
[F, M].each { |seq|
{|i| seq.call(i)}.map(^20).join(' ').say
} |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Wren | Wren | import "/str" for Str
import "/sound" for Wav
var charToMorse = {
"!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.",
"(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--",
"-": "-....-", ".": ".-.-.-", "/": "-..-.",
"0": "-----", "1": ".----", "2": "..---", "3": "...--... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Scilab | Scilab | // How it works:
// MontyHall() is a function with argument switch:
// it will be called 100000 times with switch=%T,
// and another 100000 times with switch=%F
function win=MontyHall(switch) //If switch==%T the player will switch
doors=zeros(1,3) //All goats
car=grand(1,1,'uin',1,3)
... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: switchWins is 0;
var integer: stayWins is 0;
var integer: winner is 0;
var integer: choice is 0;
var integer: shown is 0;
var integer: plays is 0;
begin
for plays range 1 to 10000 do
winner := rand(1, 3);
... |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Dim Base 1, A(12)
Mult=lambda (n)-> {
Flush ' empty stack
For i=1 to n : Data i*n : Next i
=Array([]) ' copy stack in an array, and return a pointer
}
i=Each(A())
Print " |";
while i {
Print Format$("{0:0:-4}",i^+... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Ada | Ada | with Ada.Text_Io;
with Ada.Numerics.Float_Random;
with Ada.Strings.Fixed;
procedure Modified_Distribution is
Observations : constant := 20_000;
Buckets : constant := 25;
Divider : constant := 12;
Char : constant Character := '*';
generic
with function Modifier (X : Float) re... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #ALGOL_68 | ALGOL 68 | BEGIN # find the smallest m where mn = digit sum of n, n in 1 .. 70 #
# returns the digit sum of n, n must be >= 0 #
OP DIGITSUM = ( INT n )INT:
IF n < 10 THEN n
ELSE
INT result := n MOD 10;
INT v := n OVER 10;
WHILE v > 0 DO
result ... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #SQL | SQL |
WITH RECURSIVE
positions(i) AS (
VALUES(0)
UNION SELECT ALL
i+1 FROM positions WHERE i < 63
),
solutions(board, n_queens) AS (
SELECT '----------------------------------------------------------------', CAST(0 AS BIGINT)
FROM positions
UNION
SELECT
substr(board, 1, i) || '*... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Factor | Factor | USING: formatting kernel make math math.constants
math.continued-fractions math.functions math.parser
math.statistics sequences sequences.extras splitting.monotonic
vectors ;
CONSTANT: max-iter 151
: >continued-fraction ( x -- seq )
0 swap 1vector
[ dup last integer? pick max-iter > or ]
[ dup next-appr... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #FreeBASIC | FreeBASIC | #define MAXITER 151
function minkowski( x as double ) as double
if x>1 or x<0 then return int(x)+minkowski(x-int(x))
dim as ulongint p = int(x)
dim as ulongint q = 1, r = p + 1, s = 1, m, n
dim as double d = 1, y = p
while true
d = d / 2.0
if y + d = y then exit while
m = ... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #Smalltalk | Smalltalk | |F M ra rb|
F := [ :n |
(n == 0)
ifTrue: [ 1 ]
ifFalse: [ n - (M value: (F value: (n-1))) ]
].
M := [ :n |
(n == 0)
ifTrue: [ 0 ]
ifFalse: [ n - (F value: (M value: (n-1))) ]
].
ra := OrderedCollection new.
rb := OrderedCollection new.
0 to: 19 do: [ :i |
ra add: (F value: i).
rb ad... |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #XPL0 | XPL0 | code ChOut=8, CrLf=9, Sound=39;
string 0; \use zero-terminated strings
proc Morse(Msg); \Output Msg string as audible International Morse code
char Msg;
char C, D;
int Code, Vol;
[Code:= [" ", \space
".-.-..",".-..-.", " ", "...-..-"," ", ... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Sidef | Sidef | var n = 1000 # number of times to play
var switchWins = (var stayWins = 0) # sum of each strategy's wins
n.times { # play the game n times
var prize = pick(^3)
var chosen = pick(^3)
var show;
do {
show = pick(^3)
}... |
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.
| #Maple | Maple | printf(" ");
for i to 12 do
printf("%-3d ", i);
end do;
printf("\n");
for i to 75 do
printf("-");
end do;
for i to 12 do
printf("\n%2d| ", i);
for j to 12 do
if j<i then
printf(" ");
else
printf("%-3d ", i * j);
end if
end do
end do |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Factor | Factor | USING: assocs assocs.extras formatting io kernel math
math.functions math.statistics random sequences
tools.memory.private ;
: modifier ( x -- y ) 0.5 over 0.5 < [ swap ] when - dup + ;
: random-unit-by ( quot: ( x -- y ) -- z )
random-unit dup pick call random-unit 2dup >
[ 2drop nip ] [ 3drop random-unit-... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #FreeBASIC | FreeBASIC | #define NRUNS 100000
#define NBINS 20
function modifier( x as double ) as double
return iif(x < 0.5, 2*(0.5 - x), 2*(x - 0.5))
end function
function modrand() as double
dim as double random1, random2
do
random1 = rnd
random2 = rnd
if random2 < modifier(random1) then
r... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #APL | APL | {n←⍵ ⋄ (+∘1)⍣{n=+/10⊥⍣¯1⊢⍺×n}⊢0 } ¨ 7 10⍴⍳70 |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #AWK | AWK |
# syntax: GAWK -f MINIMUM_MULTIPLE_OF_M_WHERE_DIGITAL_SUM_EQUALS_M.AWK
BEGIN {
start = 1
stop = 70
printf("A131382 %d-%d:\n",start,stop)
for (n=start; n<=stop; n++) {
for (m=1; ; m++) {
if (digit_sum(m*n,10) == n) {
printf("%9d%1s",m,++count%10?"":"\n")
break
... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #SQL_PL | SQL PL |
-- A column of a matrix.
CREATE TYPE INTEGER_ARRAY AS INTEGER ARRAY[]@
-- The whole matrix of any size.
CREATE TYPE INTEGER_MATRIX AS INTEGER_ARRAY ARRAY[]@
/**
* Retrieves the value from a matrix at a specific position.
*
* IN X: Row number.
* IN Y: Column number.
* IN M: Matrix.
* RETURN the integer value ... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Go | Go | package main
import (
"fmt"
"math"
)
const MAXITER = 151
func minkowski(x float64) float64 {
if x > 1 || x < 0 {
return math.Floor(x) + minkowski(x-math.Floor(x))
}
p := uint64(x)
q := uint64(1)
r := p + 1
s := uint64(1)
d := 1.0
y := float64(p)
for {
d ... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #SNOBOL4 | SNOBOL4 | define('f(n)') :(f_end)
f f = eq(n,0) 1 :s(return)
f = n - m(f(n - 1)) :(return)
f_end
define('m(n)') :(m_end)
m m = eq(n,0) 0 :s(return)
m = n - f(m(n - 1)) :(return)
m_end
* # Test and display
L1 s1 = s1 m(i) ' ' ; s2 = s2 f(i) ' '
i = le(i,25) i + 1... |
http://rosettacode.org/wiki/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #Yabasic | Yabasic | 10 REM Morse code
20 DIM c$(54)
30 FOR f = 1 TO 54
40 READ l$, m$
50 LET d$ = d$ + l$ : LET c$(f) = m$
60 NEXT f
100 LINE INPUT "Message? " t$
105 t$ = upper$(t$)
110 FOR f = 1 TO LEN(t$)
120 p = INSTR(d$, mid$(t$, f, 1))
130 IF p > 0 then
PRINT c$(p);
else
print "?";
end if
140 NEXT f
print
g... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #SPAD | SPAD |
montyHall(n) ==
wd:=[1+random(3) for j in 1..n]
fc:=[1+random(3) for j in 1..n]
st:=reduce(_+,[1 for j in 1..n | wd.j=fc.j])
p:=(st/n)::DoubleFloat
FORMAT(nil,"stay: ~A, switch: ~A",p,1-p)$Lisp
|
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Stata | Stata | clear
set obs 1000000
gen car=runiformint(1,3)
gen choice1=runiformint(1,3)
gen succ1=car==choice1
gen shown=cond(succ1,runiformint(1,2),6-car-choice1)
replace shown=shown+1 if succ1 & (car==1 | car==shown)
gen choice2=6-shown-choice1
gen succ2=car==choice2
tabstat succ1 succ2, s(mean) |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Grid[{{Range[12]//Column,Grid[UpperTriangularize[KroneckerProduct[Range[12],Range[12]]]/.{0->""}]}}] |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math"
"math/rand"
"strings"
"time"
)
func rng(modifier func(x float64) float64) float64 {
for {
r1 := rand.Float64()
r2 := rand.Float64()
if r2 < modifier(r1) {
return r1
}
}
}
func commatize(n int) string {
s... |
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
{\displaysty... | #Ada | Ada | with Ada.Text_IO;
procedure Modular_Demo is
type Modul_13 is mod 13;
function F (X : Modul_13) return Modul_13 is
begin
return X**100 + X + 1;
end F;
package Modul_13_IO is
new Ada.Text_IO.Modular_IO (Modul_13);
use Ada.Text_IO;
use Modul_13_IO;
X_Integer : constant Intege... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #BASIC | BASIC | c = 0
n = 1
while c < 70
m = 1
while 1
nm = n*m
t = 0
while nm
t += nm mod 10
nm = floor(nm / 10)
end while
if t = n then exit while
m += 1
end while
c += 1
print rjust(string(m), 8); " ";
if c mod 10 = 0 then print
n += 1
end... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #C | C | #include <stdio.h>
unsigned digit_sum(unsigned n) {
unsigned sum = 0;
do { sum += n % 10; }
while(n /= 10);
return sum;
}
unsigned a131382(unsigned n) {
unsigned m;
for (m = 1; n != digit_sum(m*n); m++);
return m;
}
int main() {
unsigned n;
for (n = 1; n <= 70; n++) {
p... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Standard_ML | Standard ML |
(*
* val threat : (int * int) -> (int * int) -> bool
* Returns true iff the queens at the given positions threaten each other
*)
fun threat (x, y) (x', y') =
x = x' orelse y = y' orelse abs(x - x') = abs(y - y');
(*
* val conflict : (int * int) -> (int * int) list -> bool
* Returns true if there exists a co... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Haskell | Haskell | import Data.Tree
import Data.Ratio
import Data.List
intervalTree :: (a -> a -> a) -> (a, a) -> Tree a
intervalTree node = unfoldTree $
\(a, b) -> let m = node a b in (m, [(a,m), (m,b)])
Node a _ ==> Node b [] = const b
Node a [] ==> Node b _ = const b
Node a [l1, r1] ==> Node b [l2, r2] =
\x -> case x `compare`... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #SNUSP | SNUSP | /======\
F==!/=!\?\+# | />-<-\
| \@\-@/@\===?/<#
| | |
$+++/======|====/
! /=/ /+<<-\
| \!/======?\>>=?/<# dup
| \<<+>+>-/
! !
\======|====\
| | |
| /===|==\ |
M==!\=!\?\#| | |
\@/-@/@/===?\<#
^ \>-<-/
... |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Swift | Swift | import Foundation
func montyHall(doors: Int = 3, guess: Int, switch: Bool) -> Bool {
guard doors > 2, guess > 0, guess <= doors else { fatalError() }
let winningDoor = Int.random(in: 1...doors)
return winningDoor == guess ? !`switch` : `switch`
}
var switchResults = [Bool]()
for _ in 0..<1_000 {
let g... |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | function table = timesTable(N)
table = [(0:N); (1:N)' triu( kron((1:N),(1:N)') )];
end |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"strings"
"time"
)
func rng(modifier func(x float64) float64) float64 {
for {
r1 := rand.Float64()
r2 := rand.Float64()
if r2 < modifier(r1) {
return r1
}
}
}
func commatize(n int) string {
s... |
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
{\displaysty... | #ALGOL_68 | ALGOL 68 | # allow for large integers in Algol 68G #
PR precision 200 PR
# modular integer type #
MODE MODULARINT = STRUCT( LONG LONG INT v, INT modulus );
# modular integer + and * operators #
# where both operands are modular, they must have the same modulus #
OP + = ( MODULARINT a, b )MODULARINT: ( ( v OF a + v OF b )... |
http://rosettacode.org/wiki/Minimum_multiple_of_m_where_digital_sum_equals_m | Minimum multiple of m where digital sum equals m | Generate the sequence a(n) when each element is the minimum integer multiple m such that the digit sum of n times m is equal to n.
Task
Find the first 40 elements of the sequence.
Stretch
Find the next 30 elements of the sequence.
See also
OEIS:A131382 - Minimal number m such that Sum_digits(n*m)=n
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
int digit_sum(int n) {
int sum = 0;
for (; n > 0; n /= 10)
sum += n % 10;
return sum;
}
int main() {
for (int n = 1; n <= 70; ++n) {
for (int m = 1;; ++m) {
if (digit_sum(m * n) == n) {
std::cout << std::setw(8) << m ... |
http://rosettacode.org/wiki/Minimal_steps_down_to_1 | Minimal steps down to 1 |
Given:
A starting, positive integer (greater than one), N.
A selection of possible integer perfect divisors, D.
And a selection of possible subtractors, S.
The goal is find the minimum number of steps necessary to reduce N down to one.
At any step, the number may be:
Divided by any member of D if it is perfect... | #11l | 11l | T Mintab
Set[Int] divs, subs
[Int] table
[[String]] hows
F (divs, subs)
.divs = copy(divs)
.subs = copy(subs)
F _mintab(n)
‘Tabulation, memoised minimised steps to 1’
V table = [n + 2] * (n + 1)
table[1] = 0
V how = (0 .< n + 2).map(_ -> [‘’])
how[1] = [Strin... |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #Stata | Stata | mata
real matrix queens(real scalar n) {
real scalar i, j, k, p, q
real rowvector a, s, u, v
real matrix m
m = J(0, n, .)
a = 1..n
s = J(1, n, 0)
u = J(1, 2*n-1, 1)
v = J(1, 2*n-1, 1)
i = 1
L1: if (i > n) {
m = m\a
goto L4
}
j=i
L2: k = a[j]
p = i-k+n
q = i+k-1
if (u[p] & v[q]) {
u[p] = v[q] = 0
... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #J | J | ITERCOUNT=: 52
minkowski=: {{
f=. 1|y
node=. *i.2 2 NB. node of Stern-Brocot tree
B=. ''
for. i.ITERCOUNT do.
B=. B, b=. f>:%/t=. +/node
node=. t (1-b)} node
end.
(<.y)+B+/ .*2^-1+i.ITERCOUNT
}}
invmink=: {{
f=. 1|y
cf=. i.0
cur=. 0 NB. 1 if generating "top" side of cf
cnt=. 1 NB. propo... |
http://rosettacode.org/wiki/Minkowski_question-mark_function | Minkowski question-mark function | The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o... | #Julia | Julia | function minkowski(x)
p = Int(floor(x))
(x > 1 || x < 0) && return p + minkowski(x)
q, r, s, m, n = 1, p + 1, 1, 0, 0
d, y = 1.0, Float64(p)
while true
d /= 2.0
y + d == y && break
m = p + r
(m < 0 || p < 0) && break
n = q + s
n < 0 && break
if... |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
... | #SPL | SPL | f(n)=
? n=0, <= 1
<= n-m(f(n-1))
.
m(n)=
? n=0, <= 0
<= n-f(m(n-1))
.
> i, 0..20
fs += " "+f(i)
ms += " "+m(i)
<
#.output("F:",fs)
#.output("M:",ms) |
http://rosettacode.org/wiki/Monty_Hall_problem | Monty Hall problem |
Suppose you're on a game show and you're given the choice of three doors.
Behind one door is a car; behind the others, goats.
The car and the goats were placed randomly behind the doors before the show.
Rules of the game
After you have chosen a door, the door remains closed for the time being.
The game show hos... | #Tcl | Tcl | set stay 0; set change 0; set total 10000
for {set i 0} {$i<$total} {incr i} {
if {int(rand()*3) == int(rand()*3)} {
incr stay
} else {
incr change
}
}
puts "Estimate: $stay/$total wins for staying strategy"
puts "Estimate: $change/$total wins for changing strategy" |
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.
| #Maxima | Maxima | for i: 1 thru 12 do (
for j: 1 thru 12 do (
if j>=i or j=1 then printf(true, "~4d", i*j) else printf(true, " ")
),
printf(true, "~%")
); |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Haskell | Haskell | import System.Random
import Data.List
import Text.Printf
modify :: Ord a => (a -> a) -> [a] -> [a]
modify f = foldMap test . pairs
where
pairs lst = zip lst (tail lst)
test (r1, r2) = if r2 < f r1 then [r1] else []
vShape x = if x < 0.5 then 2*(0.5-x) else 2*(x-0.5)
hist b lst = zip [0,b..] res
where... |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #J | J | probmod=: {{y
while.do.r=.?0 0
if. (<u)/r do. {:r return.end.
end.
}}
mod=: {{|1-2*y}} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.