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_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
| #Swift | Swift | public func totient(n: Int) -> Int {
var n = n
var i = 2
var tot = n
while i * i <= n {
if n % i == 0 {
while n % i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
public struct P... |
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... | #Logo | Logo | make "suits {Diamonds Hearts Clubs Spades}
make "pips {Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King}
to card :n
output (sentence item 1 + modulo :n 13 :pips "of item 1 + int quotient :n 13 :suits)
end
to new.deck
make "deck listtoarray iseq 0 51
make "top 1
end
to swap :i :j :a
local... |
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 ...... | #Kotlin | Kotlin | // version 1.1.2
import java.math.BigInteger
val ZERO = BigInteger.ZERO
val ONE = BigInteger.ONE
val TWO = BigInteger.valueOf(2L)
val THREE = BigInteger.valueOf(3L)
val FOUR = BigInteger.valueOf(4L)
val SEVEN = BigInteger.valueOf(7L)
val TEN = BigInteger.TEN
fun calcPi() {
var nn: BigInteger
var ... |
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... | #Run_BASIC | Run BASIC | numPlayers = 2
maxScore = 100
dim safeScore(numPlayers)
[loop]
for player = 1 to numPlayers
score = 0
while safeScore(player) < maxScore
input "Player ";player;" Rolling? (Y) ";rolling$
if upper$(rolling$) = "Y" then
rolled = int(rnd(0) * 5) + 1
print "Player ";player;" rolled ";roll... |
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... | #Nim | Nim | import strutils
proc count(s: string; sub: char): int =
var i = 0
while true:
i = s.find(sub, i)
if i < 0:
break
inc i
inc result
proc popcount(n: int): int = n.toBin(64).count('1')
const primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61}
var p: seq[int]
var ... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Picat | Picat | go =>
% single element
println(choice=choice(10)), % single element
% From a list of numbers
L = 1..10,
println([choice(L) : _ in 1..10]),
% From a string
S = "pickrandomelement",
println([choice(S) : _ in 1..10]),
nl.
% Pick a random number from 1..N
choice(N) = random(1,N), integer(N) => tru... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #PicoLisp | PicoLisp | (get Lst (rand 1 (length Lst))) |
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... | #Racket | Racket | #lang racket/base
(require
(only-in srfi/13 string-reverse)
(only-in racket/string string-split string-join))
(define (phrase-reversal s)
(list
(string-reverse s)
(string-join (map string-reverse (string-split s)))
(string-join (reverse (string-split s)))))
(for-each displayln (phrase-reversal "roset... |
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... | #Raku | Raku | my $s = 'rosetta code phrase reversal';
put 'Input : ', $s;
put 'String reversed : ', $s.flip;
put 'Each word reversed : ', $s.words».flip;
put 'Word-order reversed : ', $s.words.reverse; |
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... | #PureBasic | PureBasic |
Procedure.q Subfactoral(n)
If n=0:ProcedureReturn 1:EndIf
If n=1:ProcedureReturn 0:EndIf
ProcedureReturn (Subfactoral(n-1)+Subfactoral(n-2))*(n-1)
EndProcedure
factFile.s="factorials.txt"
tempFile.s="temp.txt"
drngFile.s="derangements.txt"
DeleteFile(factFile.s)
DeleteFile(tempFile.s)
DeleteFile(drngFile.s)
n=4
... |
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 ... | #Wren | Wren | var johnsonTrotter = Fn.new { |n|
var p = List.filled(n, 0) // permutation
var q = List.filled(n, 0) // inverse permutation
for (i in 0...n) p[i] = q[i] = i
var d = List.filled(n, -1) // direction = 1 or -1
var sign = 1
var perms = []
var signs = []
var permute // recursive closure
... |
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... | #Perl | Perl | use Image::Imlib2;
my $img1 = Image::Imlib2->load('Lenna50.jpg') || die;
my $img2 = Image::Imlib2->load('Lenna100.jpg') || die;
my $w = $img1->width;
my $h = $img1->height;
my $sum = 0;
for my $x (0..$w-1) {
for my $y (0..$h-1) {
my ($r1, $g1, $b1) = $img1->query_pixel($x, $y);
my ($r2, $g2... |
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... | #Common_Lisp | Common Lisp | (defun perfectp (n)
(= n (loop for i from 1 below n when (= 0 (mod n i)) sum i))) |
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... | #CoffeeScript | CoffeeScript | # Returns a copy of an array with the element at a specific position
# removed from it.
arrayExcept = (arr, idx) ->
res = arr[0..]
res.splice idx, 1
res
# The actual function which returns the permutations of an array-like
# object (or a proper array).
permute = (arr) ->
arr = Array::slice.call arr, 0
return [[]... |
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 ... | #Nim | Nim | import sequtils, strutils
proc newValList(size: Positive): seq[int] =
if (size and 1) != 0:
raise newException(ValueError, "size must be even.")
result = toSeq(1..size)
func shuffled(list: seq[int]): seq[int] =
result.setLen(list.len)
let half = list.len div 2
for i in 0..<half:
result[2 * i] = ... |
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 ... | #Oforth | Oforth | : shuffle(l) l size 2 / dup l left swap l right zip expand ;
: nbShuffles(l) 1 l while( shuffle dup l <> ) [ 1 under+ ] drop ; |
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
... | #Swift | Swift | import Foundation
struct Perlin {
private static let permutation = [
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, ... |
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
| #Wren | Wren | var totient = Fn.new { |n|
var tot = n
var i = 2
while (i*i <= n) {
if (n%i == 0) {
while(n%i == 0) n = (n/i).floor
tot = tot - (tot/i).floor
}
if (i == 2) i = 1
i = i + 2
}
if (n > 1) tot = tot - (tot/n).floor
return tot
}
var 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 mu... | #Lua | Lua |
suits = {"Clubs", "Diamonds", "Hearts", "Spades"}
faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"}
--a stack is a set of cards. a stack of length 1 acts as a card; the stack constructor only creates decks.
stack = setmetatable({
--shuffles a stack
__unm = function(z)
local ret = {}
for i = #z, 1, -1 do
... |
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 ...... | #Lasso | Lasso | #!/usr/bin/lasso9
define generatePi => {
yield currentCapture
local(r = array(), i, k, b, d, c = 0, x)
with i in generateSeries(1, 2800)
do #r->insert(2000)
with k in generateSeries(2800, 1, -14)
do {
#d = 0
#i = #k
while(true) => {
#d += #r->get(#i) * 10000
#b = 2 * #i - 1
... |
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... | #Rust | Rust | use rand::prelude::*;
fn main() {
println!("Beginning game of Pig...");
let mut players = vec![
Player::new(String::from("PLAYER (1) ONE")),
Player::new(String::from("PLAYER (2) TWO")),
];
'game: loop {
for player in players.iter_mut() {
if player.cont() {
... |
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... | #Panda | Panda | fun prime(a) type integer->integer
a where count{{a.factor}}==2
fun pernisc(a) type integer->integer
a where sum{{a.radix:2 .char.integer}}.integer.prime
1..36.pernisc
888888877..888888888.pernisc |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #PL.2FI | PL/I | declare t(0:9) character (1) static initial
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
put ( t(10*random()) ); |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Powershell | Powershell |
1..100 | Get-Random -Count 3
|
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... | #REXX | REXX | s='rosetta code phrase reversal'
r1=reverse(s)
r2=''
Do i=1 To words(s)
r2=r2 reverse(word(s,i))
End
r2=strip(r2)
r3=''
Do i=words(s) To 1 By -1
r3=r3 word(s,i)
End
r3=strip(r3)
Say "input : " s
say "string reversed : " r1
say "each word reversed : " r2
say "word-order reversed : " r3 |
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... | #Ring | Ring |
aString = "Welcome to the Ring Language"
bString = ""
see reverseString(aString)
func reverseString cString
for i= len(cString) to 1 step -1
bString = bString + cString[i]
next
return bString
|
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... | #Python | Python | from itertools import permutations
import math
def derangements(n):
'All deranged permutations of the integers 0..n-1 inclusive'
return ( perm for perm in permutations(range(n))
if all(indx != p for indx, p in enumerate(perm)) )
def subfact(n):
if n == 2 or n == 0:
return 1
el... |
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 ... | #XPL0 | XPL0 | include c:\cxpl\codes;
proc PERMS(N);
int N; \number of elements
int I, K, S, T, P;
[P:= Reserve((N+1)*4);
for I:= 0 to N do P(I):= -I; \initialize facing left (also set P(0)=0)
S:= 1;
repeat Text(0, "Perm: [ ");
for I:= 1 to N do
[IntOut(0, abs(P(I))); ChOut(0, ... |
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 ... | #zkl | zkl | fcn permute(seq)
{
insertEverywhere := fcn(x,list){ //(x,(a,b))-->((x,a,b),(a,x,b),(a,b,x))
(0).pump(list.len()+1,List,'wrap(n){list[0,n].extend(x,list[n,*]) })};
insertEverywhereB := fcn(x,t){ //--> insertEverywhere().reverse()
[t.len()..-1,-1].pump(t.len()+1,List,'wrap(n){t[0,n].extend(x,t[n,*])})};... |
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... | #Phix | Phix | -- demo\rosetta\Percentage_difference_between_images.exw
without js -- (file i/o)
include ppm.e
function split_colour(integer c)
return sq_div(sq_and_bits(c, {#FF0000,#FF00,#FF}),
{#010000,#0100,#01})
end function
function percentage_diff(sequence img1, img2)
if length(img1)!=... |
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... | #D | D | import std.stdio, std.algorithm, std.range;
bool isPerfectNumber1(in uint n) pure nothrow
in {
assert(n > 0);
} body {
return n == iota(1, n - 1).filter!(i => n % i == 0).sum;
}
void main() {
iota(1, 10_000).filter!isPerfectNumber1.writeln;
} |
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... | #Common_Lisp | Common Lisp | (defun permute (list)
(if list
(mapcan #'(lambda (x)
(mapcar #'(lambda (y) (cons x y))
(permute (remove x list))))
list)
'(()))) ; else
(print (permute '(A B 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 ... | #PARI.2FGP | PARI/GP | magic(v)=vector(#v,i,v[if(i%2,1,#v/2)+i\2]);
shuffles_slow(n)=my(v=[1..n],o=v,s=1);while((v=magic(v))!=o,s++);s;
shuffles(n)=znorder(Mod(2,n-1));
vector(5000,n,shuffles_slow(2*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
... | #Tcl | Tcl | namespace eval perlin {
proc noise {x y z} {
# Find unit cube that contains point.
set X [expr {int(floor($x)) & 255}]
set Y [expr {int(floor($y)) & 255}]
set Z [expr {int(floor($z)) & 255}]
# Find relative x,y,z of point in cube.
set x [expr {$x - floor($x)}]
set y [expr {$y - floor($y)}]
set z [expr {$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
| #zkl | zkl | var totients=List.createLong(10_000,0); // cache
fcn totient(n){ if(phi:=totients[n]) return(phi);
totients[n]=[1..n].reduce('wrap(p,k){ p + (n.gcd(k)==1) })
}
fcn perfectTotientW{ // -->iterator
(1).walker(*).tweak(fcn(z){
parts,n := 0,z;
while(n!=1){ parts+=( n=totient(n) ) }
if(parts==z) z 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 mu... | #M2000_Interpreter | M2000 Interpreter |
Module PlayCards {
Font "Arial" ' Ensure characters exist for Suits
Cls 15,0
Pen 0
Inventory Suits = "♠":=0, "♥":=4, "♦":=4, "♣":=0 'suit -> color
Inventory Cards = "two":=2, "three":=3, "four":=4, "five":=5
Append Cards, "six":=6, "seven":=7, "eight":=8, "nine":=9
Append Ca... |
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 ...... | #Liberty_BASIC | Liberty BASIC | ndigits = 0
q = 1
r = 0
t = q
k = q
n = 3
L = n
first = 666 ' ANY non-zero =='true' in LB.
while ndigits <100
if ( 4 *q +r -t) <( n *t) then
print n;
ndigits =ndigits +1
if not( ndigits mod 40) th... |
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... | #Scala | Scala | object PigDice extends App {
private val (maxScore, nPlayers) = (100, 2)
private val rnd = util.Random
private case class Game(gameOver: Boolean, idPlayer: Int, score: Int, stickedScores: Vector[Int])
@scala.annotation.tailrec
private def loop(play: Game): Unit =
play match {
case Game(true, _, ... |
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... | #PARI.2FGP | PARI/GP | pern(n)=isprime(hammingweight(n))
select(pern, [1..36])
select(pern,[888888877..888888888]) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Prolog | Prolog |
?- random_member(M, [a, b, c, d, e, f, g, h, i, j]).
M = i.
|
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #PureBasic | PureBasic | Procedure.s pickRandomElement(List source.s())
Protected x = ListSize(source())
If x > 0
SelectElement(source(), Random(x - 1)) ;element numbering is zero - based
ProcedureReturn source()
EndIf
EndProcedure
;initialize list elements
DataSection
elements:
Data.s "One", "Two", "Three", "Four", "Five... |
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... | #Ruby | Ruby | str = "rosetta code phrase reversal"
puts str.reverse # Reversed string.
puts str.split.map(&:reverse).join(" ") # Words reversed.
puts str.split.reverse.join(" ") # Word order reversed. |
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... | #Rust | Rust | fn reverse_string(string: &str) -> String {
string.chars().rev().collect::<String>()
}
fn reverse_words(string: &str) -> String {
string
.split_whitespace()
.map(|x| x.chars().rev().collect::<String>())
.collect::<Vec<String>>()
.join(" ")
}
fn reverse_word_order(string: &str... |
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... | #QBasic | QBasic | ' Heap's algorithm non-recursive
FUNCTION permsderange (n!, flag!)
IF n = 0 THEN permsderange = 1
DIM a!(0 TO n), c!(0 TO n)
FOR j = 0 TO n - 1: a(j) = j: NEXT j
WHILE i < n
IF c(i) < i THEN
IF (i AND 1) = 0 THEN
SWAP a(0), a(i)
ELSE
... |
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... | #PicoLisp | PicoLisp | (call "convert" "Lenna50.jpg" (tmp "Lenna50.ppm"))
(call "convert" "Lenna100.jpg" (tmp "Lenna100.ppm"))
(let (Total 0 Diff 0)
(in (tmp "Lenna50.ppm")
(in (tmp "Lenna100.ppm")
(while (rd 1)
(inc 'Diff
(*/
(abs (- @ (in -1 (rd 1))))
10000... |
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... | #PureBasic | PureBasic | #URL1="http://rosettacode.org/mw/images/3/3c/Lenna50.jpg"
#URL2="http://rosettacode.org/mw/images/b/b6/Lenna100.jpg"
Procedure.s GetTempFileName(basename$="",Extension$=".tmp")
Protected file$, i
Repeat: file$=GetTemporaryDirectory()+basename$+"_"+Str(i)+Extension$: i+1
Until FileSize(file$) = -1 ; E.g. File no... |
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... | #Dart | Dart | /*
* Function to test if a number is a perfect number
* A number is a perfect number if it is equal to the sum of all its divisors
* Input: Positive integer n
* Output: true if n is a perfect number, false otherwise
*/
bool isPerfect(int n){
//Generate a list of integers in the range 1 to n-1 : [1, 2, ..., n-1... |
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... | #Crystal | Crystal | puts [1, 2, 3].permutations |
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 ... | #Perl | Perl | use List::Util qw(all);
sub perfect_shuffle {
my $mid = @_ / 2;
map { @_[$_, $_ + $mid] } 0..($mid - 1);
}
for my $size (8, 24, 52, 100, 1020, 1024, 10000) {
my @shuffled = my @deck = 1 .. $size;
my $n = 0;
do { $n++; @shuffled = perfect_shuffle(@shuffled) }
until all { $shuffled[$_] == ... |
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 ... | #Phix | Phix | with javascript_semantics
function perfect_shuffle(sequence deck)
integer l = length(deck), mp = l/2, k = 1
sequence res = repeat(0,l)
for i=1 to mp do
res[k] = deck[i] k += 1
res[k] = deck[i+mp] k += 1
end for
return res
end function
constant testsizes = {8, 24, 52, 100... |
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
... | #Vlang | Vlang | import math
// vlang doesn't have globals
const (
p = [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... |
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... | #M4 | M4 | define(`randSeed',141592653)dnl
define(`setRand',
`define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')dnl
define(`rand_t',`eval(randSeed^(randSeed>>13))')dnl
define(`random',
`define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')dnl
define(`for',
`ifelse($#,0,``$0'',
`ifelse(ev... |
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 ...... | #Lua | Lua | a = {}
n = 1000
len = math.modf( 10 * n / 3 )
for j = 1, len do
a[j] = 2
end
nines = 0
predigit = 0
for j = 1, n do
q = 0
for i = len, 1, -1 do
x = 10 * a[i] + q * i
a[i] = math.fmod( x, 2 * i - 1 )
q = math.modf( x / ( 2 * i - 1 ) )
end
a[1] = math.fmod( q, 10 )
q = ma... |
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... | #Tcl | Tcl | package require TclOO
oo::class create Player {
variable me
constructor {name} {
set me $name
}
method name {} {
return $me
}
method wantToRoll {safeScore roundScore} {}
method stuck {score} {}
method busted {score} {}
method won {score} {}
method rolled {who what} {
if ... |
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... | #Pascal | Pascal | program pernicious;
{$IFDEF FPC}
{$OPTIMIZATION ON,Regvar,ASMCSE,CSE,PEEPHOLE}// 3x speed up
{$ENDIF}
uses
sysutils;//only used for time
type
tbArr = array[0..64] of byte;
{
PrimeTil64 : array[0..64] of byte =
(0,0,2,3,0,5,0, 7,0,0,0,11,0,13,0,0,0,17,0,19,0,0,0,23,0,0,0,0,0,29,0,
31,0,0,0,0,0,37,0,0... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Python | Python | >>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz' |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Quackery | Quackery | [ dup size random peek ] is pick ( [ --> x )
randomise
' [ 20 33 -15 7 0 ] pick echo cr
' pick pick echo |
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... | #Scala | Scala | object PhraseReversals extends App {
val phrase = scala.io.StdIn.readLine
println(phrase.reverse)
println(phrase.split(' ').map(_.reverse).mkString(" "))
println(phrase.split(' ').reverse.mkString(" "))
} |
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... | #Quackery | Quackery |
[ stack ] is deranges.num ( --> [ )
forward is (deranges)
[ over size
deranges.num share = iff
[ over temp take
swap nested join
temp put ]
else
[ dup size times
[ 2dup i^ pluck
dip [ over size ... |
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... | #Python | Python | from PIL import Image
i1 = Image.open("image1.jpg")
i2 = Image.open("image2.jpg")
assert i1.mode == i2.mode, "Different kinds of images."
assert i1.size == i2.size, "Different sizes."
pairs = zip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1-p2) for p1,p2 in... |
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... | #Delphi | Delphi | func isPerfect(num) {
var sum = 0
for i in 1..<num {
if !i {
break
}
if num % i == 0 {
sum += i
}
}
return sum == num
}
let max = 33550337
print("Perfect numbers from 0 to \(max):")
for x in 0..max {
if isPerfect(x) {
print("\(x) is... |
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... | #Curry | Curry |
insert :: a -> [a] -> [a]
insert x xs = x : xs
insert x (y:ys) = y : insert x ys
permutation :: [a] -> [a]
permutation [] = []
permutation (x:xs) = insert x $ permutation xs
|
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 ... | #Picat | Picat | go =>
member(N,[8,24,52,100,1020,1024,10_000]),
println(n=N),
InOut = out, % in/out shuffling
println(inOut=InOut),
Print = cond(N < 100, true,false),
if Print then
println(1..N),
end,
Count = show_all_shuffles(N,InOut,Print),
println(count=Count),
nl,
fail,
nl.
%
% Show all ... |
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 ... | #PicoLisp | PicoLisp | (de perfectShuffle (Lst)
(mapcan '((B A) (list A B))
(cdr (nth Lst (/ (length Lst) 2)))
Lst ) )
(for N (8 24 52 100 1020 1024 10000)
(let (Lst (range 1 N) L Lst Cnt 1)
(until (= Lst (setq L (perfectShuffle L)))
(inc 'Cnt) )
(tab (5 6) N Cnt) ) ) |
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
... | #Wren | Wren | var permutation = [
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,... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | MakeDeck[] := Tuples[{{"Ace ", 2, 3 , 4 , 5, 6 , 7 , 8 , 9 , 10, "Jack" , "Queen", "King"}, {♦ , ♣, ♥ , ♠}}]
DeckShuffle[deck_] := RandomSample[deck, Length@deck]
DealFromDeck[] := (Print@First@deck; deck = deck[[2 ;; All]];) |
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 ...... | #M2000_Interpreter | M2000 Interpreter |
Module Checkpi {
Module FindPi(Digits){
Digits++
n=Int(3.32*Digits)
PlusOne=Lambda N=0% -> {
=N
N++
}
PlusTwo=Lambda N=1% -> {
=N
N+=2
}
Dim A(n)<<PlusOne(... |
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... | #VBA | VBA |
Option Explicit
Sub Main_Pig()
Dim Scs() As Byte, Ask As Integer, Np As Boolean, Go As Boolean
Dim Cp As Byte, Rd As Byte, NbP As Byte, ScBT As Byte
'You can adapt these Const, but don't touch the "¤¤¤¤"
Const INPTXT As String = "Enter number of players : "
Const INPTITL As String = "Numeric only"
C... |
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... | #Perl | Perl | sub is_pernicious {
my $n = shift;
my $c = 2693408940; # primes < 32 as set bits
while ($n) { $c >>= 1; $n &= ($n - 1); }
$c & 1;
}
my ($i, @p) = 0;
while (@p < 25) {
push @p, $i if is_pernicious($i);
$i++;
}
print join ' ', @p;
print "\n";
($i, @p) = (888888877,);
while ($i < 888888888) {
... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #R | R | # a vector (letters are builtin)
letters
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
# [20] "t" "u" "v" "w" "x" "y" "z"
# picking one element
sample(letters, 1)
# [1] "n"
# picking some elements with repetition, and concatenating to get a word
paste(sample(letters, 10, rep=T),... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Racket | Racket |
#lang racket
(define (pick-item l)
(list-ref l (random (length l))))
|
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var string: phrase is "rosetta code phrase reversal";
var string: word is "";
var array string: wordList is 0 times "";
begin
writeln("The original phrase:" rpad 27 <& phrase);
writeln("Reverse the entire phrase:" rpad 27 <& reverse(phra... |
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... | #SenseTalk | SenseTalk | set phrase to "rosetta code phrase reversal"
put phrase reversed
put (the reverse of each word of phrase) joined by space
put (each word of phrase) reversed joined by space
|
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... | #Sidef | Sidef | var str = "rosetta code phrase reversal";
say str.reverse; # reversed string
say str.words.map{.reverse}.join(' '); # words reversed
say str.words.reverse.join(' '); # word order reversed |
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... | #Racket | Racket |
#lang racket
(define (all-misplaced? l)
(for/and ([x (in-list l)] [n (in-naturals 1)]) (not (= x n))))
;; 1. Create a named function to generate derangements of the integers 0..n-1.
(define (derangements n)
(define (all-misplaced? l1 l2)
(or (null? l1)
(and (not (eq? (car l1) (car l2)))
... |
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... | #Raku | Raku | sub derangements(@l) {
@l.permutations.grep(-> @p { none(@p Zeqv @l) })
}
sub prefix:<!>(Int $n) {
(1, 0, 1, -> $a, $b { ($++ + 2) × ($b + $a) } ... *)[$n]
}
say 'derangements([1, 2, 3, 4])';
say derangements([1, 2, 3, 4]), "\n";
say 'n == !n == derangements(^n).elems';
for 0 .. 9 -> $n {
say "!$n == ... |
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... | #Racket | Racket | #lang racket
(require racket/draw)
(define (percentage-difference bitmap1 bitmap2)
(define width (send bitmap1 get-width))
(define height (send bitmap1 get-height))
(define buffer1 (make-bytes (* width height 4)))
(define buffer2 (make-bytes (* width height 4)))
(send (send bitmap1 make-dc) get-argb-pixels ... |
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... | #Raku | Raku | use GD::Raw;
my $fh1 = fopen('./Lenna50.jpg', "rb") or die;
my $img1 = gdImageCreateFromJpeg($fh1);
my $fh2 = fopen('./Lenna100.jpg', "rb") or die;
my $img2 = gdImageCreateFromJpeg($fh2);
my $img1X = gdImageSX($img1);
my $img1Y = gdImageSY($img1);
my $img2X = gdImageSX($img2);
my $img2Y = gdImageSY($img2);
($img1... |
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... | #Dyalect | Dyalect | func isPerfect(num) {
var sum = 0
for i in 1..<num {
if !i {
break
}
if num % i == 0 {
sum += i
}
}
return sum == num
}
let max = 33550337
print("Perfect numbers from 0 to \(max):")
for x in 0..max {
if isPerfect(x) {
print("\(x) is... |
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... | #E | E | pragma.enable("accumulator")
def isPerfectNumber(x :int) {
var sum := 0
for d ? (x % d <=> 0) in 1..!x {
sum += d
if (sum > x) { return false }
}
return sum <=> x
} |
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... | #D | D | T[][] permutations(T)(T[] items) pure nothrow {
T[][] result;
void perms(T[] s, T[] prefix=[]) nothrow {
if (s.length)
foreach (immutable i, immutable c; s)
perms(s[0 .. i] ~ s[i+1 .. $], prefix ~ c);
else
result ~= prefix;
}
perms(items);
r... |
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 ... | #Python | Python |
import doctest
import random
def flatten(lst):
"""
>>> flatten([[3,2],[1,2]])
[3, 2, 1, 2]
"""
return [i for sublst in lst for i in sublst]
def magic_shuffle(deck):
"""
>>> magic_shuffle([1,2,3,4])
[1, 3, 2, 4]
"""
half = len(deck) // 2
return flatten(zip(deck[:half]... |
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 ... | #Quackery | Quackery | [ [] swap
times [ i^ join ] ] is deck ( n --> [ )
[ dup size 2 / split swap
witheach
[ swap i^ 2 * stuff ] ] is weave ( [ --> [ )
[ 0 swap
deck dup
[ rot 1+ unrot
weave 2dup = until ]
2drop ] is shuffles ( n --> n )
' [ 8 24 52 100 1020 1024... |
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
... | #XPL0 | XPL0 | func real Noise; real X, Y, Z;
real U, V, W;
int IX, IY, IZ, P(512), A, AA, AB, B, BA, BB;
func real Fade; real T;
return T*T*T * (T*(T*6.-15.) + 10.);
func real Lerp; real T, A, B;
return A + T*(B-A);
func real Grad; int Hash; real X, Y, Z;
int H; real U, V;
[H:= Hash & $0F; ... |
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... | #MiniScript | MiniScript | suits = ["Spades", "Clubs", "Hearts", "Diamonds"]
pips = ["Ace","Two","Three","Four","Five","Six","Seven",
"Eight","Nine","Ten","Jack","Queen","King"]
Card = {}
Card.str = function()
return self.pip + " of " + self.suit + " (value: " + self.value + ")"
end function
//Build Deck
deck = []
for s in suits.inde... |
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 ...... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | WriteString[$Output, "3."];
For[i = -1, True, i--,
WriteString[$Output, RealDigits[Pi, 10, 1, i][[1, 1]]]; Pause[.05]]; |
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... | #Vlang | Vlang | import rand
import rand.seed
import os
fn main() {
rand.seed(seed.time_seed_array(2)) //Set seed to current time
mut player_scores := [0, 0]
mut turn := 0
mut current_score := 0
for {
player := turn % player_scores.len
answer := os.input("Player $player [${player_scores[player]}, $current_score], (H)old,... |
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... | #Phix | Phix | with javascript_semantics
function pernicious(integer n)
return is_prime(sum(int_to_bits(n,32)))
end function
sequence s = {}
integer n = 1
while length(s)<25 do
if pernicious(n) then
s &= n
end if
n += 1
end while
pp(s)
s = {}
for i=888_888_877 to 888_888_888 do
if pernicious(i) then
... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Raku | Raku | say (1, 2, 3).pick; |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Red | Red | >> random/only collect [repeat i 10 [keep i]] |
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... | #Smalltalk | Smalltalk | |str|
str := 'rosetta code phrase reversal'.
Transcript showCR:(str reversed).
Transcript showCR:(((str splitBy:$ ) collect:#reversed) join:$ ).
Transcript showCR:(((str splitBy:$ ) reversed) join:$ ). |
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... | #Swift | Swift |
func reverseString(s:String)->String{
var temp = [Character]()
for i in s.characters{
temp.append(i)
}
var j=s.characters.count-1
for i in s.characters{
temp[j]=i
j-=1
}
return String(temp)
}
func reverseWord(s:String)->String{
var temp = [Character]()
va... |
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... | #REXX | REXX | /*REXX program generates all permutations of N derangements and subfactorial # */
numeric digits 1000 /*be able to handle large subfactorials*/
parse arg N .; if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/
d= derangeSet(N) ... |
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... | #REBOL | REBOL | rebol [
Title: "Percent Image Difference"
URL: http://rosettacode.org/wiki/Percentage_of_difference_between_2_images
]
; Load from local storage. Un/comment as preferred.
; a: load-image %lenna50.jpg
; b: load-image %lenna100.jpg
; Download from rosettacode.org.
a: load-image http://rosettacode.org/mw/images/3/3c... |
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... | #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
do
io.put_string (" 6 is perfect...%T")
io.put_boolean (is_perfect_number (6))
io.new_line
io.put_string (" 77 is perfect...%T")
io.put_boolean (is_perfect_number (77))
io.new_line
io.put_string ("128 is perfect...%T")
io.put_boolean (is_p... |
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... | #Delphi | Delphi | program TestPermutations;
{$APPTYPE CONSOLE}
type
TItem = Integer; // declare ordinal type for array item
TArray = array[0..3] of TItem;
const
Source: TArray = (1, 2, 3, 4);
procedure Permutation(K: Integer; var A: TArray);
var
I, J: Integer;
Tmp: TItem;
begin
for I:= Low(A) + 1 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 ... | #R | R | wave.shuffle <- function(n) {
deck <- 1:n ## create the original deck
new.deck <- c(matrix(data = deck, ncol = 2, byrow = TRUE)) ## shuffle the deck once
counter <- 1 ## track the number of loops
## defining a loop that shuffles the new deck until identical with the original one
## and in the same time incre... |
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
... | #zkl | zkl | class [static] ImprovedNoise{ // a container, not an object
fcn noise(xyz){ xyz=vm.arglist.apply("toFloat");
X,Y,Z:= // FIND UNIT CUBE THAT CONTAINS POINT.
xyz.apply(fcn(x){ x.floor().toInt().bitAnd(255) });
xyz= // FIND RELATIVE X,Y,Z OF POINT IN CUBE.
xyz.apply(fcn(x){ x - x.flo... |
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... | #MUMPS | MUMPS | import random, strutils
type
Suit* = enum ♥, ♦, ♣, ♠
Rank* {.pure.} = enum
Ace = (1, "A")
Two = (2, "2")
Three = (3, "3")
Four = (4, "4")
Five = (5, "5")
Six = (6, "6")
Seven = (7, "7")
Eight = (8, "8")
Nine = (9, "9")
Ten = (10, "10")
Jack = (11, "J")
Queen = (12... |
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 ...... | #MATLAB_.2F_Octave | MATLAB / Octave | pi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.