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/Percolation/Mean_cluster_density | Percolation/Mean cluster density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
c
{\displaystyle c}
be a 2D boolean square matrix of
n
×
n
{\displaystyle n\times n}
values of either 1 or 0 where the
probability of any value being 1 is
p
{\displaystyle p}
, (and of 0 is therefore
1
−
p
{\displaystyle 1-p}
).
We define a cluster of 1's as being a group of 1's connected vertically or
horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either
0
{\displaystyle 0}
or by the limits of the matrix.
Let the number of such clusters in such a randomly constructed matrix be
C
n
{\displaystyle C_{n}}
.
Percolation theory states that
K
(
p
)
{\displaystyle K(p)}
(the mean cluster density) will satisfy
K
(
p
)
=
C
n
/
n
2
{\displaystyle K(p)=C_{n}/n^{2}}
as
n
{\displaystyle n}
tends to infinity. For
p
=
0.5
{\displaystyle p=0.5}
,
K
(
p
)
{\displaystyle K(p)}
is found numerically to approximate
0.065770
{\displaystyle 0.065770}
...
Task
Show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
for
p
=
0.5
{\displaystyle p=0.5}
and
for values of
n
{\displaystyle n}
up to at least
1000
{\displaystyle 1000}
.
Any calculation of
C
n
{\displaystyle C_{n}}
for finite
n
{\displaystyle n}
is subject to randomness, so an approximation should be
computed as the average of
t
{\displaystyle t}
runs, where
t
{\displaystyle t}
≥
5
{\displaystyle 5}
.
For extra credit, graphically show clusters in a
15
×
15
{\displaystyle 15\times 15}
,
p
=
0.5
{\displaystyle p=0.5}
grid.
Show your output here.
See also
s-Cluster on Wolfram mathworld. | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var RAND_MAX = 32767
var list = []
var w = 0
var ww = 0
var ALPHA = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var ALEN = ALPHA.count - 3
var makeList = Fn.new { |p|
var thresh = (p * RAND_MAX).truncate
ww = w * w
var i = ww
list = List.filled(i, 0)
while (i != 0) {
i = i - 1
var r = rand.int(RAND_MAX+1)
if (r < thresh) list[i] = -1
}
}
var showCluster = Fn.new {
var k = 0
for (i in 0...w) {
for (j in 0...w) {
var s = list[k]
k = k + 1
var c = (s < ALEN) ? ALPHA[1 + s] : "?"
System.write(" %(c)")
}
System.print()
}
}
var recur // recursive
recur = Fn.new { |x, v|
if (x >= 0 && x < ww && list[x] == -1) {
list[x] = v
recur.call(x - w, v)
recur.call(x - 1, v)
recur.call(x + 1, v)
recur.call(x + w, v)
}
}
var countClusters = Fn.new {
var cls = 0
for (i in 0...ww) {
if (list[i] == -1) {
cls = cls + 1
recur.call(i, cls)
}
}
return cls
}
var tests = Fn.new { |n, p|
var k = 0
for (i in 0...n) {
makeList.call(p)
k = k + countClusters.call() / ww
}
return k / n
}
w = 15
makeList.call(0.5)
var cls = countClusters.call()
System.print("width = 15, p = 0.5, %(cls) clusters:")
showCluster.call()
System.print("\np = 0.5, iter = 5:")
w = 1 << 2
while (w <= (1 << 13)) {
var t = tests.call(5, 0.5)
Fmt.print("$5d $9.6f", w, t)
w = w << 1
} |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Axiom | Axiom | perfect?(n:Integer):Boolean == reduce(+,divisors n) = 2*n |
http://rosettacode.org/wiki/Percolation/Bond_percolation | Percolation/Bond percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
, assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards. Each
c
e
l
l
[
m
,
n
]
{\displaystyle \mathrm {cell} [m,n]}
is bounded by (horizontal) walls
h
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {hwall} [m,n]}
and
h
w
a
l
l
[
m
+
1
,
n
]
{\displaystyle \mathrm {hwall} [m+1,n]}
; (vertical) walls
v
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {vwall} [m,n]}
and
v
w
a
l
l
[
m
,
n
+
1
]
{\displaystyle \mathrm {vwall} [m,n+1]}
Assume that the probability of any wall being present is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
Except for the outer horizontal walls at
m
=
0
{\displaystyle m=0}
and
m
=
M
{\displaystyle m=M}
which are always present.
The task
Simulate pouring a fluid onto the top surface (
n
=
0
{\displaystyle n=0}
) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall.
The fluid does not move beyond the horizontal constraints of the grid.
The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
=
100
{\displaystyle t=100}
.
Use an
M
=
10
,
N
=
10
{\displaystyle M=10,N=10}
grid of cells for all cases.
Optionally depict fluid successfully percolating through a grid graphically.
Show all output on this page.
| #Swift | Swift | let randMax = 32767.0
let filled = 1
let rightWall = 2
let bottomWall = 4
final class Percolate {
let height: Int
let width: Int
private var grid: [Int]
private var end: Int
init(height: Int, width: Int) {
self.height = height
self.width = width
self.end = width
self.grid = [Int](repeating: 0, count: width * (height + 2))
}
private func fill(at p: Int) -> Bool {
guard grid[p] & filled == 0 else { return false }
grid[p] |= filled
guard p < end else { return true }
return (((grid[p + 0] & bottomWall) == 0) && fill(at: p + width)) ||
(((grid[p + 0] & rightWall) == 0) && fill(at: p + 1)) ||
(((grid[p - 1] & rightWall) == 0) && fill(at: p - 1)) ||
(((grid[p - width] & bottomWall) == 0) && fill(at: p - width))
}
func makeGrid(porosity p: Double) {
grid = [Int](repeating: 0, count: width * (height + 2))
end = width
let thresh = Int(randMax * p)
for i in 0..<width {
grid[i] = bottomWall | rightWall
}
for _ in 0..<height {
for _ in stride(from: width - 1, through: 1, by: -1) {
let r1 = Int.random(in: 0..<Int(randMax)+1)
let r2 = Int.random(in: 0..<Int(randMax)+1)
grid[end] = (r1 < thresh ? bottomWall : 0) | (r2 < thresh ? rightWall : 0)
end += 1
}
let r3 = Int.random(in: 0..<Int(randMax)+1)
grid[end] = rightWall | (r3 < thresh ? bottomWall : 0)
end += 1
}
}
@discardableResult
func percolate() -> Bool {
var i = 0
while i < width && !fill(at: width + i) {
i += 1
}
return i < width
}
func showGrid() {
for _ in 0..<width {
print("+--", terminator: "")
}
print("+")
for i in 0..<height {
print(i == height ? " " : "|", terminator: "")
for j in 0..<width {
print(grid[i * width + j + width] & filled != 0 ? "[]" : " ", terminator: "")
print(grid[i * width + j + width] & rightWall != 0 ? "|" : " ", terminator: "")
}
print()
guard i != height else { return }
for j in 0..<width {
print(grid[i * width + j + width] & bottomWall != 0 ? "+--" : "+ ", terminator: "")
}
print("+")
}
}
}
let p = Percolate(height: 10, width: 10)
p.makeGrid(porosity: 0.5)
p.percolate()
p.showGrid()
print("Running \(p.height) x \(p.width) grid 10,000 times for each porosity")
for factor in 1...10 {
var count = 0
let porosity = Double(factor) / 10.0
for _ in 0..<10_000 {
p.makeGrid(porosity: porosity)
if p.percolate() {
count += 1
}
}
print("p = \(porosity): \(Double(count) / 10_000.0)")
} |
http://rosettacode.org/wiki/Percolation/Bond_percolation | Percolation/Bond percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
, assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards. Each
c
e
l
l
[
m
,
n
]
{\displaystyle \mathrm {cell} [m,n]}
is bounded by (horizontal) walls
h
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {hwall} [m,n]}
and
h
w
a
l
l
[
m
+
1
,
n
]
{\displaystyle \mathrm {hwall} [m+1,n]}
; (vertical) walls
v
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {vwall} [m,n]}
and
v
w
a
l
l
[
m
,
n
+
1
]
{\displaystyle \mathrm {vwall} [m,n+1]}
Assume that the probability of any wall being present is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
Except for the outer horizontal walls at
m
=
0
{\displaystyle m=0}
and
m
=
M
{\displaystyle m=M}
which are always present.
The task
Simulate pouring a fluid onto the top surface (
n
=
0
{\displaystyle n=0}
) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall.
The fluid does not move beyond the horizontal constraints of the grid.
The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
=
100
{\displaystyle t=100}
.
Use an
M
=
10
,
N
=
10
{\displaystyle M=10,N=10}
grid of cells for all cases.
Optionally depict fluid successfully percolating through a grid graphically.
Show all output on this page.
| #Tcl | Tcl | package require Tcl 8.6
# Structure the bond percolation system as a class
oo::class create BondPercolation {
variable hwall vwall cells M N
constructor {width height probability} {
set M $height
set N $width
for {set i 0} {$i <= $height} {incr i} {
for {set j 0;set walls {}} {$j < $width} {incr j} {
lappend walls [expr {rand() < $probability}]
}
lappend hwall $walls
}
for {set i 0} {$i <= $height} {incr i} {
for {set j 0;set walls {}} {$j <= $width} {incr j} {
lappend walls [expr {$j==0 || $j==$width || rand() < $probability}]
}
lappend vwall $walls
}
set cells [lrepeat $height [lrepeat $width 0]]
}
method print {{percolated ""}} {
set nw [string length $M]
set grid $cells
if {$percolated ne ""} {
lappend grid [lrepeat $N 0]
lset grid end $percolated 1
}
foreach hws $hwall vws [lrange $vwall 0 end-1] r $grid {
incr row
puts -nonewline [string repeat " " [expr {$nw+2}]]
foreach w $hws {
puts -nonewline [if {$w} {subst "+-"} {subst "+ "}]
}
puts "+"
puts -nonewline [format "%-*s" [expr {$nw+2}] [expr {
$row>$M ? $percolated eq "" ? " " : ">" : "$row)"
}]]
foreach v $vws c $r {
puts -nonewline [if {$v==1} {subst "|"} {subst " "}]
puts -nonewline [if {$c==1} {subst "#"} {subst " "}]
}
puts ""
}
}
method percolate {} {
try {
for {set i 0} {$i < $N} {incr i} {
if {![lindex $hwall 0 $i]} {
my FloodFill $i 0
}
}
return ""
} trap PERCOLATED n {
return $n
}
}
method FloodFill {x y} {
# fill cell
lset cells $y $x 1
# bottom
if {![lindex $hwall [expr {$y+1}] $x]} {
if {$y == $N-1} {
# THE bottom
throw PERCOLATED $x
}
if {$y < $N-1 && ![lindex $cells [expr {$y+1}] $x]} {
my FloodFill $x [expr {$y+1}]
}
}
# left
if {![lindex $vwall $y $x] && ![lindex $cells $y [expr {$x-1}]]} {
my FloodFill [expr {$x-1}] $y
}
# right
if {![lindex $vwall $y [expr {$x+1}]] && ![lindex $cells $y [expr {$x+1}]]} {
my FloodFill [expr {$x+1}] $y
}
# top
if {$y>0 && ![lindex $hwall $y $x] && ![lindex $cells [expr {$y-1}] $x]} {
my FloodFill $x [expr {$y-1}]
}
}
}
# Demonstrate one run
puts "Sample percolation, 10x10 p=0.5"
BondPercolation create bp 10 10 0.5
bp print [bp percolate]
bp destroy
puts ""
# Collect some aggregate statistics
apply {{} {
puts "Percentage of tries that percolate, varying p"
set tries 100
for {set pint 0} {$pint <= 10} {incr pint} {
set p [expr {$pint * 0.1}]
set tot 0
for {set i 0} {$i < $tries} {incr i} {
set bp [BondPercolation new 10 10 $p]
if {[$bp percolate] ne ""} {
incr tot
}
$bp destroy
}
puts [format "p=%.2f: %2.1f%%" $p [expr {$tot*100./$tries}]]
}
}} |
http://rosettacode.org/wiki/Percolation/Mean_run_density | Percolation/Mean run density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
v
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #Perl | Perl | sub R {
my ($n, $p) = @_;
my $r = join '',
map { rand() < $p ? 1 : 0 } 1 .. $n;
0+ $r =~ s/1+//g;
}
use constant t => 100;
printf "t= %d\n", t;
for my $p (qw(.1 .3 .5 .7 .9)) {
printf "p= %f, K(p)= %f\n", $p, $p*(1-$p);
for my $n (qw(10 100 1000)) {
my $r; $r += R($n, $p) for 1 .. t; $r /= $n;
printf " R(n, p)= %f\n", $r / t;
}
} |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards.
Assume that the probability of any cell being filled is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
The task
Simulate creating the array of cells with probability
p
{\displaystyle p}
and then
testing if there is a route through adjacent filled cells from any on row
0
{\displaystyle 0}
to any on row
N
{\displaystyle N}
, i.e. testing for site percolation.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
>=
100
{\displaystyle t>=100}
.
Use an
M
=
15
,
N
=
15
{\displaystyle M=15,N=15}
grid of cells for all cases.
Optionally depict a percolation through a cell grid graphically.
Show all output on this page.
| #Tcl | Tcl | package require Tcl 8.6
oo::class create SitePercolation {
variable cells w h
constructor {width height probability} {
set w $width
set h $height
for {set cells {}} {[llength $cells] < $h} {lappend cells $row} {
for {set row {}} {[llength $row] < $w} {lappend row $cell} {
set cell [expr {rand() < $probability}]
}
}
}
method print {out} {
array set map {0 "#" 1 " " -1 .}
puts "+[string repeat . $w]+"
foreach row $cells {
set s "|"
foreach cell $row {
append s $map($cell)
}
puts [append s "|"]
}
set outline [lrepeat $w "-"]
foreach index $out {
lset outline $index "."
}
puts "+[join $outline {}]+"
}
method percolate {} {
for {set work {}; set i 0} {$i < $w} {incr i} {
if {[lindex $cells 0 $i]} {lappend work 0 $i}
}
try {
my Fill $work
return {}
} trap PERCOLATED x {
return [list $x]
}
}
method Fill {queue} {
while {[llength $queue]} {
set queue [lassign $queue y x]
if {$y >= $h} {throw PERCOLATED $x}
if {$y < 0 || $x < 0 || $x >= $w} continue
if {[lindex $cells $y $x]<1} continue
lset cells $y $x -1
lappend queue [expr {$y+1}] $x [expr {$y-1}] $x
lappend queue $y [expr {$x-1}] $y [expr {$x+1}]
}
}
}
# Demonstrate one run
puts "Sample percolation, 15x15 p=0.6"
SitePercolation create bp 15 15 0.6
bp print [bp percolate]
bp destroy
puts ""
# Collect statistics
apply {{} {
puts "Percentage of tries that percolate, varying p"
set tries 100
for {set pint 0} {$pint <= 10} {incr pint} {
set p [expr {$pint * 0.1}]
set tot 0
for {set i 0} {$i < $tries} {incr i} {
set bp [SitePercolation new 15 15 $p]
if {[$bp percolate] ne ""} {
incr tot
}
$bp destroy
}
puts [format "p=%.2f: %2.1f%%" $p [expr {$tot*100./$tries}]]
}
}} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AutoHotkey | AutoHotkey | #NoEnv
StringCaseSense On
o := str := "Hello"
Loop
{
str := perm_next(str)
If !str
{
MsgBox % clipboard := o
break
}
o.= "`n" . str
}
perm_Next(str){
p := 0, sLen := StrLen(str)
Loop % sLen
{
If A_Index=1
continue
t := SubStr(str, sLen+1-A_Index, 1)
n := SubStr(str, sLen+2-A_Index, 1)
If ( t < n )
{
p := sLen+1-A_Index, pC := SubStr(str, p, 1)
break
}
}
If !p
return false
Loop
{
t := SubStr(str, sLen+1-A_Index, 1)
If ( t > pC )
{
n := sLen+1-A_Index, nC := SubStr(str, n, 1)
break
}
}
return SubStr(str, 1, p-1) . nC . Reverse(SubStr(str, p+1, n-p-1) . pC . SubStr(str, n+1))
}
Reverse(s){
Loop Parse, s
o := A_LoopField o
return o
} |
http://rosettacode.org/wiki/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #FreeBASIC | FreeBASIC | function is_in_order( d() as uinteger ) as boolean
'tests if a deck is in order
for i as uinteger = lbound(d) to ubound(d)-1
if d(i) > d(i+1) then return false
next i
return true
end function
sub init_deck( d() as uinteger )
for i as uinteger = 1 to ubound(d)
d(i) = i
next i
return
end sub
sub shuffle( d() as uinteger )
'does a faro shuffle of the deck
dim as integer n = ubound(d), i
dim as integer b( 1 to n )
for i = 1 to n/2
b(2*i-1) = d(i)
b(2*i) = d(n/2+i)
next i
for i = 1 to n
d(i) = b(i)
next i
return
end sub
function shufs_needed( size as integer ) as uinteger
dim as uinteger d(1 to size), s = 0
init_deck(d())
do
shuffle(d())
s+=1
if is_in_order(d()) then exit do
loop
return s
end function
dim as uinteger tests(1 to 7) = {8, 24, 52, 100, 1020, 1024, 10000}, i
for i = 1 to 7
print tests(i);" cards require "; shufs_needed(tests(i)); " shuffles."
next i |
http://rosettacode.org/wiki/Perlin_noise | Perlin noise | The Perlin noise is a kind of gradient noise invented by Ken Perlin around the end of the twentieth century and still currently heavily used in computer graphics, most notably to procedurally generate textures or heightmaps.
The Perlin noise is basically a pseudo-random mapping of
R
d
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #Pascal | Pascal | program perlinNoise;
//Perlin Noise
//http://rosettacode.org/mw/index.php?title=Perlin_noise#Go
uses
sysutils;
type
float64 = double;
const
p{ermutation} : array[0..255] of byte = (
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180);
function fade(t:float64):float64;inline;
begin
fade := ((t*6-15)*t + 10) * t*t*t;
end;
function lerp(t, a, b:float64):float64;inline;
Begin
lerp := t*(b-a)+a;
end;
function grad(hash:integer; x, y, z: float64):float64;
Begin
case (hash AND 15) of
0:
grad := x + y;
1:
grad := y - x;
2:
grad := x - y;
3:
grad := -x - y;
4:
grad := x + z;
5:
grad := z - x;
6:
grad := x - z;
7:
grad := -x - z;
8:
grad := y + z;
9:
grad := z - y;
10:
grad := y - z;
11:
grad := -y - z;
12:
grad := x + y;
13:
grad := z - y;
14:
grad := y - x;
15:
grad := -y - z;
end;
end;
function noise(x, y, z: float64):float64;
var
u,v,w : float64;
a,b,c,A0,A1,A2,B0,B1,B2 : Integer;
Begin
a := trunc(x) AND 255;
b := trunc(y) AND 255;
c := trunc(z) AND 255;
x := frac(x);
y := frac(y);
z := frac(z);
u := fade(x);
v := fade(y);
w := fade(z);
A0 := p[ a] + b;
A1 := p[A0] + c;
A2 := p[A0+1] + c;
B0 := p[ a+1] + b;
B1 := p[B0] + c;
B2 := p[B0+1] + c;
noise:= lerp(w, lerp(v, lerp(u, grad(p[A1], x, y, z),
grad(p[B1], x-1, y, z)),
lerp(u, grad(p[A2], x, y-1, z),
grad(p[B2], x-1, y-1, z))),
lerp(v, lerp(u, grad(p[A1+1], x, y, z-1),
grad(p[B1+1], x-1, y, z-1)),
lerp(u, grad(p[A2+1], x, y-1, z-1),
grad(p[B2+1], x-1, y-1, z-1))))
end;
Begin
writeln(noise(3.14, 42, 7):20:17);
end.
|
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #Nim | Nim | import strformat
func totient(n: int): int =
var tot = n
var nn = n
var i = 2
while i * i <= nn:
if nn mod i == 0:
while nn mod i == 0:
nn = nn div i
dec tot, tot div i
if i == 2:
i = 1
inc i, 2
if nn > 1:
dec tot, tot div nn
tot
var n = 1
var num = 0
echo "The first 20 perfect totient numbers are:"
while num < 20:
var tot = n
var sum = 0
while tot != 1:
tot = totient(tot)
inc sum, tot
if sum == n:
write(stdout, fmt"{n} ")
inc num
inc n, 2
write(stdout, "\n") |
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #Pascal | Pascal | program Perftotient;
{$IFdef FPC}
{$MODE DELPHI} {$CodeAlign proc=32,loop=1}
{$IFEND}
uses
sysutils;
const
cLimit = 57395631;//177147;//4190263;//57395631;//1162261467;//
//global
var
TotientList : array of LongWord;
Sieve : Array of byte;
SolList : array of LongWord;
T1,T0 : INt64;
procedure SieveInit(svLimit:NativeUint);
var
pSieve:pByte;
i,j,pr :NativeUint;
Begin
svlimit := (svLimit+1) DIV 2;
setlength(sieve,svlimit+1);
pSieve := @Sieve[0];
For i := 1 to svlimit do
Begin
IF pSieve[i]= 0 then
Begin
pr := 2*i+1;
j := (sqr(pr)-1) DIV 2;
IF j> svlimit then
BREAK;
repeat
pSieve[j]:= 1;
inc(j,pr);
until j> svlimit;
end;
end;
pr := 0;
j := 0;
For i := 1 to svlimit do
Begin
IF pSieve[i]= 0 then
Begin
pSieve[j] := i-pr;
inc(j);
pr := i;
end;
end;
setlength(sieve,j);
end;
procedure TotientInit(len: NativeUint);
var
pTotLst : pLongWord;
pSieve : pByte;
test : double;
i: NativeInt;
p,j,k,svLimit : NativeUint;
Begin
SieveInit(len);
T0:= GetTickCount64;
setlength(TotientList,len+12);
pTotLst := @TotientList[0];
//Fill totient with simple start values for odd and even numbers
//and multiples of 3
j := 1;
k := 1;// k == j DIV 2
p := 1;// p == j div 3;
repeat
pTotLst[j] := j;//1
pTotLst[j+1] := k;//2 j DIV 2; //2
inc(k);
inc(j,2);
pTotLst[j] := j-p;//3
inc(p);
pTotLst[j+1] := k;//4 j div 2
inc(k);
inc(j,2);
pTotLst[j] := j;//5
pTotLst[j+1] := p;//6 j DIV 3 <= (div 2) * 2 DIV/3
inc(j,2);
inc(p);
inc(k);
until j>len+6;
//correct values of totient by prime factors
svLimit := High(sieve);
p := 3;// starting after 3
pSieve := @Sieve[svLimit+1];
i := -svlimit;
repeat
p := p+2*pSieve[i];
j := p;
// Test := (1-1/p);
while j <= cLimit do
Begin
// pTotLst[j] := trunc(pTotLst[j]*Test);
k:= pTotLst[j];
pTotLst[j]:= k-(k DIV p);
inc(j,p);
end;
inc(i);
until i=0;
T1:= GetTickCount64;
writeln('totient calculated in ',T1-T0,' ms');
setlength(sieve,0);
end;
function GetPerfectTotient(len: NativeUint):NativeUint;
var
pTotLst : pLongWord;
i,sum: NativeUint;
Begin
T0:= GetTickCount64;
pTotLst := @TotientList[0];
setlength(SolList,100);
result := 0;
For i := 3 to Len do
Begin
sum := pTotLst[i];
pTotLst[i] := sum+pTotLst[sum];
end;
//Check for solution ( IF ) in seperate loop ,reduces time consuption ~ 12% for this function
For i := 3 to Len do
IF pTotLst[i] =i then
Begin
SolList[result] := i;
inc(result);
end;
T1:= GetTickCount64;
setlength(SolList,result);
writeln('calculated totientsum in ',T1-T0,' ms');
writeln('found ',result,' perfect totient numbers');
end;
var
j,k : NativeUint;
Begin
TotientInit(climit);
GetPerfectTotient(climit);
k := 0;
For j := 0 to High(Sollist) do
Begin
inc(k);
if k > 4 then
Begin
writeln(Sollist[j]);
k := 0;
end
else
write(Sollist[j],',');
end;
end. |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Hy | Hy | (import [random [shuffle]])
(setv pips (.split "2 3 4 5 6 7 8 9 10 J Q K A"))
(setv suits (.split "♥ ♦ ♣ ♠"))
(setv cards_per_hand 5)
(defn make_deck [pips suits]
(lfor
x pips
y suits
(+ x y)))
(defn deal_hand [num_cards deck]
(setv delt (cut deck None num_cards))
(setv new_deck (lfor
x deck
:if (not (in x delt))
x))
[delt new_deck])
(if (= __name__ "__main__")
(do
(setv deck (make_deck pips suits))
(shuffle deck)
(setv [first_hand deck] (deal_hand cards_per_hand deck))
(setv [second_hand deck] (deal_hand cards_per_hand deck))
(print "\nThe first hand delt was:" (.join " " (map str first_hand)))
(print "\nThe second hand delt was:" (.join " " (map str second_hand)))
(print "\nThe remaining cards in the deck are...\n" (.join " " (map str deck))))) |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Go | Go | package main
import (
"fmt"
"math/big"
)
type lft struct {
q,r,s,t big.Int
}
func (t *lft) extr(x *big.Int) *big.Rat {
var n, d big.Int
var r big.Rat
return r.SetFrac(
n.Add(n.Mul(&t.q, x), &t.r),
d.Add(d.Mul(&t.s, x), &t.t))
}
var three = big.NewInt(3)
var four = big.NewInt(4)
func (t *lft) next() *big.Int {
r := t.extr(three)
var f big.Int
return f.Div(r.Num(), r.Denom())
}
func (t *lft) safe(n *big.Int) bool {
r := t.extr(four)
var f big.Int
if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {
return true
}
return false
}
func (t *lft) comp(u *lft) *lft {
var r lft
var a, b big.Int
r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))
r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))
r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))
r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))
return &r
}
func (t *lft) prod(n *big.Int) *lft {
var r lft
r.q.SetInt64(10)
r.r.Mul(r.r.SetInt64(-10), n)
r.t.SetInt64(1)
return r.comp(t)
}
func main() {
// init z to unit
z := new(lft)
z.q.SetInt64(1)
z.t.SetInt64(1)
// lfts generator
var k int64
lfts := func() *lft {
k++
r := new(lft)
r.q.SetInt64(k)
r.r.SetInt64(4*k+2)
r.t.SetInt64(2*k+1)
return r
}
// stream
for {
y := z.next()
if z.safe(y) {
fmt.Print(y)
z = z.prod(y)
} else {
z = z.comp(lfts())
}
}
} |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Perl | Perl | #!perl
use strict;
use warnings;
my @players = @ARGV;
@players = qw(Joe Mike);
my @scores = (0) x @players;
while( 1 ) {
PLAYER: for my $i ( 0 .. $#players ) {
my $name = $players[$i];
my $score = $scores[$i];
my $roundscore = 1 + int rand 6;
print "$name, your score so far is $score.\n";
print "You rolled a $roundscore.\n";
next PLAYER if $roundscore == 1;
while($score + $roundscore < 100) {
print "Roll again, or hold [r/h]: ";
my $answer = <>;
$answer = 'h' unless defined $answer;
if( $answer =~ /^h/i ) {
$score += $roundscore;
$scores[$i] = $score;
print "Your score is now $score.\n";
next PLAYER;
} elsif( $answer =~ /^r/ ) {
my $die = 1 + int rand 6;
print "$name, you rolled a $die.\n";
next PLAYER if $die == 1;
$roundscore += $die;
print "Your score for the round is now $roundscore.\n";
} else {
print "I did not understand that.\n";
}
}
$score += $roundscore;
print "With that, your score became $score.\n";
print "You won!\n";
exit;
}
}
__END__
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Icon_and_Unicon | Icon and Unicon | link "factors"
procedure main(A)
every writes((pernicious(seq())\25||" ") | "\n")
every writes((pernicious(888888877 to 888888888)||" ") | "\n")
end
procedure pernicious(n)
return (isprime(c1bits(n)),n)
end
procedure c1bits(n)
c := 0
while n > 0 do c +:= 1(n%2, n/:=2)
return c
end |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | RandomChoice[{a, b, c}] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #MATLAB_.2F_Octave | MATLAB / Octave | list = {'a','b','c'};
list{ceil(rand(1)*length(list))} |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MATLAB_.2F_Octave | MATLAB / Octave |
function r=revstr(s,d)
slist=strsplit(s,d);
for k=1:length(slist)
rlist{k}=slist{k}(end:-1:1);
end;
fprintf(1,'%s\n',s)
fprintf(1,'%s %c',slist{end:-1:1},d)
fprintf(1,'\n');
fprintf(1,'%s %c',rlist{:},d)
fprintf(1,'\n');
fprintf(1,'%s\n',s(end:-1:1))
end
revstr('Rosetta Code Phrase Reversal', ' ')
|
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MiniScript | MiniScript | phrase = "rosetta code phrase reversal"
// general sequence reversal function
reverse = function(seq)
out = []
for i in range(seq.len-1, 0)
out.push seq[i]
end for
if seq isa string then return out.join("")
return out
end function
// 1. Reverse the characters of the string.
print reverse(phrase)
// 2. Reverse the characters of each individual word in the string, maintaining original word order within the string.
words = phrase.split
for i in words.indexes
words[i] = reverse(words[i])
end for
print words.join
// 3. Reverse the order of each word of the string, maintaining the order of characters in each word.
print reverse(phrase.split).join
|
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | // version 1.1.2
fun <T> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<T>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
fun derange(input: List<Int>): List<List<Int>> {
if (input.isEmpty()) return listOf(input)
return permute(input).filter { permutation ->
permutation.filterIndexed { i, index -> i == index }.none()
}
}
fun subFactorial(n: Int): Long =
when (n) {
0 -> 1
1 -> 0
else -> (n - 1) * (subFactorial(n - 1) + subFactorial(n - 2))
}
fun main(args: Array<String>) {
val input = listOf(0, 1, 2, 3)
val derangements = derange(input)
println("There are ${derangements.size} derangements of $input, namely:\n")
derangements.forEach(::println)
println("\nN Counted Calculated")
println("- ------- ----------")
for (n in 0..9) {
val list = List(n) { it }
val counted = derange(list).size
println("%d %-9d %-9d".format(n, counted, subFactorial(n)))
}
println("\n!20 = ${subFactorial(20)}")
} |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #Phix | Phix | function spermutations(integer p, integer i)
--
-- generate the i'th permutation of [1..p]:
-- first obtain the appropriate permutation of [1..p-1],
-- then insert p/move it down k(=0..p-1) places from the end.
--
sequence res
integer k = mod(i-1,2*p)
if k>=p then k=2*p-1-k end if
if p>1 then
res = spermutations(p-1,floor((i-1)/p)+1)
res = res[1..length(res)-k]&p&res[length(res)-k+1..$]
else
res = {1}
end if
return res
end function
for p=1 to 4 do
printf(1,"==%d==\n",p)
for i=1 to factorial(p) do
integer parity = iff(and_bits(i,1)?1:-1)
?{i,spermutations(p,i),parity}
end for
end for
|
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Rust | Rust |
fn main() {
let treatment = vec![85, 88, 75, 66, 25, 29, 83, 39, 97];
let control = vec![68, 41, 10, 49, 16, 65, 32, 92, 28, 98];
let mut data_set = control.clone();
data_set.extend_from_slice(&treatment);
let greater = combinations(treatment.iter().sum(), treatment.len() as i64, &data_set) as f64;
let lesser = combinations(control.iter().sum(), control.len() as i64, &data_set) as f64;
let total = binomial(data_set.len() as i64, treatment.len() as i64) as f64;
println!("<= : {}%", (lesser / total * 100.0));
println!(" > : {}%", (greater / total * 100.0));
}
fn factorial(x: i64) -> i64 {
let mut product = 1;
for a in 1..(x + 1) {
product *= a;
}
product
}
fn binomial(n: i64, k: i64) -> i64 {
let numerator = factorial(n);
let denominator = factorial(k) * factorial(n - k);
numerator / denominator
}
fn combinations(total: i64, number: i64, data: &[i64]) -> i64 {
if total < 0 {
return binomial(data.len() as i64, number);
}
if number == 0 {
return 0;
}
if number > data.len() as i64 {
return 0;
}
if number == data.len() as i64 {
if total < data.iter().sum() {
return 1;
} else {
return 0;
}
}
let tail = &data[1..];
combinations(total - data[0], number - 1, &tail) + combinations(total, number, &tail)
}
|
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Scala | Scala | object PermutationTest extends App {
private val data =
Array(85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98)
private var (total, treat) = (1.0, 0)
private def pick(at: Int, remain: Int, accu: Int, treat: Int): Int = {
if (remain == 0) return if (accu > treat) 1 else 0
pick(at - 1, remain - 1, accu + data(at - 1), treat) +
(if (at > remain) pick(at - 1, remain, accu, treat) else 0)
}
for (i <- 0 to 8) treat += data(i)
for (j <- 19 to 11 by -1) total *= j
for (g <- 9 to 1 by -1) total /= g
private val gt = pick(19, 9, 0, treat)
private val le = (total - gt).toInt
println(f"<= : ${100.0 * le / total}%f%% ${le}%d")
println(f" > : ${100.0 * gt / total}%f%% ${gt}%d")
} |
http://rosettacode.org/wiki/Percentage_difference_between_images | Percentage difference between images | basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The expected difference for these two images is 1.62125%
| #Icon_and_Unicon | Icon and Unicon | link printf # for main only
procedure main() # % difference between images
fn1 := "Lenna100.jpg"
fn2 := "Lenna50.jpg"
printf("%%difference of files %i & %i = %r\n",fn1,fn2,ImageDiff(fn1,fn2))
end
procedure ImageDiff(fn1,fn2) #: return % difference of two images
img1 := open(1,"g","canvas=hidden","image="||fn1) | stop("Open failed ",fn1)
img2 := open(2,"g","canvas=hidden","image="||fn2) | stop("Open failed ",fn2)
if WAttrib(img1,"width") ~= WAttrib(img2,"width") |
WAttrib(img1,"height") ~= WAttrib(img2,"height") then
stop("Images must be the same size")
pix1 := create Pixel(img1) # access pixels one at a time
pix2 := create Pixel(img2) # ... facilitate interleaved access
sum := pix := 0
while pix +:= 1 & p1 := csv2l(@pix1) & p2 := csv2l(@pix2) do
every sum +:= abs(p1[i := 1 to *p1] - p2[i])
every close(img1|img2)
return sum / (pix * 3 * 65535 / 100. )
end
procedure csv2l(p) #: return a list from a comma separated string
L := []
p ? until pos(0) do {
put(L,tab(find(",")|0))
move(1)
}
return L
end |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I
I L N Y
FF I L NN PP TTT V W X YY ZZ
FF I L N PP T U U V WW XXX Y Z
F I LL N P T UUU VVV WW X Y ZZ
A Pentomino tiling is an example of an exact cover problem and can take on many forms.
A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered
by the 12 pentomino shapes, without overlaps, with every shape only used once.
The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.
Task
Create an 8 by 8 tiling and print the result.
Example
F I I I I I L N
F F F L L L L N
W F - X Z Z N N
W W X X X Z N V
T W W X - Z Z V
T T T P P V V V
T Y - P P U U U
Y Y Y Y P U - U
Related tasks
Free polyominoes enumeration
| #Raku | Raku | # 20201028 Raku programming solution
my \F = [ <1 -1 1 0 1 1 2 1>, <0 1 1 -1 1 0 2 0>, <1 0 1 1 1 2 2 1>,
<1 0 1 1 2 -1 2 0>, <1 -2 1 -1 1 0 2 -1>, <0 1 1 1 1 2 2 1>,
<1 -1 1 0 1 1 2 -1>, <1 -1 1 0 2 0 2 1> ];
my \I = [ <0 1 0 2 0 3 0 4>, <1 0 2 0 3 0 4 0> ];
my \L = [ <1 0 1 1 1 2 1 3>, <1 0 2 0 3 0 3 1>, <0 1 0 2 0 3 1 3>,
<0 1 1 0 2 0 3 0>, <0 1 1 1 2 1 3 1>, <0 1 0 2 0 3 1 0>,
<1 0 2 0 3 -1 3 0>, <1 -3 1 -2 1 -1 1 0> ];
my \N = [ <0 1 1 -2 1 -1 1 0>, <1 0 1 1 2 1 3 1>, <0 1 0 2 1 -1 1 0>,
<1 0 2 0 2 1 3 1>, <0 1 1 1 1 2 1 3>, <1 0 2 -1 2 0 3 -1>,
<0 1 0 2 1 2 1 3>, <1 -1 1 0 2 -1 3 -1> ];
my \P = [ <0 1 1 0 1 1 2 1>, <0 1 0 2 1 0 1 1>, <1 0 1 1 2 0 2 1>,
<0 1 1 -1 1 0 1 1>, <0 1 1 0 1 1 1 2>, <1 -1 1 0 2 -1 2 0>,
<0 1 0 2 1 1 1 2>, <0 1 1 0 1 1 2 0> ];
my \T = [ <0 1 0 2 1 1 2 1>, <1 -2 1 -1 1 0 2 0>,
<1 0 2 -1 2 0 2 1>, <1 0 1 1 1 2 2 0> ];
my \U = [ <0 1 0 2 1 0 1 2>, <0 1 1 1 2 0 2 1>,
<0 2 1 0 1 1 1 2>, <0 1 1 0 2 0 2 1> ];
my \V = [ <1 0 2 0 2 1 2 2>, <0 1 0 2 1 0 2 0>,
<1 0 2 -2 2 -1 2 0>, <0 1 0 2 1 2 2 2> ];
my \W = [ <1 0 1 1 2 1 2 2>, <1 -1 1 0 2 -2 2 -1>,
<0 1 1 1 1 2 2 2>, <0 1 1 -1 1 0 2 -1> ];
my \X = [ <1 -1 1 0 1 1 2 0> , ]; # self-ref: reddit.com/r/rakulang/comments/jpys5p/gbi71jt/
my \Y = [ <1 -2 1 -1 1 0 1 1>, <1 -1 1 0 2 0 3 0>, <0 1 0 2 0 3 1 1>,
<1 0 2 0 2 1 3 0>, <0 1 0 2 0 3 1 2>, <1 0 1 1 2 0 3 0>,
<1 -1 1 0 1 1 1 2>, <1 0 2 -1 2 0 3 0> ];
my \Z = [ <0 1 1 0 2 -1 2 0>, <1 0 1 1 1 2 2 2>,
<0 1 1 1 2 1 2 2>, <1 -2 1 -1 1 0 2 -2> ];
our @shapes = F, I, L, N, P, T, U, V, W, X, Y, Z ;
my @symbols = "FILNPTUVWXYZ-".comb;
my %symbols = @symbols.pairs;
my $nRows = my $nCols = 8; my $blank = 12;
my @grid = [ [-1 xx $nCols ] xx $nRows ];
my @placed;
sub shuffleShapes {
my @rand = (0 ..^+@shapes).pick(*);
for (0 ..^+@shapes) -> \i {
(@shapes[i], @shapes[@rand[i]]) = (@shapes[@rand[i]], @shapes[i]);
(@symbols[i], @symbols[@rand[i]]) = (@symbols[@rand[i]], @symbols[i])
}
}
sub solve($pos,$numPlaced) {
return True if $numPlaced == +@shapes;
my \row = $pos div $nCols;
my \col = $pos mod $nCols;
return solve($pos + 1, $numPlaced) if @grid[row;col] != -1;
for ^+@shapes -> \i {
if !@placed[i] {
for @shapes[i] -> @orientation {
for @orientation -> @o {
next if !tryPlaceOrientation(@o, row, col, i);
@placed[i] = True;
return True if solve($pos + 1, $numPlaced + 1);
removeOrientation(@o, row, col);
@placed[i] = False;
}
}
}
}
return False
}
sub tryPlaceOrientation (@o, $r, $c, $shapeIndex) {
loop (my $i = 0; $i < +@o; $i += 2) {
my \x = $c + @o[$i + 1];
my \y = $r + @o[$i];
return False if
(x < 0 or x ≥ $nCols or y < 0 or y ≥ $nRows or @grid[y;x] != -1)
}
@grid[$r;$c] = $shapeIndex;
loop ($i = 0; $i < +@o; $i += 2) {
@grid[ $r + @o[$i] ; $c + @o[$i + 1] ] = $shapeIndex;
}
return True
}
sub removeOrientation(@o, $r, $c) {
@grid[$r;$c] = -1;
loop (my $i = 0; $i < +@o; $i += 2) {
@grid[ $r + @o[$i] ; $c + @o[$i + 1] ] = -1;
}
}
sub PrintResult {
my $output;
for @grid[*] -> @line {
$output ~= "%symbols{$_} " for @line;
$output ~= "\n"
}
if my \Embedded_Marketing_Mode = True {
$output .= subst('-', $_.chr) for < 0x24c7 0x24b6 0x24c0 0x24ca >
}
say $output
}
#shuffleShapes(); # xkcd.com/221
for ^4 {
loop {
if @grid[my \R = (^$nRows).roll;my \C = (^$nCols).roll] != $blank
{ @grid[R;C] = $blank and last }
}
}
PrintResult() if solve 0,0 |
http://rosettacode.org/wiki/Percolation/Mean_cluster_density | Percolation/Mean cluster density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
c
{\displaystyle c}
be a 2D boolean square matrix of
n
×
n
{\displaystyle n\times n}
values of either 1 or 0 where the
probability of any value being 1 is
p
{\displaystyle p}
, (and of 0 is therefore
1
−
p
{\displaystyle 1-p}
).
We define a cluster of 1's as being a group of 1's connected vertically or
horizontally (i.e., using the Von Neumann neighborhood rule) and bounded by either
0
{\displaystyle 0}
or by the limits of the matrix.
Let the number of such clusters in such a randomly constructed matrix be
C
n
{\displaystyle C_{n}}
.
Percolation theory states that
K
(
p
)
{\displaystyle K(p)}
(the mean cluster density) will satisfy
K
(
p
)
=
C
n
/
n
2
{\displaystyle K(p)=C_{n}/n^{2}}
as
n
{\displaystyle n}
tends to infinity. For
p
=
0.5
{\displaystyle p=0.5}
,
K
(
p
)
{\displaystyle K(p)}
is found numerically to approximate
0.065770
{\displaystyle 0.065770}
...
Task
Show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
for
p
=
0.5
{\displaystyle p=0.5}
and
for values of
n
{\displaystyle n}
up to at least
1000
{\displaystyle 1000}
.
Any calculation of
C
n
{\displaystyle C_{n}}
for finite
n
{\displaystyle n}
is subject to randomness, so an approximation should be
computed as the average of
t
{\displaystyle t}
runs, where
t
{\displaystyle t}
≥
5
{\displaystyle 5}
.
For extra credit, graphically show clusters in a
15
×
15
{\displaystyle 15\times 15}
,
p
=
0.5
{\displaystyle p=0.5}
grid.
Show your output here.
See also
s-Cluster on Wolfram mathworld. | #zkl | zkl | const X=-1; // the sentinal that marks an untouched cell
var C,N,NN,P;
fcn createC(n,p){
N,P=n,p; NN=N*N;
C=NN.pump(List.createLong(NN),0); // vector of ints
foreach n in (NN){ C[n]=X*(Float.random(1)<=P) } // X is the sentinal
}
fcn showCluster{
alpha:="-ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
foreach n in ([0..NN,N]){ C[n,N].pump(String,alpha.get).println() }
}
fcn countClusters{
clusters:=0;
foreach n in (NN){
if(X!=C[n]) continue;
fcn(n,v){
if((0<=n<NN) and C[n]==X){
C[n]=v;
self.fcn(n-N,v); self.fcn(n-1,v); self.fcn(n+1,v); self.fcn(n+N,v);
}
}(n,clusters+=1);
}
clusters
}
fcn tests(N,n,p){
k:=0.0;
foreach z in (n){ createC(N,p); k+=countClusters().toFloat()/NN; }
k/n
} |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #BASIC | BASIC | FUNCTION perf(n)
sum = 0
FOR i = 1 TO n - 1
IF n MOD i = 0 THEN
sum = sum + i
END IF
NEXT i
IF sum = n THEN
perf = 1
ELSE
perf = 0
END IF
END FUNCTION |
http://rosettacode.org/wiki/Percolation/Bond_percolation | Percolation/Bond percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
, assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards. Each
c
e
l
l
[
m
,
n
]
{\displaystyle \mathrm {cell} [m,n]}
is bounded by (horizontal) walls
h
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {hwall} [m,n]}
and
h
w
a
l
l
[
m
+
1
,
n
]
{\displaystyle \mathrm {hwall} [m+1,n]}
; (vertical) walls
v
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {vwall} [m,n]}
and
v
w
a
l
l
[
m
,
n
+
1
]
{\displaystyle \mathrm {vwall} [m,n+1]}
Assume that the probability of any wall being present is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
Except for the outer horizontal walls at
m
=
0
{\displaystyle m=0}
and
m
=
M
{\displaystyle m=M}
which are always present.
The task
Simulate pouring a fluid onto the top surface (
n
=
0
{\displaystyle n=0}
) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall.
The fluid does not move beyond the horizontal constraints of the grid.
The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
=
100
{\displaystyle t=100}
.
Use an
M
=
10
,
N
=
10
{\displaystyle M=10,N=10}
grid of cells for all cases.
Optionally depict fluid successfully percolating through a grid graphically.
Show all output on this page.
| #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var RAND_MAX = 32767
// cell states
var FILL = 1
var RWALL = 2 // right wall
var BWALL = 4 // bottom wall
var x = 10
var y = 10
var grid = List.filled(x * (y + 2), 0)
var cells = 0
var end = 0
var m = 0
var n = 0
var makeGrid = Fn.new { |p|
var thresh = (p * RAND_MAX).truncate
m = x
n = y
for (i in 0...grid.count) grid[i] = 0 // clears grid
for (i in 0...m) grid[i] = BWALL | RWALL
cells = m
end = m
for (i in 0...y) {
for (j in x - 1..1) {
var r1 = rand.int(RAND_MAX + 1)
var r2 = rand.int(RAND_MAX + 1)
grid[end] = ((r1 < thresh) ? BWALL : 0) |
((r2 < thresh) ? RWALL : 0)
end = end + 1
}
var r3 = rand.int(RAND_MAX + 1)
grid[end] = RWALL | ((r3 < thresh) ? BWALL : 0)
end = end + 1
}
}
var showGrid = Fn.new {
for (j in 0...m) System.write("+--")
System.print("+")
for (i in 0..n) {
System.write((i == n) ? " " : "|")
for (j in 0...m) {
System.write(((grid[i * m + j + cells] & FILL) != 0) ? "[]" : " ")
System.write(((grid[i * m + j + cells] & RWALL) != 0) ? "|" : " ")
}
System.print()
if (i == n) return
for (j in 0...m) {
System.write(((grid[i * m + j + cells] & BWALL) != 0) ? "+--" : "+ ")
}
System.print("+")
}
}
var fill // recursive
fill = Fn.new { |p|
if ((grid[p] & FILL) != 0) return false
grid[p] = grid[p] | FILL
if (p >= end) return true // success: reached bottom row
return (((grid[p + 0] & BWALL) == 0) && fill.call(p + m)) ||
(((grid[p + 0] & RWALL) == 0) && fill.call(p + 1)) ||
(((grid[p - 1] & RWALL) == 0) && fill.call(p - 1)) ||
(((grid[p - m] & BWALL) == 0) && fill.call(p - m))
}
var percolate = Fn.new {
var i = 0
while (i < m && !fill.call(cells + i)) i = i + 1
return i < m
}
makeGrid.call(0.5)
percolate.call()
showGrid.call()
System.print("\nRunning %(x) x %(y) grids 10,000 times for each p:")
for (p in 1..9) {
var cnt = 0
var pp = p / 10
for (i in 0...10000) {
makeGrid.call(pp)
if (percolate.call()) cnt = cnt + 1
}
Fmt.print("p = $3g: $.4f", pp, cnt / 10000)
} |
http://rosettacode.org/wiki/Percolation/Mean_run_density | Percolation/Mean run density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
v
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #Phix | Phix | with javascript_semantics
function run_test(atom p, integer len, runs)
integer count = 0
for r=1 to runs do
bool v, pv = false
for l=1 to len do
v = rnd()<p
count += pv<v
pv = v
end for
end for
return count/runs/len
end function
procedure main()
printf(1,"Running 1000 tests each:\n")
printf(1," p n K p(1-p) delta\n")
printf(1,"--------------------------------------------\n")
for ip=1 to 10 by 2 do
atom p = ip/10,
p1p = p*(1-p)
integer n = 100
while n<=100000 do
atom K = run_test(p, n, 1000)
printf(1,"%.1f %6d %6.4f %6.4f %+7.4f (%+5.2f%%)\n",
{p, n, K, p1p, K-p1p, (K-p1p)/p1p*100})
n *= 10
end while
printf(1,"\n")
end for
end procedure
main()
|
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards.
Assume that the probability of any cell being filled is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
The task
Simulate creating the array of cells with probability
p
{\displaystyle p}
and then
testing if there is a route through adjacent filled cells from any on row
0
{\displaystyle 0}
to any on row
N
{\displaystyle N}
, i.e. testing for site percolation.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
>=
100
{\displaystyle t>=100}
.
Use an
M
=
15
,
N
=
15
{\displaystyle M=15,N=15}
grid of cells for all cases.
Optionally depict a percolation through a cell grid graphically.
Show all output on this page.
| #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var RAND_MAX = 32767
var EMPTY = ""
var x = 15
var y = 15
var grid = List.filled((x + 1) * (y + 1) + 1, EMPTY)
var cell = 0
var end = 0
var m = 0
var n = 0
var makeGrid = Fn.new { |p|
var thresh = (p * RAND_MAX).truncate
m = x
n = y
grid.clear()
grid = List.filled(m + 1, EMPTY)
end = m + 1
cell = m + 1
for (i in 0...n) {
for (j in 0...m) {
var r = rand.int(RAND_MAX+1)
grid.add((r < thresh) ? "+" : ".")
end = end + 1
}
grid.add("\n")
end = end + 1
}
grid[end-1] = EMPTY
m = m + 1
end = end - m // end is the index of the first cell of bottom row
}
var ff // recursive
ff = Fn.new { |p| // flood fill
if (grid[p] != "+") return false
grid[p] = "#"
return p >= end || ff.call(p + m) || ff.call(p + 1) || ff.call(p - 1) ||
ff.call(p - m)
}
var percolate = Fn.new {
var i = 0
while (i < m && !ff.call(cell + i)) i = i + 1
return i < m
}
makeGrid.call(0.5)
percolate.call()
System.print("%(x) x %(y) grid:")
System.print(grid.join(""))
System.print("\nRunning 10,000 tests for each case:")
for (ip in 0..10) {
var p = ip / 10
var cnt = 0
for (i in 0...10000) {
makeGrid.call(p)
if (percolate.call()) cnt = cnt + 1
}
Fmt.print("p = $.1f: $.4f", p, cnt / 10000)
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #AWK | AWK |
# syntax: GAWK -f PERMUTATIONS.AWK [-v sep=x] [word]
#
# examples:
# REM all permutations on one line
# GAWK -f PERMUTATIONS.AWK
#
# REM all permutations on a separate line
# GAWK -f PERMUTATIONS.AWK -v sep="\n"
#
# REM use a different word
# GAWK -f PERMUTATIONS.AWK Gwen
#
# REM command used for RosettaCode output
# GAWK -f PERMUTATIONS.AWK -v sep="\n" Gwen
#
BEGIN {
sep = (sep == "") ? " " : substr(sep,1,1)
str = (ARGC == 1) ? "abc" : ARGV[1]
printf("%s%s",str,sep)
leng = length(str)
for (i=1; i<=leng; i++) {
arr[i-1] = substr(str,i,1)
}
ana_permute(0)
exit(0)
}
function ana_permute(pos, i,j,str) {
if (leng - pos < 2) { return }
for (i=pos; i<leng-1; i++) {
ana_permute(pos+1)
ana_rotate(pos)
for (j=0; j<=leng-1; j++) {
printf("%s",arr[j])
}
printf(sep)
}
ana_permute(pos+1)
ana_rotate(pos)
}
function ana_rotate(pos, c,i) {
c = arr[pos]
for (i=pos; i<leng-1; i++) {
arr[i] = arr[i+1]
}
arr[leng-1] = c
}
|
http://rosettacode.org/wiki/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #Go | Go | package main
import "fmt"
type Deck struct {
Cards []int
length int
}
func NewDeck(deckSize int) (res *Deck){
if deckSize % 2 != 0{
panic("Deck size must be even")
}
res = new(Deck)
res.Cards = make([]int, deckSize)
res.length = deckSize
for i,_ := range res.Cards{
res.Cards[i] = i
}
return
}
func (d *Deck)shuffleDeck(){
tmp := make([]int,d.length)
for i := 0;i <d.length/2;i++ {
tmp[i*2] = d.Cards[i]
tmp[i*2+1] = d.Cards[d.length / 2 + i]
}
d.Cards = tmp
}
func (d *Deck) isEqualTo(c Deck) (res bool) {
if d.length != c.length {
panic("Decks aren't equally sized")
}
res = true
for i, v := range d.Cards{
if v != c.Cards[i] {
res = false
}
}
return
}
func main(){
for _,v := range []int{8,24,52,100,1020,1024,10000} {
fmt.Printf("Cards count: %d, shuffles required: %d\n",v,ShufflesRequired(v))
}
}
func ShufflesRequired(deckSize int)(res int){
deck := NewDeck(deckSize)
Ref := *deck
deck.shuffleDeck()
res++
for ;!deck.isEqualTo(Ref);deck.shuffleDeck(){
res++
}
return
} |
http://rosettacode.org/wiki/Perlin_noise | Perlin noise | The Perlin noise is a kind of gradient noise invented by Ken Perlin around the end of the twentieth century and still currently heavily used in computer graphics, most notably to procedurally generate textures or heightmaps.
The Perlin noise is basically a pseudo-random mapping of
R
d
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #Perl | Perl | use strict;
use warnings;
use experimental 'signatures';
use constant permutation => qw{
151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69
142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252
219 203 117 35 11 32 57 177 33 88 237 149 56 87 174 20 125 136 171 168 68
175 74 165 71 134 139 48 27 166 77 146 158 231 83 111 229 122 60 211 133 230
220 105 92 41 55 46 245 40 244 102 143 54 65 25 63 161 1 216 80 73 209
76 132 187 208 89 18 169 200 196 135 130 116 188 159 86 164 100 109 198 173 186
3 64 52 217 226 250 124 123 5 202 38 147 118 126 255 82 85 212 207 206 59
227 47 16 58 17 182 189 28 42 223 183 170 213 119 248 152 2 44 154 163 70
221 153 101 155 167 43 172 9 129 22 39 253 19 98 108 110 79 113 224 232 178
185 112 104 218 246 97 228 251 34 242 193 238 210 144 12 191 179 162 241 81 51
145 235 249 14 239 107 49 192 214 31 181 199 106 157 184 84 204 176 115 121 50
45 127 4 150 254 138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66
215 61 156 180};
use constant p => permutation, permutation;
sub floor ($x) { my $xi = int($x); return $x < $xi ? $xi - 1 : $xi }
sub fade ($t) { $t**3 * ($t * ($t * 6 - 15) + 10) }
sub lerp ($t, $a, $b) { $a + $t * ($b - $a) }
sub grad ($h, $x, $y, $z) {
$h &= 15;
my $u = $h < 8 ? $x : $y;
my $v = $h < 4 ? $y : ($h == 12 or $h == 14) ? $x : $z;
(($h & 1) == 0 ? $u : -$u) + (($h & 2) == 0 ? $v : -$v);
}
sub noise ($x, $y, $z) {
my ($X, $Y, $Z) = map { 255 & floor $_ } $x, $y, $z;
my ($u, $v, $w) = map { fade $_ } $x -= $X, $y -= $Y, $z -= $Z;
my $A = (p)[$X] + $Y;
my ($AA, $AB) = ( (p)[$A] + $Z, (p)[$A + 1] + $Z );
my $B = (p)[$X + 1] + $Y;
my ($BA, $BB) = ( (p)[$B] + $Z, (p)[$B + 1] + $Z );
lerp($w, lerp($v, lerp($u, grad((p)[$AA ], $x , $y , $z ),
grad((p)[$BA ], $x - 1, $y , $z )),
lerp($u, grad((p)[$AB ], $x , $y - 1, $z ),
grad((p)[$BB ], $x - 1, $y - 1, $z ))),
lerp($v, lerp($u, grad((p)[$AA + 1], $x , $y , $z - 1 ),
grad((p)[$BA + 1], $x - 1, $y , $z - 1 )),
lerp($u, grad((p)[$AB + 1], $x , $y - 1, $z - 1 ),
grad((p)[$BB + 1], $x - 1, $y - 1, $z - 1 ))));
}
print noise 3.14, 42, 7; |
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #Perl | Perl | use ntheory qw(euler_phi);
sub phi_iter {
my($p) = @_;
euler_phi($p) + ($p == 2 ? 0 : phi_iter(euler_phi($p)));
}
my @perfect;
for (my $p = 2; @perfect < 20 ; ++$p) {
push @perfect, $p if $p == phi_iter($p);
}
printf "The first twenty perfect totient numbers:\n%s\n", join ' ', @perfect; |
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #Phix | Phix | with javascript_semantics
function totient(integer n)
integer tot = n, i = 2
while i*i<=n do
if mod(n,i)=0 then
while true do
n /= i
if mod(n,i)!=0 then exit end if
end while
tot -= tot/i
end if
i += iff(i=2?1:2)
end while
if n>1 then
tot -= tot/n
end if
return tot
end function
sequence perfect = {}
integer n = 1
while length(perfect)<20 do
integer tot = n,
tsum = 0
while tot!=1 do
tot = totient(tot)
tsum += tot
end while
if tsum=n then
perfect &= n
end if
n += 2
end while
printf(1,"The first 20 perfect totient numbers are:\n")
?perfect
|
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
cards := 2 # cards per hand
players := 5 # players to deal to
write("New deck : ", showcards(D := newcarddeck())) # create and show a new deck
write("Shuffled : ", showcards(D := shufflecards(D))) # shuffle it
H := list(players)
every H[1 to players] := [] # hands for each player
every ( c := 1 to cards ) & ( p := 1 to players ) do
put(H[p], dealcard(D)) # deal #players hands of #cards
every write("Player #",p := 1 to players,"'s hand : ",showcards(H[p]))
write("Remaining: ",showcards(D)) # show the rest of the deck
end
record card(suit,pip) #: datatype for a card suit x pip
procedure newcarddeck() #: return a new standard deck
local D
every put(D := [], card(suits(),pips()))
return D
end
procedure suits() #: generate suits
suspend !["H","S","D","C"]
end
procedure pips() #: generate pips
suspend !["2","3","4","5","6","7","8","9","10","J","Q","K","A"]
end
procedure shufflecards(D) #: shuffle a list of cards
every !D :=: ?D # see INL#9
return D
end
procedure dealcard(D) #: deal a card (from the top)
return get(D)
end
procedure showcards(D) #: return a string of all cards in the given list (deck/hand/etc.)
local s
every (s := "") ||:= card2string(!D) || " "
return s
end
procedure card2string(x) #: return a string version of a card
return x.pip || x.suit
end |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Groovy | Groovy | BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3
String nn
boolean first = true
while (true) {
(nn, first, q, r, t, k, n, l) = (4*q + r - t < n*t) \
? ["${n}${first?'.':''}", false, 10*q, 10*(r - n*t), t , k , 10*(3*q + r)/t - 10*n , l ] \
: ['' , first, q*k , (2*q + r)*l , t*l, k + 1, (q*(7*k + 2) + r*l)/(t*l), l + 2]
print nn
} |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Phix | Phix | constant numPlayers = 2,
maxScore = 100
sequence scores = repeat(0,numPlayers)
printf(1,"\nPig The Dice Game\n\n")
integer points = 0, -- points accumulated in current turn, 0=swap turn
player = 1 -- start with first player
while true do
integer roll = rand(6)
printf(1,"Player %d, your score is %d, you rolled %d. ",{player,scores[player],roll})
if roll=1 then
printf(1," Too bad. :(\n")
points = 0 -- swap turn
else
points += roll
if scores[player]+points>=maxScore then exit end if
printf(1,"Round score %d. Roll or Hold?",{points})
integer reply = upper(wait_key())
printf(1,"%c\n",{reply})
if reply == 'H' then
scores[player] += points
points = 0 -- swap turn
end if
end if
if points=0 then
player = mod(player,numPlayers) + 1
end if
end while
printf(1,"\nPlayer %d wins with a score of %d!\n",{player,scores[player]+points}) |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #J | J | ispernicious=: 1 p: +/"1@#: |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Java | Java | public class Pernicious{
//very simple isPrime since x will be <= Long.SIZE
public static boolean isPrime(int x){
if(x < 2) return false;
for(int i = 2; i < x; i++){
if(x % i == 0) return false;
}
return true;
}
public static int popCount(long x){
return Long.bitCount(x);
}
public static void main(String[] args){
for(long i = 1, n = 0; n < 25; i++){
if(isPrime(popCount(i))){
System.out.print(i + " ");
n++;
}
}
System.out.println();
for(long i = 888888877; i <= 888888888; i++){
if(isPrime(popCount(i))) System.out.print(i + " ");
}
}
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Maxima | Maxima | random_element(l):= part(l, 1+random(length(l)));
/* (%i1) random_element(['a, 'b, 'c]);
(%o1) c
*/ |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 0 П0 1 П1 2 П2 3 П3 4 П4 5
^ СЧ * [x] ПE КИПE С/П |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MUMPS | MUMPS | set string="Rosetta Code Phrase Reversal"
set str="",len=$length(string," ")
for i=1:1:len set $piece(str," ",i)=$piece(string," ",len-i+1)
write string,!
write $reverse(string),!
write str,!
write $reverse(str),! |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import algorithm, sequtils, strutils
const Phrase = "rosetta code phrase reversal"
echo "Phrase: ", Phrase
echo "Reversed phrase: ", reversed(Phrase).join()
echo "Reversed words: ", Phrase.split().mapIt(reversed(it).join()).join(" ")
echo "Reversed word order: ", reversed(Phrase.split()).join(" ") |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lua | Lua | -- Return an iterator to produce every permutation of list
function permute (list)
local function perm (list, n)
if n == 0 then coroutine.yield(list) end
for i = 1, n do
list[i], list[n] = list[n], list[i]
perm(list, n - 1)
list[i], list[n] = list[n], list[i]
end
end
return coroutine.wrap(function() perm(list, #list) end)
end
-- Return a copy of table t (wouldn't work for a table of tables)
function copy (t)
if not t then return nil end
local new = {}
for k, v in pairs(t) do new[k] = v end
return new
end
-- Return true if no value in t1 can be found at the same index of t2
function noMatches (t1, t2)
for k, v in pairs(t1) do
if t2[k] == v then return false end
end
return true
end
-- Return a table of all derangements of table t
function derangements (t)
local orig = copy(t)
local nextPerm, deranged = permute(t), {}
local numList, keep = copy(nextPerm())
while numList do
if noMatches(numList, orig) then table.insert(deranged, numList) end
numList = copy(nextPerm())
end
return deranged
end
-- Return the subfactorial of n
function subFact (n)
if n < 2 then
return 1 - n
else
return (subFact(n - 1) + subFact(n - 2)) * (n - 1)
end
end
-- Return a table of the numbers 1 to n
function listOneTo (n)
local t = {}
for i = 1, n do t[i] = i end
return t
end
-- Main procedure
print("Derangements of [1,2,3,4]")
for k, v in pairs(derangements(listOneTo(4))) do print("", unpack(v)) end
print("\n\nSubfactorial vs counted derangements\n")
print("\tn\t| subFact(n)\t| Derangements")
print(" " .. string.rep("-", 42))
for i = 0, 9 do
io.write("\t" .. i .. "\t| " .. subFact(i))
if string.len(subFact(i)) < 5 then io.write("\t") end
print("\t| " .. #derangements(listOneTo(i)))
end
print("\n\nThe subfactorial of 20 is " .. subFact(20)) |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #PicoLisp | PicoLisp | (let
(N 4
L
(mapcar
'((I) (list I 0))
(range 1 N) ) )
(for I L
(printsp (car I)) )
(prinl)
(while
# find the lagest mobile integer
(setq
X
(maxi
'((I) (car (get L (car I))))
(extract
'((I J)
(let? Y
(get
L
((if (=0 (cadr I)) dec inc) J) )
(when (> (car I) (car Y))
(list J (cadr I)) ) ) )
L
(range 1 N) ) )
Y (get L (car X)) )
# swap integer and adjacent int it is looking at
(xchg
(nth L (car X))
(nth
L
((if (=0 (cadr X)) dec inc) (car X)) ) )
# reverse direction of all ints large than our
(for I L
(when (< (car Y) (car I))
(set (cdr I)
(if (=0 (cadr I)) 1 0) ) ) )
# print current positions
(for I L
(printsp (car I)) )
(prinl) ) )
(bye) |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #PowerShell | PowerShell |
function output([Object[]]$A, [Int]$k, [ref]$sign)
{
"Perm: [$([String]::Join(', ', $A))] Sign: $($sign.Value)"
}
function permutation([Object[]]$array)
{
function generate([Object[]]$A, [Int]$k, [ref]$sign)
{
if($k -eq 1)
{
output $A $k $sign
$sign.Value = -$sign.Value
}
else
{
$k -= 1
generate $A $k $sign
for([Int]$i = 0; $i -lt $k; $i += 1)
{
if($i % 2 -eq 0)
{
$A[$i], $A[$k] = $A[$k], $A[$i]
}
else
{
$A[0], $A[$k] = $A[$k], $A[0]
}
generate $A $k $sign
}
}
}
generate $array $array.Count ([ref]1)
}
permutation @(0, 1, 2)
""
permutation @(0, 1, 2, 3)
|
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const array integer: treatmentGroup is [] (85, 88, 75, 66, 25, 29, 83, 39, 97);
const array integer: controlGroup is [] (68, 41, 10, 49, 16, 65, 32, 92, 28, 98);
const array integer: both is treatmentGroup & controlGroup;
const func integer: pick (in integer: at, in integer: remain, in integer: accu, in integer: treat) is func
result
var integer: picked is 0;
begin
if remain = 0 then
picked := ord(accu > treat);
else
picked := pick(at - 1, remain - 1, accu + both[at], treat);
if at > remain then
picked +:= pick(at - 1, remain, accu, treat);
end if;
end if;
end func;
const proc: main is func
local
var integer: experimentalResult is 0;
var integer: treat is 0;
var integer: total is 1;
var integer: le is 0;
var integer: gt is 0;
var integer: i is 0;
begin
for experimentalResult range treatmentGroup do
treat +:= experimentalResult;
end for;
total := 19 ! 10; # Binomial coefficient
gt := pick(19, 9, 0, treat);
le := total - gt;
writeln("<= : " <& 100.0 * flt(le) / flt(total) digits 6 <& "% " <& le);
writeln(" > : " <& 100.0 * flt(gt) / flt(total) digits 6 <& "% " <& gt);
end func; |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Sidef | Sidef | func statistic(ab, a) {
var(sumab, suma) = (ab.sum, a.sum)
suma/a.size - ((sumab-suma) / (ab.size-a.size))
}
func permutationTest(a, b) {
var ab = (a + b)
var tobs = statistic(ab, a)
var under = (var count = 0)
ab.combinations(a.len, {|*perm|
statistic(ab, perm) <= tobs && (under += 1)
count += 1
})
under * 100 / count
}
var treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]
var controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
var under = permutationTest(treatmentGroup, controlGroup)
say ("under=%.2f%%, over=%.2f%%" % (under, 100 - under)) |
http://rosettacode.org/wiki/Percentage_difference_between_images | Percentage difference between images | basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The expected difference for these two images is 1.62125%
| #J | J | require 'media/image3'
'Lenna50.jpg' (+/@,@:|@:- % 2.55 * */@$@])&read_image 'Lenna100.jpg'
1.62559 |
http://rosettacode.org/wiki/Percentage_difference_between_images | Percentage difference between images | basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The expected difference for these two images is 1.62125%
| #Java | Java | import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException {
// https://rosettacode.org/mw/images/3/3c/Lenna50.jpg
// https://rosettacode.org/mw/images/b/b6/Lenna100.jpg
BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg"));
BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg"));
double p = getDifferencePercent(img1, img2);
System.out.println("diff percent: " + p);
}
private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) {
int width = img1.getWidth();
int height = img1.getHeight();
int width2 = img2.getWidth();
int height2 = img2.getHeight();
if (width != width2 || height != height2) {
throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2));
}
long diff = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y));
}
}
long maxDiff = 3L * 255 * width * height;
return 100.0 * diff / maxDiff;
}
private static int pixelDiff(int rgb1, int rgb2) {
int r1 = (rgb1 >> 16) & 0xff;
int g1 = (rgb1 >> 8) & 0xff;
int b1 = rgb1 & 0xff;
int r2 = (rgb2 >> 16) & 0xff;
int g2 = (rgb2 >> 8) & 0xff;
int b2 = rgb2 & 0xff;
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
}
} |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I
I L N Y
FF I L NN PP TTT V W X YY ZZ
FF I L N PP T U U V WW XXX Y Z
F I LL N P T UUU VVV WW X Y ZZ
A Pentomino tiling is an example of an exact cover problem and can take on many forms.
A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered
by the 12 pentomino shapes, without overlaps, with every shape only used once.
The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.
Task
Create an 8 by 8 tiling and print the result.
Example
F I I I I I L N
F F F L L L L N
W F - X Z Z N N
W W X X X Z N V
T W W X - Z Z V
T T T P P V V V
T Y - P P U U U
Y Y Y Y P U - U
Related tasks
Free polyominoes enumeration
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Dim symbols As Char() = "XYPFTVNLUZWI█".ToCharArray(),
nRows As Integer = 8, nCols As Integer = 8,
target As Integer = 12, blank As Integer = 12,
grid As Integer()() = New Integer(nRows - 1)() {},
placed As Boolean() = New Boolean(target - 1) {},
pens As List(Of List(Of Integer())), rand As Random,
seeds As Integer() = {291, 292, 293, 295, 297, 329, 330, 332, 333, 335, 378, 586}
Sub Main()
Unpack(seeds) : rand = New Random() : ShuffleShapes(2)
For r As Integer = 0 To nRows - 1
grid(r) = Enumerable.Repeat(-1, nCols).ToArray() : Next
For i As Integer = 0 To 3
Dim rRow, rCol As Integer : Do : rRow = rand.Next(nRows) : rCol = rand.Next(nCols)
Loop While grid(rRow)(rCol) = blank : grid(rRow)(rCol) = blank
Next
If Solve(0, 0) Then
PrintResult()
Else
Console.WriteLine("no solution for this configuration:") : PrintResult()
End If
If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
Sub ShuffleShapes(count As Integer) ' changes order of the pieces for a more random solution
For i As Integer = 0 To count : For j = 0 To pens.Count - 1
Dim r As Integer : Do : r = rand.Next(pens.Count) : Loop Until r <> j
Dim tmp As List(Of Integer()) = pens(r) : pens(r) = pens(j) : pens(j) = tmp
Dim ch As Char = symbols(r) : symbols(r) = symbols(j) : symbols(j) = ch
Next : Next
End Sub
Sub PrintResult() ' display results
For Each r As Integer() In grid : For Each i As Integer In r
Console.Write("{0} ", If(i < 0, ".", symbols(i)))
Next : Console.WriteLine() : Next
End Sub
' returns first found solution only
Function Solve(ByVal pos As Integer, ByVal numPlaced As Integer) As Boolean
If numPlaced = target Then Return True
Dim row As Integer = pos \ nCols, col As Integer = pos Mod nCols
If grid(row)(col) <> -1 Then Return Solve(pos + 1, numPlaced)
For i As Integer = 0 To pens.Count - 1 : If Not placed(i) Then
For Each orientation As Integer() In pens(i)
If Not TPO(orientation, row, col, i) Then Continue For
placed(i) = True : If Solve(pos + 1, numPlaced + 1) Then Return True
RmvO(orientation, row, col) : placed(i) = False
Next : End If : Next : Return False
End Function
' removes a placed orientation
Sub RmvO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer)
grid(row)(col) = -1 : For i As Integer = 0 To ori.Length - 1 Step 2
grid(row + ori(i))(col + ori(i + 1)) = -1 : Next
End Sub
' checks an orientation, if possible it is placed, else returns false
Function TPO(ByVal ori As Integer(), ByVal row As Integer, ByVal col As Integer,
ByVal sIdx As Integer) As Boolean
For i As Integer = 0 To ori.Length - 1 Step 2
Dim x As Integer = col + ori(i + 1), y As Integer = row + ori(i)
If x < 0 OrElse x >= nCols OrElse y < 0 OrElse y >= nRows OrElse
grid(y)(x) <> -1 Then Return False
Next : grid(row)(col) = sIdx
For i As Integer = 0 To ori.Length - 1 Step 2
grid(row + ori(i))(col + ori(i + 1)) = sIdx
Next : Return True
End Function
'!' the following routines expand the seed values into the 63 orientation arrays.
' source code space savings comparison:
' around 2000 chars for the expansion code, verses about 3000 chars for the integer array defs.
' perhaps not worth the savings?
Sub Unpack(sv As Integer()) ' unpacks a list of seed values into a set of 63 rotated pentominoes
pens = New List(Of List(Of Integer())) : For Each item In sv
Dim Gen As New List(Of Integer()), exi As List(Of Integer) = Expand(item),
fx As Integer() = ToP(exi) : Gen.Add(fx) : For i As Integer = 1 To 7
If i = 4 Then Mir(exi) Else Rot(exi)
fx = ToP(exi) : If Not Gen.Exists(Function(Red) TheSame(Red, fx)) Then Gen.Add(ToP(exi))
Next : pens.Add(Gen) : Next
End Sub
' expands an integer into a set of directions
Function Expand(i As Integer) As List(Of Integer)
Expand = {0}.ToList() : For j As Integer = 0 To 3 : Expand.Insert(1, i And 15) : i >>= 4 : Next
End Function
' converts a set of directions to an array of y, x pairs
Function ToP(p As List(Of Integer)) As Integer()
Dim tmp As List(Of Integer) = {0}.ToList() : For Each item As Integer In p.Skip(1)
tmp.Add(tmp.Item(item >> 2) + {1, 8, -1, -8}(item And 3)) : Next
tmp.Sort() : For i As Integer = tmp.Count - 1 To 0 Step -1 : tmp.Item(i) -= tmp.Item(0) : Next
Dim res As New List(Of Integer) : For Each item In tmp.Skip(1)
Dim adj = If((item And 7) > 4, 8, 0)
res.Add((adj + item) \ 8) : res.Add((item And 7) - adj)
Next : Return res.ToArray()
End Function
' compares integer arrays for equivalency
Function TheSame(a As Integer(), b As Integer()) As Boolean
For i As Integer = 0 To a.Count - 1 : If a(i) <> b(i) Then Return False
Next : Return True
End Function
Sub Rot(ByRef p As List(Of Integer)) ' rotates a set of directions by 90 degrees
For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or ((p(i) + 1) And 3) : Next
End Sub
Sub Mir(ByRef p As List(Of Integer)) ' mirrors a set of directions
For i As Integer = 0 To p.Count - 1 : p(i) = (p(i) And -4) Or (((p(i) Xor 1) + 1) And 3) : Next
End Sub
End Module
|
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #BBC_BASIC | BBC BASIC | FOR n% = 2 TO 10000 STEP 2
IF FNperfect(n%) PRINT n%
NEXT
END
DEF FNperfect(N%)
LOCAL I%, S%
S% = 1
FOR I% = 2 TO SQR(N%)-1
IF N% MOD I% = 0 S% += I% + N% DIV I%
NEXT
IF I% = SQR(N%) S% += I%
= (N% = S%) |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Bracmat | Bracmat | ( ( perf
= sum i
. 0:?sum
& 0:?i
& whl
' ( !i+1:<!arg:?i
& ( mod$(!arg.!i):0&!sum+!i:?sum
|
)
)
& !sum:!arg
)
& 0:?n
& whl
' ( !n+1:~>10000:?n
& (perf$!n&out$!n|)
)
); |
http://rosettacode.org/wiki/Percolation/Bond_percolation | Percolation/Bond percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
, assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards. Each
c
e
l
l
[
m
,
n
]
{\displaystyle \mathrm {cell} [m,n]}
is bounded by (horizontal) walls
h
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {hwall} [m,n]}
and
h
w
a
l
l
[
m
+
1
,
n
]
{\displaystyle \mathrm {hwall} [m+1,n]}
; (vertical) walls
v
w
a
l
l
[
m
,
n
]
{\displaystyle \mathrm {vwall} [m,n]}
and
v
w
a
l
l
[
m
,
n
+
1
]
{\displaystyle \mathrm {vwall} [m,n+1]}
Assume that the probability of any wall being present is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
Except for the outer horizontal walls at
m
=
0
{\displaystyle m=0}
and
m
=
M
{\displaystyle m=M}
which are always present.
The task
Simulate pouring a fluid onto the top surface (
n
=
0
{\displaystyle n=0}
) where the fluid will enter any empty cell it is adjacent to if there is no wall between where it currently is and the cell on the other side of the (missing) wall.
The fluid does not move beyond the horizontal constraints of the grid.
The fluid may move “up” within the confines of the grid of cells. If the fluid reaches a bottom cell that has a missing bottom wall then the fluid can be said to 'drip' out the bottom at that point.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
=
100
{\displaystyle t=100}
.
Use an
M
=
10
,
N
=
10
{\displaystyle M=10,N=10}
grid of cells for all cases.
Optionally depict fluid successfully percolating through a grid graphically.
Show all output on this page.
| #zkl | zkl | // cell states
const FILLED=1; // and odd
const RWALL =2; // right wall
const BWALL =4; // bottom wall
fcn P(p,wall){ (0.0).random(1)<p and wall or 0 }
fcn makeGrid(m,n,p){
// Allocate two addition rows to avoid checking bounds.
// Bottom row is also required by drippage
grid:=Data(m*(n+2));
do(m){ grid.write(BWALL + RWALL); } // grid is topped with walls
do(n){
do(m-1){ grid.write( P(p,BWALL) + P(p,RWALL) ) }
grid.write(RWALL + P(p,BWALL)); // right border is all right wall, as is left border
}
do(m){ grid.write(0); } // for drips off the bottom of grid
grid
}
fcn show(grid,m,n){ n+=1;
println("+--"*m,"+");
foreach i in ([1..n]){ y:=i*m;
print(i==n and " " or "|"); // bottom row is special, otherwise always have left wall
foreach j in (m){ c:=grid[y + j];
print(c.bitAnd(FILLED) and "**" or " ", c.bitAnd(RWALL)and"|"or" ");
}
println();
if(i==n) return(); // nothing under the bottom row
foreach j in (m){ print((grid[y + j].bitAnd(BWALL)) and "+--" or "+ "); }
println("+");
}
}
fcn fill(grid,x,m){
if(grid[x].isOdd) return(False); // aka .bitAnd(FILLED) aka already been here
grid[x]+=FILLED;
if(x+m>=grid.len()) return(True); // success: reached bottom row
return(( not grid[x] .bitAnd(BWALL) and fill(grid,x + m,m) ) or // down
( not grid[x] .bitAnd(RWALL) and fill(grid,x + 1,m) ) or // right
( not grid[x - 1].bitAnd(RWALL) and fill(grid,x - 1,m) ) or // left
( not grid[x - m].bitAnd(BWALL) and fill(grid,x - m,m) )); // up
}
fcn percolate(grid,m){
i:=0; while(i<m and not fill(grid,i+m,m)){ i+=1; } // pour juice on top row
return(i<m); // percolated through the grid?
} |
http://rosettacode.org/wiki/Percolation/Mean_run_density | Percolation/Mean run density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
v
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #Python | Python | from __future__ import division
from random import random
from math import fsum
n, p, t = 100, 0.5, 500
def newv(n, p):
return [int(random() < p) for i in range(n)]
def runs(v):
return sum((a & ~b) for a, b in zip(v, v[1:] + [0]))
def mean_run_density(n, p):
return runs(newv(n, p)) / n
for p10 in range(1, 10, 2):
p = p10 / 10
limit = p * (1 - p)
print('')
for n2 in range(10, 16, 2):
n = 2**n2
sim = fsum(mean_run_density(n, p) for i in range(t)) / t
print('t=%3i p=%4.2f n=%5i p(1-p)=%5.3f sim=%5.3f delta=%3.1f%%'
% (t, p, n, limit, sim, abs(sim - limit) / limit * 100 if limit else sim * 100)) |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N
{\displaystyle M\times N}
rectangular array of cells numbered
c
e
l
l
[
0..
M
−
1
,
0..
N
−
1
]
{\displaystyle \mathrm {cell} [0..M-1,0..N-1]}
assume
M
{\displaystyle M}
is horizontal and
N
{\displaystyle N}
is downwards.
Assume that the probability of any cell being filled is a constant
p
{\displaystyle p}
where
0.0
≤
p
≤
1.0
{\displaystyle 0.0\leq p\leq 1.0}
The task
Simulate creating the array of cells with probability
p
{\displaystyle p}
and then
testing if there is a route through adjacent filled cells from any on row
0
{\displaystyle 0}
to any on row
N
{\displaystyle N}
, i.e. testing for site percolation.
Given
p
{\displaystyle p}
repeat the percolation
t
{\displaystyle t}
times to estimate the proportion of times that the fluid can percolate to the bottom for any given
p
{\displaystyle p}
.
Show how the probability of percolating through the random grid changes with
p
{\displaystyle p}
going from
0.0
{\displaystyle 0.0}
to
1.0
{\displaystyle 1.0}
in
0.1
{\displaystyle 0.1}
increments and with the number of repetitions to estimate the fraction at any given
p
{\displaystyle p}
as
t
>=
100
{\displaystyle t>=100}
.
Use an
M
=
15
,
N
=
15
{\displaystyle M=15,N=15}
grid of cells for all cases.
Optionally depict a percolation through a cell grid graphically.
Show all output on this page.
| #zkl | zkl | fcn makeGrid(m,n,p){
grid:=Data((m+1)*(n+1)); // first row and right edges are buffers
grid.write(" "*m); grid.write("\r");
do(n){
do(m){ grid.write(((0.0).random(1)<p) and "+" or "."); } // cell is porous or not
grid.write("\n");
}
grid
}
fcn ff(grid,x,m){ // walk across row looking for a porous cell
if(grid[x]!=43) return(0); // '+' == 43 ASCII == porous
grid[x]="#";
return(x+m>=grid.len() or
ff(grid,x+m,m) or ff(grid,x+1,m) or ff(grid,x-1,m) or ff(grid,x-m,m));
}
fcn percolate(grid,m){
x:=m+1; i:=0; while(i<m and not ff(grid,x,m)){ x+=1; i+=1; }
return(i<m); // percolated through the grid?
}
grid:=makeGrid(15,15,0.60);
println("Did liquid percolate: ",percolate(grid,15));
println("15x15 grid:\n",grid.text);
println("Running 10,000 tests for each case:");
foreach p in ([0.0 .. 1.0, 0.1]){
cnt:=0.0; do(10000){ cnt+=percolate(makeGrid(15,15,p),15); }
"p=%.1f: %.4f".fmt(p, cnt/10000).println();
} |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #BASIC256 | BASIC256 | arraybase 1
n = 4 : cont = 0
dim a(n)
dim c(n)
for j = 1 to n
a[j] = j
next j
do
for i = 1 to n
print a[i];
next
print " ";
i = n
cont += 1
if cont = 12 then
print
cont = 0
else
print " ";
end if
do
i -= 1
until (i = 0) or (a[i] < a[i+1])
j = i + 1
k = n
while j < k
tmp = a[j] : a[j] = a[k] : a[k] = tmp
j += 1
k -= 1
end while
if i > 0 then
j = i + 1
while a[j] < a[i]
j += 1
end while
tmp = a[j] : a[j] = a[i] : a[i] = tmp
end if
until i = 0
end |
http://rosettacode.org/wiki/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #Haskell | Haskell | shuffle :: [a] -> [a]
shuffle lst = let (a,b) = splitAt (length lst `div` 2) lst
in foldMap (\(x,y) -> [x,y]) $ zip a b
findCycle :: Eq a => (a -> a) -> a -> [a]
findCycle f x = takeWhile (/= x) $ iterate f (f x)
main = mapM_ report [ 8, 24, 52, 100, 1020, 1024, 10000 ]
where
report n = putStrLn ("deck of " ++ show n ++ " cards: "
++ show (countSuffles n) ++ " shuffles!")
countSuffles n = 1 + length (findCycle shuffle [1..n]) |
http://rosettacode.org/wiki/Perlin_noise | Perlin noise | The Perlin noise is a kind of gradient noise invented by Ken Perlin around the end of the twentieth century and still currently heavily used in computer graphics, most notably to procedurally generate textures or heightmaps.
The Perlin noise is basically a pseudo-random mapping of
R
d
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #Phix | Phix | with javascript_semantics
constant ph = x"97 A0 89 5B 5A 0F 83 0D C9 5F 60 35 C2 E9 07 E1"&
x"8C 24 67 1E 45 8E 08 63 25 F0 15 0A 17 BE 06 94"&
x"F7 78 EA 4B 00 1A C5 3E 5E FC DB CB 75 23 0B 20"&
x"39 B1 21 58 ED 95 38 57 AE 14 7D 88 AB A8 44 AF"&
x"4A A5 47 86 8B 30 1B A6 4D 92 9E E7 53 6F E5 7A"&
x"3C D3 85 E6 DC 69 5C 29 37 2E F5 28 F4 66 8F 36"&
x"41 19 3F A1 01 D8 50 49 D1 4C 84 BB D0 59 12 A9"&
x"C8 C4 87 82 74 BC 9F 56 A4 64 6D C6 AD BA 03 40"&
x"34 D9 E2 FA 7C 7B 05 CA 26 93 76 7E FF 52 55 D4"&
x"CF CE 3B E3 2F 10 3A 11 B6 BD 1C 2A DF B7 AA D5"&
x"77 F8 98 02 2C 9A A3 46 DD 99 65 9B A7 2B AC 09"&
x"81 16 27 FD 13 62 6C 6E 4F 71 E0 E8 B2 B9 70 68"&
x"DA F6 61 E4 FB 22 F2 C1 EE D2 90 0C BF B3 A2 F1"&
x"51 33 91 EB F9 0E EF 6B 31 C0 D6 1F B5 C7 6A 9D"&
x"B8 54 CC B0 73 79 32 2D 7F 04 96 FE 8A EC CD 5D"&
x"DE 72 43 1D 18 48 F3 8D 80 C3 4E 42 D7 3D 9C B4",
p = ph&ph
function fade(atom t) return t * t * t * (t * (t * 6 - 15) + 10) end function
function lerp(atom t, a, b) return a + t * (b - a) end function
function grad(int hash, atom x, y, z)
int h = and_bits(hash,15)
atom u = iff(h<8 ? x : y),
v = iff(h<4 ? y : iff(h==12 or h==14 ? x : z))
return iff(and_bits(h,1) == 0 ? u : -u) +
iff(and_bits(h,2) == 0 ? v : -v)
end function
function noise(atom x, y, z)
integer X = and_bits(x,255),
Y = and_bits(y,255),
Z = and_bits(z,255)
x -= floor(x)
y -= floor(y)
z -= floor(z)
atom u = fade(x),
v = fade(y),
w = fade(z)
integer A = p[X+1]+Y, AA = p[A+1]+Z, AB = p[A+2]+Z,
B = p[X+2]+Y, BA = p[B+1]+Z, BB = p[B+2]+Z
return lerp(w,lerp(v,lerp(u,grad(p[AA+1], x , y , z ),
grad(p[BA+1], x-1, y , z )),
lerp(u,grad(p[AB+1], x , y-1, z ),
grad(p[BB+1], x-1, y-1, z ))),
lerp(v,lerp(u,grad(p[AA+2], x , y , z-1 ),
grad(p[BA+2], x-1, y , z-1 )),
lerp(u,grad(p[AB+2], x , y-1, z-1 ),
grad(p[BB+2], x-1, y-1, z-1 ))))
end function
printf(1,"Perlin Noise for (3.14,42,7) is %.17f\n",{noise(3.14,42,7)})
|
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #PicoLisp | PicoLisp | (gc 16)
(de gcd (A B)
(until (=0 B)
(let M (% A B)
(setq A B B M) ) )
(abs A) )
(de totient (N)
(let C 0
(for I N
(and (=1 (gcd N I)) (inc 'C)) )
C ) )
(de totients (NIL)
(let (C 0 N 1)
(while (> 20 C)
(let (Cur N S 0)
(while (> Cur 1)
(inc 'S (setq Cur (totient Cur))) )
(when (= S N)
(inc 'C)
(prin N " ")
(flush) )
(inc 'N 2) ) )
(prinl) ) )
(totients) |
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #PILOT | PILOT | C :z=0
:n=3
*num
C :s=0
:x=n
*perfect
C :t=0
:i=1
*totient
C :a=x
:b=i
*gcd
C :c=a-b*(a/b)
:a=b
:b=c
J (b>0):*gcd
C (a=1):t=t+1
C :i=i+1
J (i<=x-1):*totient
C :x=t
:s=s+x
J (x<>1):*perfect
T (s=n):#n
C (s=n):z=z+1
C :n=n+2
J (z<20):*num
E : |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #J | J | NB. playingcards.ijs
NB. Defines a Rosetta Code playing cards class
NB. Multiple decks may be used, one for each instance of this class.
coclass 'rcpc' NB. Rosetta Code playing cards class
NB. Class objects
Ranks=: _2 ]\ ' A 2 3 4 5 6 7 8 910 J Q K'
Suits=: ucp '♦♣♥♠'
DeckPrototype=: (] #: i.@:*/)Ranks ,&# Suits
NB. Class methods
create=: monad define
1: TheDeck=: DeckPrototype
)
destroy=: codestroy
sayCards=: ({&Ranks@{. , {&Suits@{:)"1
shuffle=: monad define
1: TheDeck=: ({~ ?~@#) TheDeck
)
NB.*dealCards v Deals y cards [to x players]
NB. x is: optional number of players, defaults to one
NB. Used monadically, the player-axis is omitted from output.
dealCards=: verb define
{. 1 dealCards y
:
'Too few cards in deck' assert (# TheDeck) >: ToBeDealt=. x*y
CardsOffTop=. ToBeDealt {. TheDeck
TheDeck =: ToBeDealt }. TheDeck
(x,y)$ CardsOffTop
)
NB.*pcc v "Print" current contents of the deck.
pcc=: monad define
sayCards TheDeck
)
newDeck_z_=: conew&'rcpc' |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Haskell | Haskell | pi_ = g (1, 0, 1, 1, 3, 3)
where
g (q, r, t, k, n, l) =
if 4 * q + r - t < n * t
then n :
g
( 10 * q
, 10 * (r - n * t)
, t
, k
, div (10 * (3 * q + r)) t - 10 * n
, l)
else g
( q * k
, (2 * q + r) * l
, t * l
, k + 1
, div (q * (7 * k + 2) + r * l) (t * l)
, l + 2) |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #PHP | PHP | error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING ));
define('MAXSCORE', 100);
define('PLAYERCOUNT', 2);
$confirm = array('Y', 'y', '');
while (true) {
printf(' Player %d: (%d, %d) Rolling? (Yn) ', $player,
$safeScore[$player], $score);
if ($safeScore[$player] + $score < MAXSCORE &&
in_array(trim(fgets(STDIN)), $confirm)) {
$rolled = rand(1, 6);
echo " Rolled $rolled \n";
if ($rolled == 1) {
printf(' Bust! You lose %d but keep %d \n\n',
$score, $safeScore[$player]);
} else {
$score += $rolled;
continue;
}
} else {
$safeScore[$player] += $score;
if ($safeScore[$player] >= MAXSCORE)
break;
echo ' Sticking with ', $safeScore[$player], '\n\n';
}
$score = 0;
$player = ($player + 1) % PLAYERCOUNT;
}
printf('\n\nPlayer %d wins with a score of %d ',
$player, $safeScore[$player]);
|
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #jq | jq | # is_prime is designed to work with jq 1.4
def is_prime:
if . == 2 then true
else 2 < . and . % 2 == 1 and
. as $in
| (($in + 1) | sqrt) as $m
| (((($m - 1) / 2) | floor) + 1) as $max
| reduce range(1; $max) as $i
(true; if . then ($in % ((2 * $i) + 1)) > 0 else false end)
end;
def popcount:
def bin: recurse( if . == 0 then empty else ./2 | floor end ) % 2;
[bin] | add;
def is_pernicious: popcount | is_prime;
# Emit a stream of "count" pernicious numbers greater than
# or equal to m:
def pernicious(m; count):
if count > 0 then
if m | is_pernicious then m, pernicious(m+1; count -1)
else pernicious(m+1; count)
end
else empty
end;
def task:
# display the first 25 pernicious numbers:
[ pernicious(1;25) ],
# display all pernicious numbers between
# 888,888,877 and 888,888,888 (inclusive).
[ range(888888877; 888888889) | select( is_pernicious ) ]
;
task |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Julia | Julia | using Primes
ispernicious(n::Integer) = isprime(count_ones(n))
nextpernicious(n::Integer) = begin n += 1; while !ispernicious(n) n += 1 end; return n end
function perniciouses(n::Int)
rst = Vector{Int}(n)
rst[1] = 3
for i in 2:n
rst[i] = nextpernicious(rst[i-1])
end
return rst
end
perniciouses(a::Integer, b::Integer) = filter(ispernicious, a:b)
println("First 25 pernicious numbers: ", join(perniciouses(25), ", "))
println("Perniciouses in [888888877, 888888888]: ", join(perniciouses(888888877, 888888888), ", ")) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Nanoquery | Nanoquery | import Nanoquery.Util
list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
println list[new(Random).getInt(len(list))] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #NetLogo | NetLogo | ;; from list containnig only literals and literal constants
user-message one-of [ 1 3 "rooster" blue ]
;; from list containing variables and reporters
user-message one-of (list (red + 2) turtles (patch 0 0) ) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
iArray = [ 1, 2, 3, 4, 5 ] -- a traditional array
iList = Arrays.asList(iArray) -- a Java Collection "List" object
iWords = '1 2 3 4 5' -- a list as a string of space delimited words
v1 = iArray[Random().nextInt(iArray.length)]
v2 = iList.get(Random().nextInt(iList.size()))
v3 = iWords.word(Random().nextInt(iWords.words()) + 1) -- the index for word() starts at one
say v1 v2 v3
|
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Oforth | Oforth | "rosetta code phrase reversal" reverse println
"rosetta code phrase reversal" words map(#reverse) unwords println
"rosetta code phrase reversal" words reverse unwords println |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Perl | Perl | use feature 'say';
my $s = "rosetta code phrase reversal";
say "0. Input : ", $s;
say "1. String reversed : ", scalar reverse $s;
say "2. Each word reversed : ", join " ", reverse split / /, reverse $s;
say "3. Word-order reversed : ", join " ", reverse split / /,$s;
# Or, using a regex:
say "2. Each word reversed : ", $s =~ s/[^ ]+/reverse $&/gre; |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language |
Needs["Combinatorica`"]
derangements[n_] := Derangements[Range[n]]
derangements[4]
Table[{NumberOfDerangements[i], Subfactorial[i]}, {i, 9}] // TableForm
Subfactorial[20] |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #Python | Python | from operator import itemgetter
DEBUG = False # like the built-in __debug__
def spermutations(n):
"""permutations by swapping. Yields: perm, sign"""
sign = 1
p = [[i, 0 if i == 0 else -1] # [num, direction]
for i in range(n)]
if DEBUG: print ' #', p
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p): # moving
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),
key=itemgetter(1))
sign *= -1
if d1 == -1:
# Swap down
i2 = i1 - 1
p[i1], p[i2] = p[i2], p[i1]
# If this causes the chosen element to reach the First or last
# position within the permutation, or if the next element in the
# same direction is larger than the chosen element:
if i2 == 0 or p[i2 - 1][0] > n1:
# The direction of the chosen element is set to zero
p[i2][1] = 0
elif d1 == 1:
# Swap up
i2 = i1 + 1
p[i1], p[i2] = p[i2], p[i1]
# If this causes the chosen element to reach the first or Last
# position within the permutation, or if the next element in the
# same direction is larger than the chosen element:
if i2 == n - 1 or p[i2 + 1][0] > n1:
# The direction of the chosen element is set to zero
p[i2][1] = 0
if DEBUG: print ' #', p
yield tuple(pp[0] for pp in p), sign
for i3, pp in enumerate(p):
n3, d3 = pp
if n3 > n1:
pp[1] = 1 if i3 < i2 else -1
if DEBUG: print ' # Set Moving'
if __name__ == '__main__':
from itertools import permutations
for n in (3, 4):
print '\nPermutations and sign of %i items' % n
sp = set()
for i in spermutations(n):
sp.add(i[0])
print('Perm: %r Sign: %2i' % i)
#if DEBUG: raw_input('?')
# Test
p = set(permutations(range(n)))
assert sp == p, 'Two methods of generating permutations do not agree' |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Tcl | Tcl | package require Tcl 8.5
# Difference of means; note that the first list must be the concatenation of
# the two lists (because this is cheaper to work with).
proc statistic {AB A} {
set sumAB [tcl::mathop::+ {*}$AB]
set sumA [tcl::mathop::+ {*}$A]
expr {
$sumA / double([llength $A]) -
($sumAB - $sumA) / double([llength $AB] - [llength $A])
}
}
# Selects all k-sized combinations from a list.
proc selectCombinationsFrom {k l} {
if {$k == 0} {return {}} elseif {$k == [llength $l]} {return [list $l]}
set all {}
set n [expr {[llength $l] - [incr k -1]}]
for {set i 0} {$i < $n} {} {
set first [lindex $l $i]
incr i
if {$k == 0} {
lappend all $first
} else {
foreach s [selectCombinationsFrom $k [lrange $l $i end]] {
lappend all [list $first {*}$s]
}
}
}
return $all
}
# Compute the permutation test value and its complement.
proc permutationTest {A B} {
set whole [concat $A $B]
set Tobs [statistic $whole $A]
set undercount 0
set overcount 0
set count 0
foreach perm [selectCombinationsFrom [llength $A] $whole] {
set t [statistic $whole $perm]
incr count
if {$t <= $Tobs} {incr undercount} else {incr overcount}
}
set count [tcl::mathfunc::double $count]
list [expr {$overcount / $count}] [expr {$undercount / $count}]
} |
http://rosettacode.org/wiki/Percentage_difference_between_images | Percentage difference between images | basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The expected difference for these two images is 1.62125%
| #JavaScript | JavaScript | function getImageData(url, callback) {
var img = document.createElement('img');
var canvas = document.createElement('canvas');
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
callback(ctx.getImageData(0, 0, img.width, img.height));
};
img.src = url;
}
function compare(firstImage, secondImage, callback) {
getImageData(firstImage, function (img1) {
getImageData(secondImage, function (img2) {
if (img1.width !== img2.width || img1.height != img2.height) {
callback(NaN);
return;
}
var diff = 0;
for (var i = 0; i < img1.data.length / 4; i++) {
diff += Math.abs(img1.data[4 * i + 0] - img2.data[4 * i + 0]) / 255;
diff += Math.abs(img1.data[4 * i + 1] - img2.data[4 * i + 1]) / 255;
diff += Math.abs(img1.data[4 * i + 2] - img2.data[4 * i + 2]) / 255;
}
callback(100 * diff / (img1.width * img1.height * 3));
});
});
}
compare('Lenna50.jpg', 'Lenna100.jpg', function (result) {
console.log(result);
}); |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I
I L N Y
FF I L NN PP TTT V W X YY ZZ
FF I L N PP T U U V WW XXX Y Z
F I LL N P T UUU VVV WW X Y ZZ
A Pentomino tiling is an example of an exact cover problem and can take on many forms.
A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered
by the 12 pentomino shapes, without overlaps, with every shape only used once.
The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.
Task
Create an 8 by 8 tiling and print the result.
Example
F I I I I I L N
F F F L L L L N
W F - X Z Z N N
W W X X X Z N V
T W W X - Z Z V
T T T P P V V V
T Y - P P U U U
Y Y Y Y P U - U
Related tasks
Free polyominoes enumeration
| #Wren | Wren | import "random" for Random
import "/trait" for Stepped
var F = [
[1, -1, 1, 0, 1, 1, 2, 1], [0, 1, 1, -1, 1, 0, 2, 0],
[1, 0, 1, 1, 1, 2, 2, 1], [1, 0, 1, 1, 2, -1, 2, 0],
[1, -2, 1, -1, 1, 0, 2, -1], [0, 1, 1, 1, 1, 2, 2, 1],
[1, -1, 1, 0, 1, 1, 2, -1], [1, -1, 1, 0, 2, 0, 2, 1]
]
var I = [
[0, 1, 0, 2, 0, 3, 0, 4], [1, 0, 2, 0, 3, 0, 4, 0]
]
var L = [
[1, 0, 1, 1, 1, 2, 1, 3], [1, 0, 2, 0, 3, -1, 3, 0],
[0, 1, 0, 2, 0, 3, 1, 3], [0, 1, 1, 0, 2, 0, 3, 0],
[0, 1, 1, 1, 2, 1, 3, 1], [0, 1, 0, 2, 0, 3, 1, 0],
[1, 0, 2, 0, 3, 0, 3, 1], [1, -3, 1, -2, 1, -1, 1, 0]
]
var N = [
[0, 1, 1, -2, 1, -1, 1, 0], [1, 0, 1, 1, 2, 1, 3, 1],
[0, 1, 0, 2, 1, -1, 1, 0], [1, 0, 2, 0, 2, 1, 3, 1],
[0, 1, 1, 1, 1, 2, 1, 3], [1, 0, 2, -1, 2, 0, 3, -1],
[0, 1, 0, 2, 1, 2, 1, 3], [1, -1, 1, 0, 2, -1, 3, -1]
]
var P = [
[0, 1, 1, 0, 1, 1, 2, 1], [0, 1, 0, 2, 1, 0, 1, 1],
[1, 0, 1, 1, 2, 0, 2, 1], [0, 1, 1, -1, 1, 0, 1, 1],
[0, 1, 1, 0, 1, 1, 1, 2], [1, -1, 1, 0, 2, -1, 2, 0],
[0, 1, 0, 2, 1, 1, 1, 2], [0, 1, 1, 0, 1, 1, 2, 0]
]
var T = [
[0, 1, 0, 2, 1, 1, 2, 1], [1, -2, 1, -1, 1, 0, 2, 0],
[1, 0, 2, -1, 2, 0, 2, 1], [1, 0, 1, 1, 1, 2, 2, 0]
]
var U = [
[0, 1, 0, 2, 1, 0, 1, 2], [0, 1, 1, 1, 2, 0, 2, 1],
[0, 2, 1, 0, 1, 1, 1, 2], [0, 1, 1, 0, 2, 0, 2, 1]
]
var V = [
[1, 0, 2, 0, 2, 1, 2, 2], [0, 1, 0, 2, 1, 0, 2, 0],
[1, 0, 2, -2, 2, -1, 2, 0], [0, 1, 0, 2, 1, 2, 2, 2]
]
var W = [
[1, 0, 1, 1, 2, 1, 2, 2], [1, -1, 1, 0, 2, -2, 2, -1],
[0, 1, 1, 1, 1, 2, 2, 2], [0, 1, 1, -1, 1, 0, 2, -1]
]
var X = [[1, -1, 1, 0, 1, 1, 2, 0]]
var Y = [
[1, -2, 1, -1, 1, 0, 1, 1], [1, -1, 1, 0, 2, 0, 3, 0],
[0, 1, 0, 2, 0, 3, 1, 1], [1, 0, 2, 0, 2, 1, 3, 0],
[0, 1, 0, 2, 0, 3, 1, 2], [1, 0, 1, 1, 2, 0, 3, 0],
[1, -1, 1, 0, 1, 1, 1, 2], [1, 0, 2, -1, 2, 0, 3, 0]
]
var Z = [
[0, 1, 1, 0, 2, -1, 2, 0], [1, 0, 1, 1, 1, 2, 2, 2],
[0, 1, 1, 1, 2, 1, 2, 2], [1, -2, 1, -1, 1, 0, 2, -2]
]
var shapes = [F, I, L, N, P, T, U, V, W, X, Y, Z]
var rand = Random.new()
var symbols = "FILNPTUVWXYZ-".toList
var nRows = 8
var nCols = 8
var blank = 12
var grid = List.filled(nRows, null)
for (i in 0...nRows) grid[i] = List.filled(nCols, 0)
var placed = List.filled(symbols.count - 1, false)
var tryPlaceOrientation = Fn.new { |o, r, c, shapeIndex|
for (i in Stepped.new(0...o.count, 2)) {
var x = c + o[i + 1]
var y = r + o[i]
if (x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != - 1) return false
}
grid[r][c] = shapeIndex
for (i in Stepped.new(0...o.count, 2)) grid[r + o[i]][c + o[i + 1]] = shapeIndex
return true
}
var removeOrientation = Fn.new { |o, r, c|
grid[r][c] = -1
for (i in Stepped.new(0...o.count, 2)) grid[r + o[i]][c + o[i + 1]] = -1
}
var solve // recursive
solve = Fn.new { |pos, numPlaced|
if (numPlaced == shapes.count) return true
var row = (pos / nCols).floor
var col = pos % nCols
if (grid[row][col] != -1) return solve.call(pos + 1, numPlaced)
for (i in 0...shapes.count) {
if (!placed[i]) {
for (orientation in shapes[i]) {
if (!tryPlaceOrientation.call(orientation, row, col, i)) continue
placed[i] = true
if (solve.call(pos + 1, numPlaced + 1)) return true
removeOrientation.call(orientation, row, col)
placed[i] = false
}
}
}
return false
}
var shuffleShapes = Fn.new {
var n = shapes.count
while (n > 1) {
var r = rand.int(n)
n = n - 1
shapes.swap(r, n)
symbols.swap(r, n)
}
}
var printResult = Fn.new {
for (r in grid) {
for (i in r) System.write("%(symbols[i]) ")
System.print()
}
}
shuffleShapes.call()
for (r in 0...nRows) {
for (c in 0...grid[r].count) grid[r][c] = -1
}
for (i in 0..3) {
var randRow
var randCol
while (true) {
randRow = rand.int(nRows)
randCol = rand.int(nCols)
if (grid[randRow][randCol] != blank) break
}
grid[randRow][randCol] = blank
}
if (solve.call(0, 0)) printResult.call() else System.print("No solution") |
http://rosettacode.org/wiki/Perfect_numbers | Perfect numbers | Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself.
Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes
using the formula (2n - 1) × 2n - 1.
It is not known if there are any odd perfect numbers (any that exist are larger than 102000).
The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
See also
Rational Arithmetic
Perfect numbers on OEIS
Odd Perfect showing the current status of bounds on odd perfect numbers.
| #Burlesque | Burlesque | Jfc++\/2.*== |
http://rosettacode.org/wiki/Percolation/Mean_run_density | Percolation/Mean run density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
v
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #Racket | Racket | #lang racket
(require racket/fixnum)
(define t (make-parameter 100))
(define (Rn v)
(define (inner-Rn rv idx b-1)
(define b (fxvector-ref v idx))
(define rv+ (if (and (= b 1) (= b-1 0)) (add1 rv) rv))
(if (zero? idx) rv+ (inner-Rn rv+ (sub1 idx) b)))
(inner-Rn 0 (sub1 (fxvector-length v)) 0))
(define ((make-random-bit-vector p) n)
(for/fxvector
#:length n ((i n))
(if (<= (random) p) 1 0)))
(define (Rn/n l->p n) (/ (Rn (l->p n)) n))
(for ((p (in-list '(1/10 3/10 1/2 7/10 9/10))))
(define l->p (make-random-bit-vector p))
(define Kp (* p (- 1 p)))
(printf "p = ~a\tK(p) =\t~a\t~a~%" p Kp (real->decimal-string Kp 4))
(for ((n (in-list '(10 100 1000 10000))))
(define sum-Rn/n (for/sum ((i (in-range (t)))) (Rn/n l->p n)))
(define sum-Rn/n/t (/ sum-Rn/n (t)))
(printf "mean(R_~a/~a) =\t~a\t~a~%"
n n sum-Rn/n/t (real->decimal-string sum-Rn/n/t 4)))
(newline))
(module+ test
(require rackunit)
(check-eq? (Rn (fxvector 1 1 0 0 0 1 0 1 1 1)) 3)) |
http://rosettacode.org/wiki/Percolation/Mean_run_density | Percolation/Mean run density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
v
{\displaystyle v}
be a vector of
n
{\displaystyle n}
values of either 1 or 0 where the probability of any
value being 1 is
p
{\displaystyle p}
; the probability of a value being 0 is therefore
1
−
p
{\displaystyle 1-p}
.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length
n
{\displaystyle n}
be
R
n
{\displaystyle R_{n}}
.
For example, the following vector has
R
10
=
3
{\displaystyle R_{10}=3}
[1 1 0 0 0 1 0 1 1 1]
^^^ ^ ^^^^^
Percolation theory states that
K
(
p
)
=
lim
n
→
∞
R
n
/
n
=
p
(
1
−
p
)
{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}
Task
Any calculation of
R
n
/
n
{\displaystyle R_{n}/n}
for finite
n
{\displaystyle n}
is subject to randomness so should be
computed as the average of
t
{\displaystyle t}
runs, where
t
≥
100
{\displaystyle t\geq 100}
.
For values of
p
{\displaystyle p}
of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying
n
{\displaystyle n}
on the accuracy of simulated
K
(
p
)
{\displaystyle K(p)}
.
Show your output here.
See also
s-Run on Wolfram mathworld. | #REXX | REXX | /* REXX */
Numeric Digits 20
Call random(,12345) /* make the run reproducable */
pList = '.1 .3 .5 .7 .9'
nList = '1e2 1e3 1e4 1e5'
t = 100
Do While plist<>''
Parse Var plist p plist
theory=p*(1-p)
Say ' '
Say 'p:' format(p,2,4)' theory:'format(theory,2,4)' t:'format(t,4)
Say ' n sim sim-theory'
nl=nlist
Do While nl<>''
Parse Var nl n nl
sum=0
Do i=1 To t
run=0
Do j=1 To n
one=random(1000)<p*1000
If one & (run=0) Then
sum=sum+1
run=one
End
End
sim=sum/(n*100)
Say format(n,10)' ' format(sim,2,4)' 'format(sim-theory,2,6)
End
End |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
set arr=ABCD
set /a n=4
:: echo !arr!
call :permu %n% arr
goto:eof
:permu num &arr
setlocal
if %1 equ 1 call echo(!%2! & exit /b
set /a "num=%1-1,n2=num-1"
set arr=!%2!
for /L %%c in (0,1,!n2!) do (
call:permu !num! arr
set /a n1="num&1"
if !n1! equ 0 (call:swapit !num! 0 arr) else (call:swapit !num! %%c arr)
)
call:permu !num! arr
endlocal & set %2=%arr%
exit /b
:swapit from to &arr
setlocal
set arr=!%3!
set temp1=!arr:~%~1,1!
set temp2=!arr:~%~2,1!
set arr=!arr:%temp1%=@!
set arr=!arr:%temp2%=%temp1%!
set arr=!arr:@=%temp2%!
:: echo %1 %2 !%~3! !arr!
endlocal & set %3=%arr%
exit /b
|
http://rosettacode.org/wiki/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #J | J | shuf=: /: $ /:@$ 0 1"_ |
http://rosettacode.org/wiki/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:
original:
1
2
3
4
5
6
7
8
after 1st shuffle:
1
5
2
6
3
7
4
8
after 2nd shuffle:
1
3
5
7
2
4
6
8
after 3rd shuffle:
1
2
3
4
5
6
7
8
The Task
Write a function that can perform a perfect shuffle on an even-sized list of values.
Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
Test Cases
input (deck size)
output (number of shuffles required)
8
3
24
11
52
8
100
30
1020
1018
1024
10
10000
300
| #Java | Java | import java.util.Arrays;
import java.util.stream.IntStream;
public class PerfectShuffle {
public static void main(String[] args) {
int[] sizes = {8, 24, 52, 100, 1020, 1024, 10_000};
for (int size : sizes)
System.out.printf("%5d : %5d%n", size, perfectShuffle(size));
}
static int perfectShuffle(int size) {
if (size % 2 != 0)
throw new IllegalArgumentException("size must be even");
int half = size / 2;
int[] a = IntStream.range(0, size).toArray();
int[] original = a.clone();
int[] aa = new int[size];
for (int count = 1; true; count++) {
System.arraycopy(a, 0, aa, 0, size);
for (int i = 0; i < half; i++) {
a[2 * i] = aa[i];
a[2 * i + 1] = aa[i + half];
}
if (Arrays.equals(a, original))
return count;
}
}
} |
http://rosettacode.org/wiki/Perlin_noise | Perlin noise | The Perlin noise is a kind of gradient noise invented by Ken Perlin around the end of the twentieth century and still currently heavily used in computer graphics, most notably to procedurally generate textures or heightmaps.
The Perlin noise is basically a pseudo-random mapping of
R
d
{\displaystyle \mathbb {R} ^{d}}
into
R
{\displaystyle \mathbb {R} }
with an integer
d
{\displaystyle d}
which can be arbitrarily large but which is usually 2, 3, or 4.
Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.
Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.
| #PureBasic | PureBasic | ; Perlin_noise
; http://www.rosettacode.org
DataSection
STARTDATA:
Data.i 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180
ENDDATA:
EndDataSection
Procedure.i p(index.i)
ProcedureReturn PeekI(?STARTDATA+SizeOf(Integer)*index)
EndProcedure
Procedure.d fade(t.d)
ProcedureReturn ((t*6-15)*t+10)*t*t*t
EndProcedure
Procedure.d lerp(t.d,a.d,b.d)
ProcedureReturn t*(b-a)+a
EndProcedure
Procedure.d grad(hash.i, x.d,y.d,z.d)
Select hash & 15
Case 0 : ProcedureReturn x+y
Case 1 : ProcedureReturn y-x
Case 2 : ProcedureReturn x-y
Case 3 : ProcedureReturn -x-y
Case 4 : ProcedureReturn x+z
Case 5 : ProcedureReturn z-x
Case 6 : ProcedureReturn x-z
Case 7 : ProcedureReturn -x-y
Case 8 : ProcedureReturn y+z
Case 9 : ProcedureReturn z-y
Case 10 : ProcedureReturn y-z
Case 11 : ProcedureReturn -y-z
Case 12 : ProcedureReturn x+y
Case 13 : ProcedureReturn z-y
Case 14 : ProcedureReturn y-x
Case 15 : ProcedureReturn -y-z
EndSelect
EndProcedure
Procedure.d noise(x.d,y.d,z.d)
Define.d u,v,w
Define.i a,b,c,A0,A1,A2,B0,B1,B2
a=Int(x)&255
b=Int(y)&255
c=Int(z)&255
x=x-IntQ(x)
y=y-IntQ(y)
z=z-IntQ(z)
u=fade(x)
v=fade(y)
w=fade(z)
A0=p(a)+b
A1=p(A0)+c
A2=p(A0+1)+c
B0=p(a+1)+b
B1=p(B0)+c
B2=p(B0+1)+c
ProcedureReturn lerp(w,lerp(v,lerp(u,grad(p(A1),x,y,z),
grad(p(B1),x-1,y,z)),
lerp(u,grad(p(A2),x,y-1,z),
grad(p(B2),x-1,y-1,z))),
lerp(v,lerp(u,grad(p(A1+1),x,y,z-1),
grad(p(B1+1),x-1,y,z-1)),
lerp(u,grad(p(A2+1),x,y-1,z-1),
grad(p(B2+1),x-1,y-1,z-1))))
EndProcedure
If OpenConsole()
PrintN("noise(3.14,42,7) => "+StrD(noise(3.14,42,7),17))
Input()
EndIf
|
http://rosettacode.org/wiki/Perfect_totient_numbers | Perfect totient numbers | Generate and show here, the first twenty Perfect totient numbers.
Related task
Totient function
Also see
the OEIS entry for perfect totient numbers.
mrob list of the first 54
| #PL.2FI | PL/I | perfectTotient: procedure options(main);
gcd: procedure(aa, bb) returns(fixed);
declare (aa, bb, a, b, c) fixed;
a = aa;
b = bb;
do while(b ^= 0);
c = a;
a = b;
b = mod(c, b);
end;
return(a);
end gcd;
totient: procedure(n) returns(fixed);
declare (i, n, s) fixed;
s = 0;
do i=1 to n-1;
if gcd(n,i) = 1 then s = s+1;
end;
return(s);
end totient;
perfect: procedure(n) returns(bit);
declare (n, x, sum) fixed;
sum = 0;
x = n;
do while(x > 1);
x = totient(x);
sum = sum + x;
end;
return(sum = n);
end perfect;
declare (n, seen) fixed;
seen = 0;
do n=3 repeat(n+2) while(seen<20);
if perfect(n) then do;
put edit(n) (F(5));
seen = seen+1;
if mod(seen,10) = 0 then put skip;
end;
end;
end perfectTotient; |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card must have a pip value and a suit value which constitute the unique value of the card.
Related tasks:
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Poker hand_analyser
Go Fish
| #Java | Java | public enum Pip { Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace } |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
| #Icon_and_Unicon | Icon and Unicon | procedure pi (q, r, t, k, n, l)
first := "yes"
repeat { # infinite loop
if (4*q+r-t < n*t) then {
suspend n
if (\first) := &null then suspend "."
# compute and update variables for next cycle
nr := 10*(r-n*t)
n := ((10*(3*q+r)) / t) - 10*n
q *:= 10
r := nr
} else {
# compute and update variables for next cycle
nr := (2*q+r)*l
nn := (q*(7*k+2)+r*l) / (t*l)
q *:= k
t *:= l
l +:= 2
k +:= 1
n := nn
r := nr
}
}
end
procedure main ()
every (writes (pi (1,0,1,1,3,3)))
end |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points for that turn and their turn finishes with play passing to the next player.
Holding: the player's score for that round is added to their total and becomes safe from the effects of throwing a 1 (one). The player's turn finishes with play passing to the next player.
Task
Create a program to score for, and simulate dice throws for, a two-person game.
Related task
Pig the dice game/Player
| #Python | Python | #!/usr/bin/python3
'''
See: http://en.wikipedia.org/wiki/Pig_(dice)
This program scores and throws the dice for a two player game of Pig
'''
from random import randint
playercount = 2
maxscore = 100
safescore = [0] * playercount
player = 0
score=0
while max(safescore) < maxscore:
rolling = input("Player %i: (%i, %i) Rolling? (Y) "
% (player, safescore[player], score)).strip().lower() in {'yes', 'y', ''}
if rolling:
rolled = randint(1, 6)
print(' Rolled %i' % rolled)
if rolled == 1:
print(' Bust! you lose %i but still keep your previous %i'
% (score, safescore[player]))
score, player = 0, (player + 1) % playercount
else:
score += rolled
else:
safescore[player] += score
if safescore[player] >= maxscore:
break
print(' Sticking with %i' % safescore[player])
score, player = 0, (player + 1) % playercount
print('\nPlayer %i wins with a score of %i' %(player, safescore[player])) |
http://rosettacode.org/wiki/Pernicious_numbers | Pernicious numbers | A pernicious number is a positive integer whose population count is a prime.
The population count is the number of ones in the binary representation of a non-negative integer.
Example
22 (which is 10110 in binary) has a population count of 3, which is prime, and therefore
22 is a pernicious number.
Task
display the first 25 pernicious numbers (in decimal).
display all pernicious numbers between 888,888,877 and 888,888,888 (inclusive).
display each list of integers on one line (which may or may not include a title).
See also
Sequence A052294 pernicious numbers on The On-Line Encyclopedia of Integer Sequences.
Rosetta Code entry population count, evil numbers, odious numbers.
| #Kotlin | Kotlin | // version 1.0.5-2
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun getPopulationCount(n: Int): Int {
if (n <= 0) return 0
var nn = n
var sum = 0
while (nn > 0) {
sum += nn % 2
nn /= 2
}
return sum
}
fun isPernicious(n: Int): Boolean = isPrime(getPopulationCount(n))
fun main(args: Array<String>) {
var n = 1
var count = 0
println("The first 25 pernicious numbers are:\n")
do {
if (isPernicious(n)) {
print("$n ")
count++
}
n++
}
while (count < 25)
println("\n")
println("The pernicious numbers between 888,888,877 and 888,888,888 inclusive are:\n")
for (i in 888888877..888888888) {
if (isPernicious(i)) print("$i ")
}
} |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #NewLISP | NewLISP |
(define (pick-random-element R)
(nth (rand (length R)) R))
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Nim | Nim | import random
randomize()
let ls = @["foo", "bar", "baz"]
echo sample(ls) |
http://rosettacode.org/wiki/Phrase_reversals | Phrase reversals | Task
Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
Reverse the characters of the string.
Reverse the characters of each individual word in the string, maintaining original word order within the string.
Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Phix | Phix | with javascript_semantics
constant test = "rosetta code phrase reversal",
fmt = """
The original phrase as given: %s
1. Reverse the entire phrase: %s
2. Reverse words, same order: %s
3. Reverse order, same words: %s
"""
printf(1,fmt,{test,
reverse(test),
join(apply(split(test),reverse)),
join(reverse(split(test)))})
|
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
There are various ways to calculate !n.
Task
Create a named function/method/subroutine/... to generate derangements of the integers 0..n-1, (or 1..n if you prefer).
Generate and show all the derangements of 4 integers using the above routine.
Create a function that calculates the subfactorial of n, !n.
Print and show a table of the counted number of derangements of n vs. the calculated !n for n from 0..9 inclusive.
Optional stretch goal
Calculate !20
Related tasks
Anagrams/Deranged anagrams
Best shuffle
Left_factorials
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import algorithm, sequtils, strformat, strutils, tables
iterator derangements[T](a: openArray[T]): seq[T] =
var perm = @a
while true:
if not perm.nextPermutation():
break
block checkDerangement:
for i, val in a:
if perm[i] == val: break checkDerangement
yield perm
proc `!`(n: Natural): Natural =
if n <= 1: return 1 - n
result = (n - 1) * (!(n - 1) + !(n - 2))
echo "Derangements of 1 2 3 4:"
for d in [1, 2, 3, 4].derangements():
echo d.join(" ")
echo "\nNumber of derangements:"
echo "n counted calculated"
echo "- ------- ----------"
for n in 0..9:
echo &"{n} {toSeq(derangements(toSeq(1..n))).len:>6} {!n:>6}"
echo "\n!20 = ", !20 |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #Racket | Racket |
#lang racket
(define (add-at l i x)
(if (zero? i) (cons x l) (cons (car l) (add-at (cdr l) (sub1 i) x))))
(define (permutations l)
(define (loop l)
(cond [(null? l) '(())]
[else (for*/list ([(p i) (in-indexed (loop (cdr l)))]
[i ((if (odd? i) identity reverse)
(range (add1 (length p))))])
(add-at p i (car l)))]))
(for/list ([p (loop (reverse l))] [i (in-cycle '(1 -1))]) (cons i p)))
(define (show-permutations l)
(printf "Permutations of ~s:\n" l)
(for ([p (permutations l)])
(printf " ~a (~a)\n" (apply ~a (add-between (cdr p) ", ")) (car p))))
(for ([n (in-range 3 5)]) (show-permutations (range n)))
|
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs of three items, in order of generation here.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutations where adjacent items are swapped, but from this discussion adjacency is not a requirement.
References
Steinhaus–Johnson–Trotter algorithm
Johnson-Trotter Algorithm Listing All Permutations
Heap's algorithm
[1] Tintinnalogia
Related tasks
Matrix arithmetic
Gray code
| #Raku | Raku | sub insert($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. +@xs) }
sub order($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }
multi perms([]) {
[] => +1
}
multi perms([$x, *@xs]) {
perms(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(+1,-1) xx *
}
.say for perms([0..2]); |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Ursala | Ursala | #import std
#import nat
#import flo
treatment_group = <85,88,75,66,25,29,83,39,97>
control_group = <68,41,10,49,16,65,32,92,28,98>
f = # returns the fractions of alternative mean differences above and below the actual
float~*; -+
vid^~G(plus,~&)+ (not fleq@rlX)*|@htX; ~~ float+ length,
minus*+ mean^~*C/~& ^DrlrjXS(~&l,choices)^/-- length@l+-
#show+
t = --* *-'%'@lrNCC printf/$'%0.2f' times/$100. f(treatment_group,control_group) |
http://rosettacode.org/wiki/Permutation_test | Permutation test | Permutation test
You are encouraged to solve this task according to the task description, using any language you may know.
A new medical treatment was tested on a population of
n
+
m
{\displaystyle n+m}
volunteers, with each volunteer randomly assigned either to a group of
n
{\displaystyle n}
treatment subjects, or to a group of
m
{\displaystyle m}
control subjects.
Members of the treatment group were given the treatment,
and members of the control group were given a placebo.
The effect of the treatment or placebo on each volunteer
was measured and reported in this table.
Table of experimental results
Treatment group
Control group
85
68
88
41
75
10
66
49
25
16
29
65
83
32
39
92
97
28
98
Write a program that performs a
permutation test to judge
whether the treatment had a significantly stronger effect than the
placebo.
Do this by considering every possible alternative assignment from the same pool of volunteers to a treatment group of size
n
{\displaystyle n}
and a control group of size
m
{\displaystyle m}
(i.e., the same group sizes used in the actual experiment but with the group members chosen differently), while assuming that each volunteer's effect remains constant regardless.
Note that the number of alternatives will be the binomial coefficient
(
n
+
m
n
)
{\displaystyle {\tbinom {n+m}{n}}}
.
Compute the mean effect for each group and the difference in means between the groups in every case by subtracting the mean of the control group from the mean of the treatment group.
Report the percentage of alternative groupings for which the difference in means is less or equal to the actual experimentally observed difference in means, and the percentage for which it is greater.
Note that they should sum to 100%.
Extremely dissimilar values are evidence of an effect not entirely due
to chance, but your program need not draw any conclusions.
You may assume the experimental data are known at compile time if
that's easier than loading them at run time. Test your solution on the
data given above.
| #Wren | Wren | import "/fmt" for Fmt
var data = [85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
var pick // recursive
pick = Fn.new { |at, remain, accu, treat|
if (remain == 0) return (accu > treat) ? 1 : 0
return pick.call(at-1, remain-1, accu + data[at-1], treat) +
((at > remain) ? pick.call(at-1, remain, accu, treat) : 0)
}
var treat = 0
var total = 1
for (i in 0..8) treat = treat + data[i]
for (i in 19..11) total = total * i
for (i in 9..1) total = total / i
var gt = pick.call(19, 9, 0, treat)
var le = (total - gt).truncate
Fmt.print("<= : $f\% $d", 100 * le / total, le)
Fmt.print(" > : $f\% $d", 100 * gt / total, gt) |
http://rosettacode.org/wiki/Percentage_difference_between_images | Percentage difference between images | basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The expected difference for these two images is 1.62125%
| #Julia | Julia | using Images, FileIO, Printf
absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue))
function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T
size(A) != size(B) && throw(ArgumentError("images must be same-size"))
s = zero(T)
for (a, b) in zip(A, B)
s += absdiff(a, b)
end
return 100s / 3prod(size(A))
end
img50 = load("data/lenna50.jpg") |> Matrix{RGB{Float64}};
img100 = load("data/lenna100.jpg") |> Matrix{RGB{Float64}};
d = pctdiff(img50, img100)
@printf("Percentage difference: %.4f%%\n", d) |
http://rosettacode.org/wiki/Percentage_difference_between_images | Percentage difference between images | basic bitmap storage
Useful for comparing two JPEG images saved with a different compression ratios.
You can use these pictures for testing (use the full-size version of each):
50% quality JPEG
100% quality JPEG
link to full size 50% image
link to full size 100% image
The expected difference for these two images is 1.62125%
| #Kotlin | Kotlin | // version 1.2.10
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.math.abs
fun getDifferencePercent(img1: BufferedImage, img2: BufferedImage): Double {
val width = img1.width
val height = img1.height
val width2 = img2.width
val height2 = img2.height
if (width != width2 || height != height2) {
val f = "(%d,%d) vs. (%d,%d)".format(width, height, width2, height2)
throw IllegalArgumentException("Images must have the same dimensions: $f")
}
var diff = 0L
for (y in 0 until height) {
for (x in 0 until width) {
diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y))
}
}
val maxDiff = 3L * 255 * width * height
return 100.0 * diff / maxDiff
}
fun pixelDiff(rgb1: Int, rgb2: Int): Int {
val r1 = (rgb1 shr 16) and 0xff
val g1 = (rgb1 shr 8) and 0xff
val b1 = rgb1 and 0xff
val r2 = (rgb2 shr 16) and 0xff
val g2 = (rgb2 shr 8) and 0xff
val b2 = rgb2 and 0xff
return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2)
}
fun main(args: Array<String>) {
val img1 = ImageIO.read(File("Lenna50.jpg"))
val img2 = ImageIO.read(File("Lenna100.jpg"))
val p = getDifferencePercent(img1, img2)
println("The percentage difference is ${"%.6f".format(p)}%")
} |
http://rosettacode.org/wiki/Pentomino_tiling | Pentomino tiling | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I
I L N Y
FF I L NN PP TTT V W X YY ZZ
FF I L N PP T U U V WW XXX Y Z
F I LL N P T UUU VVV WW X Y ZZ
A Pentomino tiling is an example of an exact cover problem and can take on many forms.
A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered
by the 12 pentomino shapes, without overlaps, with every shape only used once.
The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.
Task
Create an 8 by 8 tiling and print the result.
Example
F I I I I I L N
F F F L L L L N
W F - X Z Z N N
W W X X X Z N V
T W W X - Z Z V
T T T P P V V V
T Y - P P U U U
Y Y Y Y P U - U
Related tasks
Free polyominoes enumeration
| #zkl | zkl | fcn printResult
{ foreach row in (grid){ row.apply(symbols.get).concat(" ").println() } }
fcn tryPlaceOrientation(o, R,C, shapeIndex){
foreach ro,co in (o){ r,c:=R+ro, C+co;
if(r<0 or r>=nRows or c<0 or c>=nCols or grid[r][c]!=-1) return(False);
}
grid[R][C]=shapeIndex; foreach ro,co in (o){ grid[R+ro][C+co]=shapeIndex }
True
}
fcn removeOrientation(o, r,c)
{ grid[r][c]=-1; foreach ro,co in (o){ grid[r+ro][c+co]=-1 } }
fcn solve(pos,numPlaced){
if(numPlaced==target) return(True);
row,col:=pos.divr(nCols);
if(grid[row][col]!=-1) return(solve(pos+1,numPlaced));
foreach i in (shapes.len()){
if(not placed[i]){
foreach orientation in (shapes[i]){
if(not tryPlaceOrientation(orientation, row,col, i)) continue;
placed[i]=True;
if(solve(pos+1,numPlaced+1)) return(True);
removeOrientation(orientation, row,col);
placed[i]=False;
}
}
}
False
} |
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.