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/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 ... | #Clojure | Clojure |
(defn permutation-swaps
"List of swap indexes to generate all permutations of n elements"
[n]
(if (= n 2) `((0 1))
(let [old-swaps (permutation-swaps (dec n))
swaps-> (partition 2 1 (range n))
swaps<- (reverse swaps->)]
(mapcat (fn [old-swap side]
(case side
... |
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... | #Delphi | Delphi |
program Permutation_test;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
procedure Comb(n, m: Integer; emit: TProc<TArray<Integer>>);
var
s: TArray<Integer>;
last: Integer;
procedure rc(i, next: Integer);
begin
for var j := next to n - 1 do
begin
s[i] := j;
if i = last then
emi... |
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
... | #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int p[512];
double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
double lerp(double t, double a, double b) { return a + t * (b - a); }
double grad(int hash, double x, double y, double z) {
int h = hash & 15;
d... |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android with termux */
/* program totientPerfect.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for consta... |
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... | #CoffeeScript | CoffeeScript | #translated from JavaScript example
class Card
constructor: (@pip, @suit) ->
toString: => "#{@pip}#{@suit}"
class Deck
pips = '2 3 4 5 6 7 8 9 10 J Q K A'.split ' '
suits = '♣ ♥ ♠ ♦'.split ' '
constructor: (@cards) ->
if not @cards?
@cards = []
for suit in suits
for pip in pips
... |
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 ...... | #C.2B.2B | C++ | #include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
class Gospers
{
cpp_int q, r, t, i, n;
public:
// use Gibbons spigot algorith based on the Gospers series
Gospers() : q{1}, r{0}, t{1}, i{1}
{
++*this; // move to the first digit
... |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1... | #FutureBasic | FutureBasic |
include "NSLog.incl"
local fn PeriodicTable( n as NSInteger ) as CFDictionaryRef
NSInteger i, row = 0, start = 0, finish, limits(6,6)
CFDictionaryRef dict = NULL
if n < 1 or n > 118 then NSLog( @"Atomic number is out of range." ) : exit fn
if n == 1 then dict = @{@"row":@1, @"col":@1} : exit fn
if n == 2 then d... |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1... | #Go | Go | package main
import (
"fmt"
"log"
)
var limits = [][2]int{
{3, 10}, {11, 18}, {19, 36}, {37, 54}, {55, 86}, {87, 118},
}
func periodicTable(n int) (int, int) {
if n < 1 || n > 118 {
log.Fatal("Atomic number is out of range.")
}
if n == 1 {
return 1, 1
}
if n == 2 {
... |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and th... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Pig.bas"
110 RANDOMIZE
120 STRING PLAYER$(1 TO 2)*28
130 NUMERIC POINTS(1 TO 2),VICTORY(1 TO 2)
140 LET WINNINGSCORE=100
150 TEXT 40:PRINT "Let's play Pig!";CHR$(241):PRINT
160 FOR I=1 TO 2
170 PRINT "Player";I
180 INPUT PROMPT "Whats your name? ":PLAYER$(I)
190 LET POINTS(I)=0:LET VICTORY(I)=0:PRI... |
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... | #CLU | CLU | % The population count of an integer is never going to be
% higher than the amount of bits in it (max 64)
% so we can get away with a very simple primality test.
is_prime = proc (n: int) returns (bool)
if n<=2 then return(n=2) end
if n//2=0 then return(false) end
for i: int in int$from_to_by(n+2, n/2, 2) do... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. PERNICIOUS-NUMBERS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 AMOUNT PIC 99.
03 CAND PIC 9(9).
03 POPCOUNT PIC 99.
03 POP-N PIC 9(9).
... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Racket | Racket |
#lang racket (require math)
(define-syntax def (make-rename-transformer #'match-define-values))
(define (perm xs n)
(cond [(empty? xs) '()]
[else (def (q r) (quotient/remainder n (factorial (sub1 (length xs)))))
(def (a (cons c b)) (split-at xs q))
(cons c (perm (append a b) r)... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Raku | Raku | use v6;
sub rank2inv ( $rank, $n = * ) {
$rank.polymod( 1 ..^ $n );
}
sub inv2rank ( @inv ) {
[+] @inv Z* [\*] 1, 1, * + 1 ... *
}
sub inv2perm ( @inv, @items is copy = ^@inv.elems ) {
my @perm;
for @inv.reverse -> $i {
@perm.append: @items.splice: $i, 1;
}
@perm;
}
sub perm2inv... |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be c... | #Nim | Nim | import math, strutils
func isPrime(n: int): bool =
## Check if "n" is prime by trying successive divisions.
## "n" is supposed not to be a multiple of 2 or 3.
var d = 5
var delta = 2
while d <= int(sqrt(n.toFloat)):
if n mod d == 0: return false
inc d, delta
delta = 6 - delta
result = true
f... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Euphoria | Euphoria | constant s = {'a', 'b', 'c'}
puts(1,s[rand($)]) |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #F.23 | F# | let list = ["a"; "b"; "c"; "d"; "e"]
let rand = new System.Random()
printfn "%s" list.[rand.Next(list.Length)] |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #UNIX_Shell | UNIX Shell | function primep {
typeset n=$1 p=3
(( n == 2 )) && return 0 # 2 is prime.
(( n & 1 )) || return 1 # Other evens are not prime.
(( n >= 3 )) || return 1
# Loop for odd p from 3 to sqrt(n).
# Comparing p * p <= n can overflow.
while (( p <= n / p )); do
# If p divides n, then n is not prime.
(( n % p )) || ... |
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... | #Emacs_Lisp | Emacs Lisp | (defun reverse-sep (words sep)
(mapconcat 'identity (reverse (split-string words sep)) sep))
(defun reverse-chars (line)
(reverse-sep line ""))
(defun reverse-words (line)
(reverse-sep line " "))
(defvar line "rosetta code phrase reversal")
(with-output-to-temp-buffer "*reversals*"
(princ (reverse-chars... |
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... | #C.23 | C# |
using System;
class Derangements
{
static int n = 4;
static int [] buf = new int [n];
static bool [] used = new bool [n];
static void Main()
{
for (int i = 0; i < n; i++) used [i] = false;
rec(0);
}
static void rec(int ind)
{
for (int i = 0; i < n; i++)
{
if (!used [i] && i !... |
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 ... | #Common_Lisp | Common Lisp | (defstruct (directed-number (:conc-name dn-))
(number nil :type integer)
(direction nil :type (member :left :right)))
(defmethod print-object ((dn directed-number) stream)
(ecase (dn-direction dn)
(:left (format stream "<~D" (dn-number dn)))
(:right (format stream "~D>" (dn-number dn)))))
(defun dn> ... |
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... | #Elixir | Elixir | defmodule Permutation do
def statistic(ab, a) do
sumab = Enum.sum(ab)
suma = Enum.sum(a)
suma / length(a) - (sumab - suma) / (length(ab) - length(a))
end
def test(a, b) do
ab = a ++ b
tobs = statistic(ab, a)
{under, count} = Enum.reduce(comb(ab, length(a)), {0,0}, fn perm, {under, count... |
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... | #GAP | GAP | a := [85, 88, 75, 66, 25, 29, 83, 39, 97];
b := [68, 41, 10, 49, 16, 65, 32, 92, 28, 98];
# Compute a decimal approximation of a rational
Approx := function(x, d)
local neg, a, b, n, m, s;
if x < 0 then
x := -x;
neg := true;
else
neg := false;
fi;
a := NumeratorRat(x);
b := DenominatorRat(x);
n := QuoInt... |
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... | #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) / Float(FF'FF)
V (p, t) = (0.5, 500)
F newv(n, p)
R (0 .< n).map(i -> Int(nonrandom() < @p))
F runs(v)
R sum(zip(v, v[1..] [+] [0]).map((a, b) -> (a [&] (-)b)))
F mean_run_density(n, p)
R runs(newv(n, p)) / Floa... |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N... | #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) / Float(FF'FF)
V (M, nn, t) = (15, 15, 100)
V cell2char = ‘ #abcdefghijklmnopqrstuvwxyz’
V NOT_VISITED = 1
T PercolatedException
(Int, Int) t
F (t)
.t = t
F newgrid(p)
R (0 .< :nn).map(n -> (0 .< :M).map... |
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
... | #Common_Lisp | Common Lisp | ;;;; Translation from: Java
(declaim (optimize (speed 3) (debug 0)))
(defconstant +p+
(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 32 57 177 33
88 237 149 56 87 ... |
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
| #Arturo | Arturo | totient: function [n][
tt: new n
nn: new n
i: new 2
while [nn >= i ^ 2][
if zero? nn % i [
while [zero? nn % i]->
'nn / i
'tt - tt/i
]
if i = 2 ->
i: new 1
'i + 2
]
if nn > 1 ->
'tt - tt/nn
ret... |
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
| #AutoHotkey | AutoHotkey | MsgBox, 262144, , % result := perfect_totient(20)
perfect_totient(n){
count := sum := tot := 0, str:= "", m := 1
while (count < n) {
tot := m, sum := 0
while (tot != 1) {
tot := totient(tot)
sum += tot
}
if (sum = m) {
str .= m ", "
... |
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... | #Common_Lisp | Common Lisp | (defconstant +suits+
'(club diamond heart spade)
"Card suits are the symbols club, diamond, heart, and spade.")
(defconstant +pips+
'(ace 2 3 4 5 6 7 8 9 10 jack queen king)
"Card pips are the numbers 2 through 10, and the symbols ace, jack,
queen and king.")
(defun make-deck (&aux (deck '()))
"Returns 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 ...... | #Clojure | Clojure | (ns pidigits
(:gen-class))
(def calc-pi
; integer division rounding downwards to -infinity
(let [div (fn [x y] (long (Math/floor (/ x y))))
; Computations performed after yield clause in Python code
update-after-yield (fn [[q r t k n l]]
(let [nr (* 10 (- r ... |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1... | #J | J | PT=: (' ',.~[;._2) {{)n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 H He
2 Li Be B C N O F Ne
3 Na Mg Al Si P S Cl Ar
4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br... |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1... | #Julia | Julia | const limits = [3:10, 11:18, 19:36, 37:54, 55:86, 87:118]
function periodic_table(n)
(n < 1 || n > 118) && error("Atomic number is out of range.")
n == 1 && return [1, 1]
n == 2 && return [1, 18]
57 <= n <= 71 && return [8, n - 53]
89 <= n <= 103 && return [9, n - 85]
row, limitstart, limitsto... |
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... | #J | J | require'general/misc/prompt' NB. was require'misc' in j6
status=:3 :0
'pid cur tot'=. y
player=. 'player ',":pid
potential=. ' potential: ',":cur
total=. ' total: ',":tot
smoutput player,potential,total
)
getmove=:3 :0
whilst.1~:+/choice do.
choice=.'HRQ' e. prompt '..Roll the dice or Hold or Qui... |
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... | #Common_Lisp | Common Lisp | (format T "~{~a ~}~%"
(loop for n = 1 then (1+ n)
when (primep (logcount n))
collect n into numbers
when (= (length numbers) 25)
return numbers))
(format T "~{~a ~}~%"
(loop for n from 888888877 to 888888888
when (primep (logcou... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #REXX | REXX | /*REXX program displays permutations of N number of objects (1, 2, 3, ···). */
parse arg N y seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 4 /*Not specified? Then use the default.*/
if y=='' | y=="," then y= 17 ... |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be c... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use bigint try=>"GMP";
use ntheory qw<is_prime>;
# index of mininum value in list
sub min_index { my $b = $_[my $i = 0]; $_[$_] < $b && ($b = $_[$i = $_]) for 0..$#_; $i }
sub iter1 { my $m = shift; my $e = 0; return sub { $m ** $e++; } }
sub iter2 { my $m = shift; my... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Factor | Factor | ( scratchpad ) { "a" "b" "c" "d" "e" "f" } random .
"a" |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Falcon | Falcon |
lst = [1, 3, 5, 8, 10]
> randomPick(lst)
|
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #Ursala | Ursala | #import std
#import nat
prime = ~<{0,1}&& -={2,3}!| ~&h&& (all remainder)^Dtt/~& iota@K31 |
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... | #Factor | Factor |
USE: splitting
: splitp ( str -- seq ) " " split ;
: printp ( seq -- ) " " join print ;
: reverse-string ( str -- ) reverse print ;
: reverse-words ( str -- ) splitp [ reverse ] map printp ;
: reverse-phrase ( str -- ) splitp reverse printp ;
"rosetta code phrase reversal" [ rever... |
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... | #Fortran | Fortran | DO WHILE (L1.LE.L .AND. ATXT(L1).LE." ")
L1 = L1 + 1
END DO |
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... | #Clojure | Clojure | (ns derangements.core
(:require [clojure.set :as s]))
(defn subfactorial [n]
(case n
0 1
1 0
(* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2))))))
(defn no-fixed-point
"f : A -> B must be a biyective function written as a hash-map, returns
all g : A -> B such that (f(a) = b) => not(g(a... |
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 ... | #D | D | import std.algorithm, std.array, std.typecons, std.range;
struct Spermutations(bool doCopy=true) {
private immutable uint n;
alias TResult = Tuple!(int[], int);
int opApply(in int delegate(in ref TResult) nothrow dg) nothrow {
int result;
int sign = 1;
alias Int2 = Tuple!(int, ... |
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... | #FreeBASIC | FreeBASIC |
Dim Shared datos(18) As Integer => {85, 88, 75, 66, 25, 29, 83, 39, 97,_
68, 41, 10, 49, 16, 65, 32, 92, 28, 98}
Function pick(at As Integer, remain As Integer, accu As Integer, treat As Integer) As Integer
If remain = 0 Then
If accu > treat Then Return 1 Else Return... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
// just generate 0s and 1s without storing them
double run_test(double p, int len, int runs)
{
int r, x, y, i, cnt = 0, thresh = p * RAND_MAX;
for (r = 0; r < runs; r++)
for (x = 0, i = len; i--; x = y)
cnt += x < (y = rand() < thresh);
return (double)cnt / runs / le... |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *cell, *start, *end;
int m, n;
void make_grid(int x, int y, double p)
{
int i, j, thresh = p * RAND_MAX;
m = x, n = y;
end = start = realloc(start, (x+1) * (y+1) + 1);
memset(start, 0, m + 1);
cell = end = start + m + 1;
for (i = 0; i < n; ... |
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... | #11l | 11l | V a = [1, 2, 3]
L
print(a)
I !a.next_permutation()
L.break |
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 ... | #11l | 11l | F flatten(lst)
[Int] r
L(sublst) lst
L(i) sublst
r [+]= i
R r
F magic_shuffle(deck)
V half = deck.len I/ 2
R flatten(zip(deck[0 .< half], deck[half ..]))
F after_how_many_is_equal(start, end)
V deck = magic_shuffle(start)
V counter = 1
L deck != end
deck = magic_shuffle(... |
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
... | #D | D | import std.stdio, std.math;
struct PerlinNoise {
private static double fade(in double t) pure nothrow @safe @nogc {
return t ^^ 3 * (t * (t * 6 - 15) + 10);
}
private static double lerp(in double t, in double a, in double b)
pure nothrow @safe @nogc {
return a + t * (b - a);
}
... |
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
| #AWK | AWK |
# syntax: GAWK -f PERFECT_TOTIENT_NUMBERS.AWK
BEGIN {
i = 20
printf("The first %d perfect totient numbers:\n%s\n",i,perfect_totient(i))
exit(0)
}
function perfect_totient(n, count,m,str,sum,tot) {
for (m=1; count<n; m++) {
tot = m
sum = 0
while (tot != 1) {
tot = totient(tot... |
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
| #BASIC | BASIC | 10 DEFINT A-Z
20 N=3
30 S=N: T=0
40 X=S: S=0
50 FOR I=1 TO X-1
60 A=X: B=I
70 IF B>0 THEN C=A: A=B: B=C MOD B: GOTO 70
80 IF A=1 THEN S=S+1
90 NEXT
100 T=T+S
110 IF S>1 GOTO 40
120 IF T=N THEN PRINT N,: Z=Z+1
130 N=N+2
140 IF Z<20 GOTO 30 |
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... | #D | D | import std.stdio, std.typecons, std.algorithm, std.traits, std.array,
std.range, std.random;
enum Pip {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, Queen, King, Ace}
enum Suit {Diamonds, Spades, Hearts, Clubs}
alias Card = Tuple!(Pip, Suit);
auto newDeck() pure nothrow @safe {
re... |
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 ...... | #Common_Lisp | Common Lisp | (defun pi-spigot ()
(labels
((g (q r t1 k n l)
(cond
((< (- (+ (* 4 q) r) t1)
(* n t1))
(princ n)
(g (* 10 q)
(* 10 (- r (* n t1)))
t1
k
(- (floor (/ (* 10 (+ (* 3 q) r))
... |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[FindPeriodGroup]
FindPeriodGroup[n_Integer] := Which[57 <= n <= 70,
{8, n - 53}
,
89 <= n <= 102,
{9, n - 85}
,
1 <= n <= 118,
{ElementData[n, "Period"], ElementData[n, "Group"]}
,
True,
Missing["Element does not exist"]
]
Row[{"Element ", #, " -> ", FindPeriodGroup[#]}] & /@ {1, 2, 29, 42,... |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1... | #Perl | Perl | use strict;
use warnings; no warnings 'uninitialized';
use feature 'say';
use List::Util <sum head>;
sub divmod { int $_[0]/$_[1], $_[0]%$_[1] }
my $b = 18;
my(@offset,@span,$cnt);
push @span, ($cnt++) x $_ for <1 3 8 44 15 17 15 15>;
@offset = (16, 10, 10, (2*$b)+1, (-2*$b)-15, (2*$b)+1, (-2*$b)-15);
for my $n (... |
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... | #Java | Java | import java.util.*;
public class PigDice {
public static void main(String[] args) {
final int maxScore = 100;
final int playerCount = 2;
final String[] yesses = {"y", "Y", ""};
int[] safeScore = new int[2];
int player = 0, score = 0;
Scanner sc = new Scanner(S... |
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... | #D | D | void main() {
import std.stdio, std.algorithm, std.range, core.bitop;
immutable pernicious = (in uint n) => (2 ^^ n.popcnt) & 0xA08A28AC;
uint.max.iota.filter!pernicious.take(25).writeln;
iota(888_888_877, 888_888_889).filter!pernicious.writeln;
} |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Ring | Ring |
# Project : Permutations/Rank of a permutation
list = [0, 1, 2, 3]
for perm = 0 to 23
str = ""
for i = 1 to len(list)
str = str + list[i] + ", "
next
see nl
str = left(str, len(str)-2)
see "(" + str + ") -> " + perm
nextPermutation(list)
next
func nextPermutation(a)
elemen... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Ruby | Ruby | class Permutation
include Enumerable
attr_reader :num_elements, :size
def initialize(num_elements)
@num_elements = num_elements
@size = fact(num_elements)
end
def each
return self.to_enum unless block_given?
(0...@size).each{|i| yield unrank(i)}
end
def unrank(r) # nonrecursive vers... |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be c... | #Phix | Phix | -- demo/rosetta/Pierpont_primes.exw
with javascript_semantics
include mpfr.e
function pierpont(integer n)
sequence p = {{mpz_init(2)},{}},
s = {mpz_init(1)}
integer i2 = 1, i3 = 1
mpz {n2, n3, t} = mpz_inits(3)
atom t1 = time()+1
while min(length(p[1]),length(p[2])) < n do
mpz... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Fortran | Fortran | program pick_random
implicit none
integer :: i
integer :: a(10) = (/ (i, i = 1, 10) /)
real :: r
call random_seed
call random_number(r)
write(*,*) a(int(r*size(a)) + 1)
end program |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Free_Pascal | Free Pascal | ' FB 1.05.0 Win64
Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Randomize
Dim randInt As Integer
For i As Integer = 1 To 5
randInt = Int(Rnd * 10)
Print a(randInt)
Next
Sleep |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #V | V | [prime?
2
[[dup * >] [true] [false] ifte [% 0 >] dip and]
[succ]
while
dup * <]. |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub split (s As Const String, sepList As Const String, result() As String)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To 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... | #D | D | import std.stdio, std.algorithm, std.typecons, std.conv,
std.range, std.traits;
T factorial(T)(in T n) pure nothrow @safe @nogc {
Unqual!T result = 1;
foreach (immutable i; 2 .. n + 1)
result *= i;
return result;
}
T subfact(T)(in T n) pure nothrow @safe @nogc {
if (0 <= n && 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 ... | #EchoLisp | EchoLisp |
(lib 'list)
(for/fold (sign 1) ((σ (in-permutations 4)) (count 100))
(printf "perm: %a count:%4d sign:%4d" σ count sign) (* sign -1))
perm: (0 1 2 3) count: 0 sign: 1
perm: (0 1 3 2) count: 1 sign: -1
perm: (0 3 1 2) count: 2 sign: 1
perm: (3 0 1 2) count: 3 sign: -1
perm: (3 0 2 1) count: 4 ... |
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... | #Go | Go | package main
import "fmt"
var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}
var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}
func main() {
// collect all results in a single list
all := make([]int, len(tr)+len(ct))
copy(all, tr)
copy(all[len(tr):], ct)
// compute sum of all data, usef... |
http://rosettacode.org/wiki/Percolation/Mean_cluster_density | Percolation/Mean cluster density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
c
{\disp... | #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R (:seed >> 16) / Float(FF'FF)
V nn = 15
V tt = 5
V pp = 0.5
V NotClustered = 1
V Cell2Char = ‘ #abcdefghijklmnopqrstuvwxyz’
V NRange = [4, 64, 256, 1024, 4096]
F newGrid(n, p)
R (0 .< n).map(i -> (0 .< @n).map(i -> Int(nonrandom() < @@p)))... |
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... | #C.2B.2B | C++ | #include <algorithm>
#include <random>
#include <vector>
#include <iostream>
#include <numeric>
#include <iomanip>
using VecIt = std::vector<int>::const_iterator ;
//creates vector of length n, based on probability p for 1
std::vector<int> createVector( int n, double p ) {
std::vector<int> result( n ) ;
std::ra... |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N... | #D | D | import std.stdio, std.random, std.array, std.datetime;
enum size_t nCols = 15,
nRows = 15,
nSteps = 11, // Probability granularity.
nTries = 20_000; // Simulation tries.
enum Cell : char { empty = ' ', filled = '#', visited = '.' }
alias Grid = Cell[nCols][nRows];
void 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... | #360_Assembly | 360 Assembly | * Permutations 26/10/2015
PERMUTE CSECT
USING PERMUTE,R15 set base register
LA R9,TMP-A n=hbound(a)
SR R10,R10 nn=0
LOOP LA R10,1(R10) nn=nn+1
LA R11,PG pgi=@pg
LA R6,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 ... | #Action.21 | Action! | DEFINE MAXDECK="5000"
PROC Order(INT ARRAY deck INT count)
INT i
FOR i=0 TO count-1
DO
deck(i)=i
OD
RETURN
BYTE FUNC IsOrdered(INT ARRAY deck INT count)
INT i
FOR i=0 TO count-1
DO
IF deck(i)#i THEN
RETURN (0)
FI
OD
RETURN (1)
PROC Shuffle(INT ARRAY src,dst INT count)
INT 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 ... | #Ada | Ada | with ada.text_io;use ada.text_io;
procedure perfect_shuffle is
function count_shuffle (half_size : Positive) return Positive is
subtype index is Natural range 0..2 * half_size - 1;
subtype index_that_move is index range index'first+1..index'last-1;
type deck is array (index) of index;
initial, d, ne... |
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
... | #Delphi | Delphi | x floor >integer 255 bitand :> X
y floor >integer 255 bitand :> Y
z floor >integer 255 bitand :> 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
| #BASIC256 | BASIC256 | found = 0
curr = 3
while found < 20
sum = Totient(curr)
toti = sum
while toti <> 1
toti = Totient(toti)
sum += toti
end while
if sum = curr then
print sum
found += 1
end if
curr += 1
end while
end
function GCD(n, d)
if n = 0 then return d
if d = 0 ... |
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
| #BCPL | BCPL | get "libhdr"
let gcd(a,b) = b=0 -> a, gcd(b, a rem b)
let totient(n) = valof
$( let r = 0
for i=1 to n-1
if gcd(n,i) = 1 then r := r + 1
resultis r
$)
let perfect(n) = valof
$( let sum = 0 and x = n
$( x := totient(x)
sum := sum + x
$) repeatuntil x = 1
resultis sum = n
$)
... |
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... | #Delphi | Delphi | program Cards;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
type
TPip = (pTwo, pThree, pFour, pFive, pSix, pSeven, pEight, pNine, pTen, pJack, pQueen, pKing, pAce);
TSuite = (sDiamonds, sSpades, sHearts, sClubs);
const
cPipNames: array[TPip] of string = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', ... |
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 ...... | #Crystal | Crystal | require "big"
def pi
q, r, t, k, n, l = [1, 0, 1, 1, 3, 3].map { |n| BigInt.new(n) }
dot_written = false
loop do
if 4*q + r - t < n*t
yield n
unless dot_written
yield '.'
dot_written = true
end
nr = 10*(r - n*t)
n = ((10*(3*q + r)) / t) - 10*n
q *= 10
... |
http://rosettacode.org/wiki/Periodic_table | Periodic table | Task
Display the row and column in the periodic table of the given atomic number.
The periodic table
Let us consider the following periodic table representation.
__________________________________________________________________________
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1... | #Phix | Phix | with javascript_semantics
constant match_wp = false
function prc(integer n)
constant t = {0,2,10,18,36,54,86,118,119}
integer row = abs(binary_search(n,t,true))-1,
col = n-t[row]
if col>1+(row>1) then
col = 18-(t[row+1]-n)
if match_wp then
if col<=2 then return {row+... |
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... | #JavaScript | JavaScript | let players = [
{ name: '', score: 0 },
{ name: '', score: 0 }
];
let curPlayer = 1,
gameOver = false;
players[0].name = prompt('Your name, player #1:').toUpperCase();
players[1].name = prompt('Your name, player #2:').toUpperCase();
function roll() { return 1 + Math.floor(Math.random()*6) }
function round... |
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... | #EchoLisp | EchoLisp |
(lib 'sequences)
(define (pernicious? n) (prime? (bit-count n)))
(define pernicious (filter pernicious? [1 .. ]))
(take pernicious 25)
→ (3 5 6 7 9 10 11 12 13 14 17 18 19 20 21 22 24 25 26 28 31 33 34 35 36)
(take (filter pernicious? [888888877 .. 888888889]) #:all)
→ (888888877 888888878 888888880 888... |
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation | Permutations/Rank of a permutation | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers
0..
(
n
!
−
1
)
{\displaystyle 0..(n!-1)}
to an ordering of all the permutations of the integers
0..
(
n
−
1
)
{\disp... | #Scala | Scala | import scala.math._
def factorial(n: Int): BigInt = {
(1 to n).map(BigInt.apply).fold(BigInt(1))(_ * _)
}
def indexToPermutation(n: Int, x: BigInt): List[Int] = {
indexToPermutation((0 until n).toList, x)
}
def indexToPermutation(ns: List[Int], x: BigInt): List[Int] = ns match {
case Nil => Nil
case _ => ... |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be c... | #Prolog | Prolog |
?- use_module(library(heaps)).
three_smooth(Lz) :-
singleton_heap(H, 1, nothing),
lazy_list(next_3smooth, 0-H, Lz).
next_3smooth(Top-H0, N-H2, N) :-
min_of_heap(H0, Top, _), !,
get_from_heap(H0, Top, _, H1),
next_3smooth(Top-H1, N-H2, N).
next_3smooth(_-H0, N-H3, N) :-
get_from_heap(H0, N,... |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Randomize
Dim randInt As Integer
For i As Integer = 1 To 5
randInt = Int(Rnd * 10)
Print a(randInt)
Next
Sleep |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Frink | Frink | a = ["one", "two", "three"]
println[random[a]] |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
... | #VBA | VBA | Option Explicit
Sub FirstTwentyPrimes()
Dim count As Integer, i As Long, t(19) As String
Do
i = i + 1
If IsPrime(i) Then
t(count) = i
count = count + 1
End If
Loop While count <= UBound(t)
Debug.Print Join(t, ", ")
End Sub
Function IsPrime(Nb As Long) As Boolean
If Nb... |
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... | #Frink | Frink | a = "rosetta code phrase reversal"
println[reverse[a]]
println[join["", map["reverse", wordList[a]]]]
println[reverseWords[a]] // Built-in function
// Alternately, the above could be
// join["", reverse[wordList[a]]]
|
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... | #Gambas | Gambas | Public Sub Main()
Dim sString As String = "rosetta code phrase reversal" 'The string
Dim sNewString, sTemp As String 'String variables
Dim siCount As Short 'Counter
Dim sWord As New String[] 'Word store
For siCount = Len(sString... |
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... | #EchoLisp | EchoLisp |
(lib 'list) ;; in-permutations
(lib 'bigint)
;; generates derangements by filtering out permutations
(define (derangement? nums) ;; predicate
(for/and ((n nums) (i (length nums))) (!= n i)))
(define (derangements n)
(for/list ((p (in-permutations n))) #:when (derangement? p) p))
(define (count-derangeme... |
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 ... | #Elixir | Elixir | defmodule Permutation do
def by_swap(n) do
p = Enum.to_list(0..-n) |> List.to_tuple
by_swap(n, p, 1)
end
defp by_swap(n, p, s) do
IO.puts "Perm: #{inspect for i <- 1..n, do: abs(elem(p,i))} Sign: #{s}"
k = 0 |> step_up(n, p) |> step_down(n, p)
if k > 0 do
pk = elem(p,k)
i = if 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 ... | #F.23 | F# |
(*Implement Johnson-Trotter algorithm
Nigel Galloway January 24th 2017*)
module Ring
let PlainChanges (N:'n[]) = seq{
let gn = [|for n in N -> 1|]
let ni = [|for n in N -> 0|]
let gel = Array.length(N)-1
yield N
let rec _Ni g e l = seq{
match (l,g) with
|_ when l<0 -> gn.[g] <- -gn.[g]; yield!... |
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... | #Haskell | Haskell | binomial n m = (f !! n) `div` (f !! m) `div` (f !! (n - m))
where f = scanl (*) 1 [1..]
permtest treat ctrl = (fromIntegral less) / (fromIntegral total) * 100
where
total = binomial (length avail) (length treat)
less = combos (sum treat) (length treat) avail
avail = ctrl ++ treat
combos total n a@(x:xs)
| to... |
http://rosettacode.org/wiki/Percolation/Mean_cluster_density | Percolation/Mean cluster density |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Let
c
{\disp... | #C | C | #include <stdio.h>
#include <stdlib.h>
int *map, w, ww;
void make_map(double p)
{
int i, thresh = RAND_MAX * p;
i = ww = w * w;
map = realloc(map, i * sizeof(int));
while (i--) map[i] = -(rand() < thresh);
}
char alpha[] = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
#define ALEN ((int)(si... |
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... | #11l | 11l | F perf(n)
V sum = 0
L(i) 1 .< n
I n % i == 0
sum += i
R sum == n
L(i) 1..10000
I perf(i)
print(i, end' ‘ ’) |
http://rosettacode.org/wiki/Percolation/Bond_percolation | Percolation/Bond percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N... | #11l | 11l | UInt32 seed = 0
F nonrandom()
:seed = 1664525 * :seed + 1013904223
R Int(:seed >> 16) / Float(FF'FF)
T Grid
[[Int]] cell, hwall, vwall
F (cell, hwall, vwall)
.cell = cell
.hwall = hwall
.vwall = vwall
V (M, nn, t) = (10, 10, 100)
T PercolatedException
(Int, Int) t
F (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... | #D | D | import std.stdio, std.range, std.algorithm, std.random, std.math;
enum n = 100, p = 0.5, t = 500;
double meanRunDensity(in size_t n, in double prob) {
return n.iota.map!(_ => uniform01 < prob)
.array.uniq.sum / double(n);
}
void main() {
foreach (immutable p; iota(0.1, 1.0, 0.2)) {
immu... |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N... | #Factor | Factor | USING: arrays combinators combinators.short-circuit formatting
fry generalizations io kernel math math.matrices math.order
math.ranges math.vectors prettyprint random sequences ;
IN: rosetta-code.site-percolation
SYMBOLS: ▓ . v ;
: randomly-filled-matrix ( m n probability -- matrix )
[ random-unit > ▓ . ? ] cur... |
http://rosettacode.org/wiki/Percolation/Site_percolation | Percolation/Site percolation |
Percolation Simulation
This is a simulation of aspects of mathematical percolation theory.
For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density
Given an
M
×
N... | #Fortran | Fortran |
! loosely translated from python.
! compilation: gfortran -Wall -std=f2008 thisfile.f08
!$ a=site && gfortran -o $a -g -O0 -Wall -std=f2008 $a.f08 && $a
!100 trials per
!Fill Fraction goal(%) simulated through paths(%)
! 0 0
! 10 0
! 2... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program permutation64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantes... |
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 ... | #ALGOL_68 | ALGOL 68 | # returns an array of the specified length, initialised to an ascending sequence of integers #
OP DECK = ( INT length )[]INT:
BEGIN
[ 1 : length ]INT result;
FOR i TO UPB result DO result[ i ] := i OD;
result
END # DECK # ;
# in-place shuffles the deck as per the task requirement... |
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
... | #Factor | Factor | x floor >integer 255 bitand :> X
y floor >integer 255 bitand :> Y
z floor >integer 255 bitand :> Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.