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/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 Luca... | #C | C | #include "stdio.h"
#include "math.h"
int perfect(int n) {
int max = (int)sqrt((double)n) + 1;
int tot = 1;
int i;
for (i = 2; i < max; i++)
if ( (n % i) == 0 ) {
tot += i;
int q = n / i;
if (q > i)
tot += q;
}
return tot == n;... |
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
{\disp... | #Raku | Raku | sub R($n, $p) { [+] ((rand < $p) xx $n).squish }
say 't= ', constant t = 100;
for .1, .3 ... .9 -> $p {
say "p= $p, K(p)= {$p*(1-$p)}";
for 10, 100, 1000 -> $n {
printf " R(%6d, p)= %f\n", $n, t R/ [+] R($n, $p)/$n xx t
}
} |
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
{\disp... | #Sidef | Sidef | func R(n,p) {
n.of { 1.rand < p ? 1 : 0}.sum;
}
const t = 100;
say ('t=', t);
range(.1, .9, .2).each { |p|
printf("p= %f, K(p)= %f\n", p, p*(1-p));
[10, 100, 1000].each { |n|
printf (" R(n, p)= %f\n", t.of { R(n, p) }.sum/n / t);
}
} |
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 Uni... | #BBC_BASIC | BBC BASIC | DIM List%(3)
List%() = 1, 2, 3, 4
FOR perm% = 1 TO 24
FOR i% = 0 TO DIM(List%(),1)
PRINT List%(i%);
NEXT
PRINT
PROC_NextPermutation(List%())
NEXT
END
DEF PROC_NextPermutation(A%())
LOCAL first, last, elementcount, pos
elementcou... |
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 ... | #JavaScript | JavaScript | (() => {
'use strict';
// shuffleCycleLength :: Int -> Int
const shuffleCycleLength = deckSize =>
firstCycle(shuffle, range(1, deckSize))
.all.length;
// shuffle :: [a] -> [a]
const shuffle = xs =>
concat(zip.apply(null, splitAt(div(length(xs), 2), xs)));
// firstyc... |
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
... | #Python | Python | def perlin_noise(x, y, z):
X = int(x) & 255 # FIND UNIT CUBE THAT
Y = int(y) & 255 # CONTAINS POINT.
Z = int(z) & 255
x -= int(x) # FIND RELATIVE X,Y,Z
y -= int(y) # OF POINT IN CUBE.
z -= int(z)
... |
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.2FM | PL/M | 100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = ... |
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
| #Python | Python | from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = φ(n)
par... |
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 mu... | #JavaScript | JavaScript | function Card(pip, suit) {
this.pip = pip;
this.suit = suit;
this.toString = function () {
return this.pip + ' ' + this.suit;
};
}
function Deck() {
var pips = '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' ');
var suits = 'Clubs Hearts Spades Diamonds'.split(' ');
this.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 ...... | #J | J | pi=: 3 :0
echo"0 '3.1'
i=. 0
while. i=. i + 1 do.
echo -/ 1 10 * <.@o. 10x ^ 1 0 + i
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 th... | #Racket | Racket |
#lang racket
(define (pig-the-dice #:print? [print? #t] . players)
(define prn (if print? (λ xs (apply printf xs) (flush-output)) void))
(define names (for/list ([p players] [n (in-naturals 1)]) n))
(define points (for/list ([p players]) (box 0)))
(with-handlers ([(negate exn?) identity])
(for ([nm (in-... |
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 pe... | #Ksh | Ksh |
#!/bin/ksh
# Positive integer whose population count is a prime
# # Variables:
#
integer PNUM=25 MINN=888888877 MAXN=888888888
# # Functions:
#
# # Function _dec2bin(n) - return binary representation of decimal n
#
function _dec2bin {
typeset _n ; integer _n=$1
typeset _base ; integer _base=2
typeset _q _r _... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Objeck | Objeck | values := [1, 2, 3];
value := values[(Float->Random() * 100.0)->As(Int) % values->Size()]; |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #OCaml | OCaml | let list_rand lst =
let len = List.length lst in
List.nth lst (Random.int len) |
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, maintaini... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
"Rosetta Code Phrase Reversal" dup print nl
dup reverse print nl
split dup reverse len for . pop swap print " " print endfor . nl
len for . pop swap reverse print " " print endfor . |
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, maintaini... | #PHP | PHP | <?php
// Initialize a variable with the input desired
$strin = "rosetta code phrase reversal";
// Show user what original input was
echo "Input: ".$strin."\n";
// Show the full input reversed
echo "Reversed: ".strrev($strin)."\n";
// reverse the word letters in place
$str_words_reversed = "";
$temp = explode(" ",... |
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.
The... | #PARI.2FGP | PARI/GP | derangements(n)=if(n,round(n!/exp(1)),1);
derange(n)={
my(v=[[]],tmp);
for(level=1,n,
tmp=List();
for(i=1,#v,
for(k=1,n,
if(k==level, next);
for(j=1,level-1,if(v[i][j]==k, next(2)));
listput(tmp, concat(v[i],k))
)
);
v=Vec(tmp)
);
v
};
derange(4)
for(n=0,9,print("!"n" = "#derange(n)" = "de... |
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 ... | #REXX | REXX | /*REXX program generates all permutations of N different objects by swapping. */
parse arg things bunch . /*obtain optional arguments from the CL*/
if things=='' | things=="," then things=4 /*Not specified? Then use the default.*/
if bunch =='' | bunch =="," then bunch =things... |
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... | #zkl | zkl | fcn permutationTest(a,b){
ab := a.extend(b);
tObs := a.sum(0);
combs := Utils.Helpers.pickNFrom(a.len(),ab); // 92,378
under := combs.reduce('wrap(sum,perm){ sum+(perm.sum(0) <= tObs) },0);
100.0 * under / combs.len();
}
treatmentGroup := T(85, 88, 75, 66, 25, 29, 83, 39, 97);
controlGroup := T(... |
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... | #Lua | Lua | Bitmap.loadPPM = function(self, filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
self:clear( {0,0,0} )
for y = 1, se... |
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 Luca... | #C.23 | C# | static void Main(string[] args)
{
Console.WriteLine("Perfect numbers from 1 to 33550337:");
for (int x = 0; x < 33550337; x++)
{
if (IsPerfect(x))
Console.WriteLine(x + " is perfect.");
}
Console.ReadLine();
}
static bool IsPerfect(int num)
{
int sum = 0;
for (int i = 1; i < num; i++)
{
if (num % ... |
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
{\disp... | #Tcl | Tcl | proc randomString {length probability} {
for {set s ""} {[string length $s] < $length} {} {
append s [expr {rand() < $probability}]
}
return $s
}
# By default, [regexp -all] gives the number of times that the RE matches
proc runs {str} {
regexp -all {1+} $str
}
# Compute the mean run density
proc m... |
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 Uni... | #Bracmat | Bracmat | ( perm
= prefix List result original A Z
. !arg:(?.)
| !arg:(?prefix.?List:?original)
& :?result
& whl
' ( !List:%?A ?Z
& !result perm$(!prefix !A.!Z):?result
& !Z !A:~!original:?List
)
& !result
)
& out$(perm$(.a 2 "]" u+z); |
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 ... | #jq | jq | def perfect_shuffle:
. as $a
| if (length % 2) == 1 then "cannot perform perfect shuffle on odd-length array" | error
else (length / 2) as $mid
| reduce range(0; $mid) as $i (null;
.[2*$i] = $a[$i]
| .[2*$i + 1] = $a[$mid+$i] )
end;
# How many iterations of f are required to get back to... |
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 ... | #Julia | Julia | using Printf
function perfect_shuffle(a::Array)::Array
if isodd(length(a)) error("cannot perform perfect shuffle on odd-length array") end
rst = zeros(a)
mid = div(length(a), 2)
for i in 1:mid
rst[2i-1], rst[2i] = a[i], a[mid+i]
end
return rst
end
function count_perfect_shuffles(de... |
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
... | #Racket | Racket | #lang racket
(define (floor-to-255 x)
(bitwise-and (exact-floor x) #xFF))
(define (fade t)
(* t t t (+ 10 (* t (- (* t 6) 15)))))
(define (lerp t a b)
(+ a (* t (- b a))))
;; CONVERT LO 4 BITS OF HASH CODE INTO 12 GRADIENT DIRECTIONS.
(define (grad hsh x y z)
(define h (bitwise-and hsh #x0F))
(define u ... |
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
| #Quackery | Quackery | [ 0 over
[ dup 1 != while
totient
dup dip +
again ]
drop = ] is perfecttotient ( n --> b )
[ [] 1
[ dup perfecttotient if
[ dup dip join ]
2 +
over size 20 =
until ] drop ] is task ( --> )
|
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
| #Racket | Racket |
#lang racket
(require math/number-theory)
(define (tot n)
(match n
[1 0]
[n (define t (totient n))
(+ t (tot t))]))
(define (perfect? n)
(= n (tot n)))
(define-values (ns i)
(for/fold ([ns '()] [i 0])
([n (in-naturals 1)]
#:break (= i 20)
#:when (perfec... |
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 mu... | #Julia | Julia |
type DeckDesign{T<:Integer,U<:String}
rlen::T
slen::T
ranks::Array{U,1}
suits::Array{U,1}
hlen::T
end
type Deck{T<:Integer}
cards::Array{T,1}
design::DeckDesign
end
Deck(n::Integer, des::DeckDesign) = Deck([n], des)
function pokerlayout()
r = [map(string, 2:10), "J", "Q", "K", "A... |
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 ...... | #Java | Java | import java.math.BigInteger ;
public class Pi {
final BigInteger TWO = BigInteger.valueOf(2) ;
final BigInteger THREE = BigInteger.valueOf(3) ;
final BigInteger FOUR = BigInteger.valueOf(4) ;
final BigInteger SEVEN = BigInteger.valueOf(7) ;
BigInteger q = BigInteger.ONE ;
BigInteger r = BigInteger.ZERO ... |
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 th... | #Raku | Raku | constant DIE = 1..6;
sub MAIN (Int :$players = 2, Int :$goal = 100) {
my @safe = 0 xx $players;
for |^$players xx * -> $player {
say "\nOK, player #$player is up now.";
my $safe = @safe[$player];
my $ante = 0;
until $safe + $ante >= $goal or
prompt("#$player, you have $safe + $ante = {$safe+$ante}. R... |
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 pe... | #Lua | Lua | -- Test primality by trial division
function isPrime (x)
if x < 2 then return false end
if x < 4 then return true end
if x % 2 == 0 then return false end
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
-- Take decimal number, return binary string
f... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Oforth | Oforth | : pickRand(l) l size rand l at ; |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Ol | Ol |
(import (otus random!))
(define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))
(print (list-ref x (rand! (length x))))
|
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, maintaini... | #Picat | Picat | import util.
go =>
S = "rosetta code phrase reversal",
println(S),
println(reverse(S)),
println([reverse(W) : W in S.split()].join(' ')),
println(reverse(S.split()).join(' ')),
nl. |
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, maintaini... | #PicoLisp | PicoLisp | (let (S (chop "rosetta code phrase reversal") L (split S " "))
(prinl (reverse S))
(prinl (glue " " (mapcar reverse L)))
(prinl (glue " " (reverse L))) ) |
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.
The... | #Perl | Perl | sub d {
# compare this with the deranged() sub to see how to turn procedural
# code into functional one ('functional' as not in 'understandable')
$#_ ? map d([ @{$_[0]}, $_[$_] ], @_[1 .. $_-1, $_+1 .. $#_ ]),
grep { $_[$_] != @{$_[0]} } 1 .. $#_
: $_[0]
}
s... |
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 ... | #Ruby | Ruby | def perms(n)
p = Array.new(n+1){|i| -i}
s = 1
loop do
yield p[1..-1].map(&:abs), s
k = 0
for i in 2..n
k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs
end
for i in 1...n
k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs
end
break if k.... |
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... | #Liberty_BASIC | Liberty BASIC |
now =time$( "seconds")
nomainwin
WindowWidth = 1620
WindowHeight = 660
open "jpeg.dll" for dll as #j ' "JPEG.DLL copyright Alyce Watson, 2003. "
open "RC Image Comparison- difference shown as 20 times abs( pixel_difference." for graphics_nf_nsb as #1
#1 "trapclose [quit]"
#1 "down ; fill black"
... |
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 Luca... | #C.2B.2B | C++ | #include <iostream>
using namespace std ;
int divisor_sum( int number ) {
int sum = 0 ;
for ( int i = 1 ; i < number ; i++ )
if ( number % i == 0 )
sum += i ;
return sum;
}
int main( ) {
cout << "Perfect numbers from 1 to 33550337:\n" ;
for ( int num = 1 ; num < 33550337 ; num++... |
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
{\disp... | #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var rand = Random.new()
var RAND_MAX = 32767
// just generate 0s and 1s without storing them
var runTest = Fn.new { |p, len, runs|
var cnt = 0
var thresh = (p * RAND_MAX).truncate
for (r in 0...runs) {
var x = 0
var i = len
while (... |
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 Uni... | #C | C |
#include <stdio.h>
int main (int argc, char *argv[]) {
//here we check arguments
if (argc < 2) {
printf("Enter an argument. Example 1234 or dcba:\n");
return 0;
}
//it calculates an array's length
int x;
for (x = 0; argv[1][x] != '\0'; x++);
//buble sort the array
int f, v, m;
for... |
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 ... | #Kotlin | Kotlin | // version 1.1.2
fun areSame(a: IntArray, b: IntArray): Boolean {
for (i in 0 until a.size) if (a[i] != b[i]) return false
return true
}
fun perfectShuffle(a: IntArray): IntArray {
var b = IntArray(a.size)
val hSize = a.size / 2
for (i in 0 until hSize) b[i * 2] = a[i]
var j = 1
for (i 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
... | #Raku | Raku | constant @p = map {:36($_)}, flat <
47 4G 3T 2J 2I F 3N D 5L 2N 2O 1H 5E 6H 7 69 3W 10 2V U 1X 3Y 8 2R 11 6O L A N
5A 6 44 6V 3C 6I 23 0 Q 5H 1Q 2M 70 63 5N 39 Z B W 1L 4X X 2G 6L 45 1K 2F 4U K
3H 3S 4R 4O 1W 4V 22 4L 1Z 3Q 3V 1C R 4M 25 42 4E 6F 2B 33 6D 3E 1O 5V 3P 6E 64
2X 2K 15 1J 1A 6T 14 6S 2U 3Z 1I 1T P 1R 4H 1 ... |
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
| #Raku | Raku | use Prime::Factor;
my \𝜑 = lazy 0, |(1..*).hyper.map: -> \t { t * [*] t.&prime-factors.squish.map: 1 - 1/* }
my \𝜑𝜑 = Nil, |(3, *+2 … *).grep: -> \p { p == sum 𝜑[p], { 𝜑[$_] } … 1 };
put "The first twenty Perfect totient numbers:\n", 𝜑𝜑[1..20]; |
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
| #REXX | REXX | /*REXX program calculates and displays the first N perfect totient numbers. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
@.= . ... |
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 mu... | #K | K | v:"A23456789TJQK" / values
s:"SHCD" / suites
/ create a new deck
newdeck:{deck::,/s,'\:v}
newdeck(); |
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 ...... | #JavaScript | JavaScript | let q = 1n, r = 180n, t = 60n, i = 2n;
for (;;) {
let y = (q*(27n*i-12n)+5n*r)/(5n*t);
let u = 3n*(3n*i+1n)*(3n*i+2n);
r = 10n*u*(q*(5n*i-2n)+r-y*t);
q = 10n*q*i*(2n*i-1n);
t = t*u;
i = i+1n;
process.stdout.write(y.toString());
if (i === 3n) { process.stdout.write('.'); }
} |
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 th... | #REXX | REXX | /*REXX program plays "pig the dice game" (any number of CBLFs and/or silicons or HALs).*/
sw= linesize() - 1 /*get the width of the terminal screen,*/
parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments from the CL*/
... |
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 pe... | #Maple | Maple | ispernicious := proc(n::posint)
return evalb(isprime(rhs(Statistics:-Tally(StringTools:-Explode(convert(convert(n, binary), string)))[-1])));
end proc;
print_pernicious := proc(n::posint)
local k, count, list_num;
count := 0;
list_num := [];
for k while count < n do
if ispernicious(k) then
count := ... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #PARI.2FGP | PARI/GP | pick(v)=v[random(#v)+1] |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Pascal_.2F_Delphi_.2F_Free_Pascal | Pascal / Delphi / Free Pascal | Program PickRandomElement (output);
const
s: array [1..5] of string = ('1234', 'ABCDE', 'Charlie', 'XB56ds', 'lala');
begin
randomize;
writeln(s[low(s) + random(length(s))]);
end. |
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, maintaini... | #PL.2FI | PL/I |
reverser: procedure options (main); /* 19 August 2015 */
declare (phrase, r, word) character (100) varying;
declare (start, end) fixed binary;
phrase = 'rosetta code phrase reversal';
put ('The original phrase is: ' || phrase);
put skip list ( '1. ' || reverse(phrase) );
start = 1; r ... |
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, maintaini... | #Plain_TeX | Plain TeX | \def\afterfi#1#2\fi{#2\fi#1}
\def\RevSingleWord#1{\RevSingleWordi{}#1\RSWA\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWB\RSWA}
\def\RevSingleWordi#1#2#3#4#5#6#7#8#9{\RSWgobtoB#9\RSWend\RSWB\RevSingleWordi{#9#8#7#6#5#4#3#2#1}}
\def\RSWend\RSWB\RevSingleWordi#1#2\RSWA{\RSWgobtoA#1}
\def\RSWgobtoA#1\RSWA{}
\def\RSWgobtoB#1\RSWB... |
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.
The... | #Phix | Phix | with javascript_semantics
function deranged(sequence s1, sequence s2)
for i=1 to length(s1) do
if s1[i]==s2[i] then return 0 end if
end for
return 1
end function
function derangements(integer n)
sequence ts = tagset(n)
sequence res = {}
for i=1 to factorial(n) do
sequence s = p... |
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 ... | #Rust | Rust | // Implementation of Heap's algorithm.
// See https://en.wikipedia.org/wiki/Heap%27s_algorithm#Details_of_the_algorithm
fn generate<T, F>(a: &mut [T], output: F)
where
F: Fn(&[T], isize),
{
let n = a.len();
let mut c = vec![0; n];
let mut i = 1;
let mut sign = 1;
output(a, sign);
while i < 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 ... | #Scala | Scala | object JohnsonTrotter extends App {
private def perm(n: Int): Unit = {
val p = new Array[Int](n) // permutation
val pi = new Array[Int](n) // inverse permutation
val dir = new Array[Int](n) // direction = +1 or -1
def perm(n: Int, p: Array[Int], pi: Array[Int], dir: Array[Int]): Unit = {
if ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | img50 = ImageData@Import[NotebookDirectory[] <> "Lenna50.jpg"];
img100 = ImageData@Import[NotebookDirectory[] <> "Lenna100.jpg"];
diff = img50 - img100;
Print["Total Difference between both Lenas = ",
Total@Abs@Flatten@diff/Times @@ Dimensions@img50*100, "%"] |
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... | #MATLAB | MATLAB |
% Percentage difference between images
function p = PercentageDifferenceBetweenImages(im1,im2)
if numel(im1)~=numel(im2),
error('Error: images have to be the same size');
end
d = abs(single(im1) - single(im2))./255;
p = sum(d(:))./numel(im1)*100;
disp(['Percentage difference between images is: ', num2str(p)... |
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 Luca... | #Clojure | Clojure | (defn proper-divisors [n]
(if (< n 4)
[1]
(->> (range 2 (inc (quot n 2)))
(filter #(zero? (rem n %)))
(cons 1))))
(defn perfect? [n]
(= (reduce + (proper-divisors n)) n)) |
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
{\disp... | #zkl | zkl | fcn run_test(p,len,runs){
cnt:=0; do(runs){
pv:=0; do(len){
v:=0 + ((0.0).random(1.0)<p); // 0 or 1, value of V[n]
cnt += (pv<v); // if v is 1 & prev v was zero, inc cnt
pv = v;
}
}
return(cnt.toFloat() / runs / len);
} |
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 Uni... | #C.23 | C# | public static class Extension
{
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values) where T : IComparable<T>
{
if (values.Count() == 1)
return new[] { values };
return values.SelectMany(v => Permutations(values.Where(x => x.CompareTo(v) != 0)), (v, p... |
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 ... | #Lua | Lua | -- Perform weave shuffle
function shuffle (cards)
local pile1, pile2 = {}, {}
for card = 1, #cards / 2 do table.insert(pile1, cards[card]) end
for card = (#cards / 2) + 1, #cards do table.insert(pile2, cards[card]) end
cards = {}
for card = 1, #pile1 do
table.insert(cards, pile1[card])
... |
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
... | #REXX | REXX | /*REXX program implements a Perlin noise algorithm of a point in 3D─space. */
_= 97a0895b5a0f830dc95f6035c2e907e18c24671e458e086325f0150a17be0694f778ea4b001ac53e5efcdbcb75230b2039b12158ed953857ae147d88aba844af,
||4aa547868b301ba64d929ee7536fe57a3cd385e6dc695c29372ef528f4668f3641193fa101d85049d14c84bbd0591... |
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
| #Ring | Ring |
perfect = []
n = 1
while len(perfect)<20
totnt = n
tsum = 0
while totnt!=1
totnt = totient(totnt)
tsum = tsum + totnt
end
if tsum=n
add(perfect,n)
ok
n = n + 2
end
see "The first 20 perfect totient numbers are:" + nl
showarray(perfect)
fu... |
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
| #Ruby | Ruby | require "prime"
class Integer
def φ
prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) }
end
def perfect_totient?
f, sum = self, 0
until f == 1 do
f = f.φ
sum += f
end
self == sum
end
end
puts (1..).lazy.select(&:perfect_totient?).first(20).join(",... |
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 mu... | #Kotlin | Kotlin | const val FACES = "23456789TJQKA"
const val SUITS = "shdc"
fun createDeck(): List<String> {
val cards = mutableListOf<String>()
FACES.forEach { face -> SUITS.forEach { suit -> cards.add("$face$suit") } }
return cards
}
fun dealTopDeck(deck: List<String>, n: Int) = deck.take(n)
fun dealBottomDeck(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 ...... | #jq | jq | # The Gibbons spigot, in the mold of the [[#Groovy]] and [[#Python]] programs shown on this page.
# The "bigint" functions needed are:
# long_minus long_add long_multiply long_div
def pi_spigot:
# S is the sixtuple:
# q r t k n l
# 0 1 2 3 4 5
def long_l... |
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 th... | #Ring | Ring |
# Project : Pig the dice game
numPlayers = 2
maxScore = 100
safescore = list(numPlayers)
while true
rolling = ""
for player = 1 to numPlayers
score = 0
while safeScore[player] < maxScore
see "Player " + player + " Rolling? (Y) "
... |
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 pe... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | popcount[n_Integer] := IntegerDigits[n, 2] // Total
perniciousQ[n_Integer] := popcount[n] // PrimeQ
perniciouscount = 0;
perniciouslist = {};
i = 0;
While[perniciouscount < 25,
If[perniciousQ[i], AppendTo[perniciouslist, i]; perniciouscount++];
i++]
Print["first 25 pernicious numbers"]
perniciouslist
(*******)
pe... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Perl | Perl | my @array = qw(a b c);
print $array[ rand @array ]; |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Phix | Phix | with javascript_semantics
constant s = {1,2.5,"three",{4,{"4 as well"}}}
pp(s[rand(length(s))])
|
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, maintaini... | #PowerShell | PowerShell |
function reverse($a, $sep = "") {
if($a.Length -gt 0) {
$a = $a[($a.Length -1)..0] -join $sep
}
$a
}
$line = "rosetta code phrase reversal"
$task1 = reverse $line
$task2 = ($line -split " " | foreach{ reverse $_ }) -join " "
$task3 = reverse ($line -split " ") " "
$task1
$task2
$task3
|
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, maintaini... | #PureBasic | PureBasic | #TEXT="rosetta code phrase reversal"
If OpenConsole("rosetta code phrase reversal")
Define idx.i=1, txt.s=""
Print(~"Original:\t\t")
PrintN(#TEXT)
Print(~"Reversed:\t\t")
PrintN(ReverseString(#TEXT))
Print(~"Reversed words:\t\t")
txt=StringField(#TEXT,idx," ")
While Len(txt)
Print(Revers... |
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.
The... | #Picat | Picat | import util.
go =>
foreach(N in 0..9)
println([N,num_derangements=num_derangements(N), subfactorial=subfactorial(N), subfactorial2=subfactorial2(N)])
end,
println(["!20", subfactorial(20)]),
println(["!20 approx", subfactorial2(20)]),
println("subfactorial0..30"=[subfactorial(N) : N in 0..30 ]),... |
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 ... | #Sidef | Sidef | func perms(n) {
var perms = [[+1]]
for x in (1..n) {
var sign = -1
perms = gather {
for s,*p in perms {
var r = (0 .. p.len)
take((s < 0 ? r : r.flip).map {|i|
[sign *= -1, p[^i], x, p[i..p.end]]
}...)
}
}
}
perms
}
var n = 4
for ... |
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... | #MAXScript | MAXScript | fn diffImages =
(
local img1 = selectBitmap caption:"Select Image 1"
local img2 = selectBitmap caption:"Select Image 2"
local totalDiff = 0
for i in 0 to (img1.height-1) do
(
local img1Row = getPixels img1 [0, i] img1.width
local img2Row = getPixels img2 [0, i] img2.width
for j in 1 to img1.width do
(
... |
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... | #Nim | Nim | import strformat
import imageman
var img50, img100: Image[ColorRGBU]
try:
img50 = loadImage[ColorRGBU]("Lenna50.jpg")
img100 = loadImage[ColorRGBU]("Lenna100.jpg")
except IOError:
echo getCurrentExceptionMsg()
quit QuitFailure
let width = img50.width
let height = img50.height
if img100.width != width or img... |
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 Luca... | #COBOL | COBOL | $set REPOSITORY "UPDATE ON"
IDENTIFICATION DIVISION.
PROGRAM-ID. perfect-main.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION perfect
.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 i PIC 9(8). ... |
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 Uni... | #C.2B.2B | C++ | #include <algorithm>
#include <string>
#include <vector>
#include <iostream>
template<class T>
void print(const std::vector<T> &vec)
{
for (typename std::vector<T>::const_iterator i = vec.begin(); i != vec.end(); ++i)
{
std::cout << *i;
if ((i + 1) != vec.end())
std::cout << ",";
... |
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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | shuffle[deck_] := Apply[Riffle, TakeDrop[deck, Length[deck]/2]];
shuffleCount[n_] := Block[{count=0}, NestWhile[shuffle, shuffle[Range[n]], (count++; OrderedQ[#] )&];count];
Map[shuffleCount, {8, 24, 52, 100, 1020, 1024, 10000}] |
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 ... | #MATLAB | MATLAB | function [New]=PerfectShuffle(Nitems, Nturns)
if mod(Nitems,2)==0 %only if even number
X=1:Nitems; %define deck
for c=1:Nturns %defines one shuffle
X=reshape(X,Nitems/2,2)'; %split the deck in two and stack halves
X=X(:)'; %mix the halves
end
New=X; %result of... |
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
... | #Rust | Rust | fn main() {
println!("{}", noise(3.14, 42.0, 7.0));
}
fn noise(x: f64, y: f64, z: f64) -> f64 {
let x0 = x.floor() as usize & 255;
let y0 = y.floor() as usize & 255;
let z0 = z.floor() as usize & 255;
let x = x - x.floor();
let y = y - y.floor();
let z = z - z.floor();
let u = fade(x);
let v = fade(y);
... |
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
| #Scala | Scala | //List of perfect totients
def isPerfectTotient(num: Int): Boolean = LazyList.iterate(totient(num))(totient).takeWhile(_ != 1).foldLeft(0L)(_+_) + 1 == num
def perfectTotients: LazyList[Int] = LazyList.from(3).filter(isPerfectTotient)
//Totient Function
@tailrec def scrub(f: Long, num: Long): Long = if(num%f == 0) sc... |
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 mu... | #Liberty_BASIC | Liberty BASIC | Dim deckCards(52)
Dim holdCards(1, 1)
Print "The Sorted Deck"
Call sortDeck
Call dealDeck
Print: Print
Print "The Shuffled Deck"
Call shuffleDeck
Call dealDeck
Print: Print
nPlayers = 4
nCards = 5
ct = 0
Redim holdCards(nPlayers, nCards)
Print "Dealing ";nCards;" cards to ";nPlay... |
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 ...... | #Julia | Julia | let prec = precision(BigFloat), spi = "", digit = 1
while true
if digit > lastindex(spi)
prec *= 2
setprecision(prec)
spi = string(big(π))
end
print(spi[digit])
digit += 1
end
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 th... | #Ruby | Ruby | class PigGame
Player = Struct.new(:name, :safescore, :score) do
def bust!() self.score = safescore end
def stay!() self.safescore = score end
def to_s() "#{name} (#{safescore}, #{score})" end
end
def initialize(names, maxscore=100, die_sides=6)
rotation = names.map {|name| Player.new(name,0,0) }... |
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 pe... | #Modula-2 | Modula-2 | MODULE Pernicious;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE IsPrime(x : LONGINT) : BOOLEAN;
VAR i : LONGINT;
BEGIN
IF x<2 THEN RETURN FALSE END;
FOR i:=2 TO x-1 DO
IF x MOD i = 0 THEN RETURN FALSE END
END;
RETURN TRUE
END IsPrime;
PR... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #PHP | PHP | $arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)]; |
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, maintaini... | #Python | Python | >>> phrase = "rosetta code phrase reversal"
>>> phrase[::-1] # Reversed.
'lasrever esarhp edoc attesor'
>>> ' '.join(word[::-1] for word in phrase.split()) # Words reversed.
'attesor edoc esarhp lasrever'
>>> ' '.join(phrase.split()[::-1]) # Word order reversed.
'reversal phrase code rosetta'
... |
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, maintaini... | #Quackery | Quackery | $ "rosetta code phrase reversal"
3 times dup
say "0. " echo$ cr
say "1. " reverse echo$ cr
say "2. " nest$ witheach [ reverse echo$ sp ] cr
say "3. " nest$ reverse witheach [ echo$ sp ] cr |
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.
The... | #PicoLisp | PicoLisp | (load "@lib/simul.l") # For 'permute'
(de derangements (Lst)
(filter
'((L) (not (find = L Lst)))
(permute Lst) ) )
(de subfact (N)
(if (>= 2 N)
(if (= 1 N) 0 1)
(*
(dec N)
(+ (subfact (dec N)) (subfact (- N 2))) ) ) ) |
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 ... | #Swift | Swift | // Implementation of Heap's algorithm.
// See https://en.wikipedia.org/wiki/Heap%27s_algorithm#Details_of_the_algorithm
func generate<T>(array: inout [T], output: (_: [T], _: Int) -> Void) {
let n = array.count
var c = Array(repeating: 0, count: n)
var i = 1
var sign = 1
output(array, sign)
whil... |
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 ... | #Tcl | Tcl | # A simple swap operation
proc swap {listvar i1 i2} {
upvar 1 $listvar l
set tmp [lindex $l $i1]
lset l $i1 [lindex $l $i2]
lset l $i2 $tmp
}
proc permswap {n v1 v2 body} {
upvar 1 $v1 perm $v2 sign
# Initialize
set sign -1
for {set i 0} {$i < $n} {incr i} {
lappend items $i
lappen... |
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... | #OCaml | OCaml | #! /usr/bin/env ocaml
#directory "+glMLite/"
#load "jpeg_loader.cma"
#load "bigarray.cma"
open Jpeg_loader
let () =
let img1, width1, height1, col_comp1, color_space1 = load_img (Filename Sys.argv.(1))
and img2, width2, height2, col_comp2, color_space2 = load_img (Filename Sys.argv.(2)) in
assert(width1 = wid... |
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 Luca... | #CoffeeScript | CoffeeScript | is_perfect_number = (n) ->
do_factors_add_up_to n, 2*n
do_factors_add_up_to = (n, desired_sum) ->
# We mildly optimize here, by taking advantage of
# the fact that the sum_of_factors( (p^m) * x)
# is (1 + ... + p^m-1 + p^m) * sum_factors(x) when
# x is not itself a multiple of p.
p = smallest_prime_fact... |
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 Uni... | #Clojure | Clojure |
user=> (require 'clojure.contrib.combinatorics)
nil
user=> (clojure.contrib.combinatorics/permutations [1 2 3])
((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 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 ... | #Modula-2 | Modula-2 | MODULE PerfectShuffle;
FROM FormatString IMPORT FormatString;
FROM Storage IMPORT ALLOCATE,DEALLOCATE;
FROM SYSTEM IMPORT ADDRESS,TSIZE;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteCard(c : CARDINAL);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
FormatString("%c", buf, c);
WriteString(buf)
END ... |
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
... | #Sidef | Sidef | const p = (%w'47 4G 3T 2J 2I F 3N D 5L 2N 2O 1H 5E 6H 7 69 3W 10 2V U 1X 3Y 8
2R 11 6O L A N 5A 6 44 6V 3C 6I 23 0 Q 5H 1Q 2M 70 63 5N 39 Z B W 1L 4X X 2G
6L 45 1K 2F 4U K 3H 3S 4R 4O 1W 4V 22 4L 1Z 3Q 3V 1C R 4M 25 42 4E 6F 2B 33 6D
3E 1O 5V 3P 6E 64 2X 2K 15 1J 1A 6T 14 6S 2U 3Z 1I 1T P 1R 4H 1 60 28 21 5T 24
3O 57 5... |
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
| #Sidef | Sidef | func perfect_totient({.<=1}, sum=0) { sum }
func perfect_totient( n, sum=0) { __FUNC__(var(t = n.euler_phi), sum + t) }
say (1..Inf -> lazy.grep {|n| perfect_totient(n) == n }.first(20)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.