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/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for... | #Sidef | Sidef | func solve_pell(n) {
var x = n.isqrt
var y = x
var z = 1
var r = 2*x
var (e1, e2) = (1, 0)
var (f1, f2) = (0, 1)
loop {
y = (r*z - y)
z = floor((n - y*y) / z)
r = floor((x + y) / z)
(e1, e2) = (e2, r*e2 + e1)
(f1, f2) = (f2, r*f2 + f1)
... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #11l | 11l | F pascal_upp(n)
V s = [[0] * n] * n
s[0] = [1] * n
L(i) 1 .< n
L(j) i .< n
s[i][j] = s[i - 1][j - 1] + s[i][j - 1]
R s
F pascal_low(n)
V upp = pascal_upp(n)
V s = [[0] * n] * n
L(x) 0 .< n
L(y) 0 .< n
s[y][x] = upp[x][y]
R s
F pascal_sym(n)
V s = [[1] * n] * ... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #11l | 11l | F pascal(n)
V row = [1]
V k = [0]
L 0 .< max(n, 0)
print(row.join(‘ ’).center(16))
row = zip(row [+] k, k [+] row).map((l, r) -> l + r)
pascal(7) |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #11l | 11l | F partial(f, g)
F fg(x)
R @f(@g, x)
R fg
F main()
F ffs(f, x)
R x.map(a -> @f(a))
F f1(a) {R a * 2}
F f2(a) {R a * a}
V fsf1 = partial(ffs, f1)
V fsf2 = partial(ffs, f2)
print(fsf1([1, 2, 3, 4]))
print(fsf2([1, 2, 3, 4]))
main() |
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes | Partition an integer x into n primes | Task
Partition a positive integer X into N distinct primes.
Or, to put it in another way:
Find N unique primes such that they add up to X.
Show in the output section the sum X and the N primes in ascending order separated by plus (+) signs:
• partition 99809 with 1 prime.
... | #C.2B.2B | C++ | #include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
std::vector<int> primes;
struct Seq {
public:
bool empty() {
return p < 0;
}
int front() {
return p;
}
void popFront() {
if (p == 2) {
p++;
} else {
p += 2... |
http://rosettacode.org/wiki/Partition_function_P | Partition function P |
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers.
Example
P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1)
P(n) can be expressed as the recurrence relation:
P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)... | #F.23 | F# |
// PartionP: Nigel Galloway. April 12th., 2021
let pP g=let rec fN i g e l=seq{yield(l,e+i);yield(-l,e+i+g);yield! fN(i+1)(g+2)(e+i+g)(-l)}
let N,G=Array.create(g+1) 1I,seq{yield (1I,1);yield! fN 1 3 1 1I}|>Seq.takeWhile(fun(_,n)->n<=g)|>List.ofSeq
seq{2..g}|>Seq.iter(fun p->N.[p]<-G|>List.takeWhile... |
http://rosettacode.org/wiki/Partition_function_P | Partition function P |
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers.
Example
P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1)
P(n) can be expressed as the recurrence relation:
P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)... | #Factor | Factor | USING: kernel lists lists.lazy math sequences sequences.extras ;
! Compute the nth pentagonal number.
: penta ( n -- m ) [ sq 3 * ] [ - 2/ ] bi ;
! An infinite lazy list of indices to add and subtract in the
! sequence of partitions to find the next P.
: seq ( -- list )
1 lfrom [ penta 1 - ] <lazy-map> 1 lfrom ... |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #Clojure | Clojure | (def bottom [ [0 1 0], [11 0 0], [0 1 1], [4 0 0], [0 0 1] ])
(defn plus [v1 v2] (vec (map + v1 v2)))
(defn minus [v1 v2] (vec (map - v1 v2)))
(defn scale [n v] (vec (map #(* n %) v )))
(defn above [row] (map #(apply plus %) (partition 2 1 row)))
(def rows (reverse (take 5 (iterate above bottom)))) |
http://rosettacode.org/wiki/Peaceful_chess_queen_armies | Peaceful chess queen armies | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ... | #Julia | Julia | using Gtk
struct Position
row::Int
col::Int
end
function place!(numeach, bsize, bqueens, wqueens)
isattack(q, pos) = (q.row == pos.row || q.col == pos.col ||
abs(q.row - pos.row) == abs(q.col - pos.col))
noattack(qs, pos) = !any(x -> isattack(x, pos), qs)
positionopen(bqs... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Common_Lisp | Common Lisp |
(defvar *lowercase* '(#\a #\b #\c #\d #\e #\f #\g #\h #\i #\j #\k #\l #\m
#\n #\o #\p #\q #\r #\s #\t #\u #\v #\w #\x #\y #\z))
(defvar *uppercase* '(#\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L #\M
#\N #\O #\P #\Q #\R #\S #\T #\U #\V #\W #\X #\Y #\Z))
(defvar *numbe... |
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... | #Ruby | Ruby | p [1,2,3].permutation.to_a |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Quackery | Quackery | [ $ "turtleduck.qky" loadfile ] now!
[ stack ] is switch.arg ( --> [ )
[ switch.arg put ] is switch ( x --> )
[ switch.arg release ] is otherwise ( --> )
[ switch.arg share
!= iff ]else[ done
otherwise ]'[ do ]done[ ] is case ( ... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #R | R |
#to install hilbercurve library, biocmanager needs to be installed first
install.packages("BiocManager")
BiocManager::install("HilbertCurve")
#loading library and setting seed for random numbers
library(HilbertCurve)
library(circlize)
set.seed(123)
#4th order peano curve is generated
for(i in 1:512) {
peano =... |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #Lua | Lua |
function penny_game()
local player, computer = "", ""
function player_choose()
io.write( "Enter your sequence of three H and/or T: " )
local t = io.read():upper()
if #t > 3 then t = t:sub( 1, 3 )
elseif #t < 3 then return ""
end
for i = 1, 3 do
c =... |
http://rosettacode.org/wiki/Pathological_floating_point_problems | Pathological floating point problems | Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
0.1 + 0.2 = 0.30000000000000004
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological pro... | #jq | jq | # Input: the value at which to compute v
def v:
# Input: cache
# Output: updated cache
def v_(n):
(n|tostring) as $s
| . as $cache
| if ($cache | has($s)) then .
else if n == 1 then $cache["1"] = 2
elif n == 2 then $cache["2"] = -4
else ($cache | v_(n-1) | v_(n - 2)) as $ne... |
http://rosettacode.org/wiki/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for... | #Swift | Swift | func solvePell<T: BinaryInteger>(n: T, _ a: inout T, _ b: inout T) {
func swap(_ a: inout T, _ b: inout T, mul by: T) {
(a, b) = (b, b * by + a)
}
let x = T(Double(n).squareRoot())
var y = x
var z = T(1)
var r = x << 1
var e1 = T(1)
var e2 = T(0)
var f1 = T(0)
var f2 = T(1)
while true {
... |
http://rosettacode.org/wiki/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Module Module1
Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)
Dim t As BigInteger = a : a = b : b = b * c + t
End Sub
Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)
Dim x As Integer = Math.Sqrt(n), y As Integer = x, ... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #360_Assembly | 360 Assembly | * Pascal matrix generation - 10/06/2018
PASCMATR CSECT
USING PASCMATR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
S... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #360_Assembly | 360 Assembly | * Pascal's triangle 25/10/2015
PASCAL CSECT
USING PASCAL,R15 set base register
LA R7,1 n=1
LOOPN C R7,=A(M) do n=1 to m
BH ELOOPN if n>m then goto
MVC U,=F'1' u(1)=1
LA R8,PG ... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Ada | Ada | with Ada.Text_IO;
procedure Partial_Function_Application is
type Sequence is array(Positive range <>) of Integer;
-- declare a function FS with a generic parameter F and a normal parameter S
generic
with function F(I: Integer) return Integer; -- generic parameter
function FS (S: Sequence) return... |
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes | Partition an integer x into n primes | Task
Partition a positive integer X into N distinct primes.
Or, to put it in another way:
Find N unique primes such that they add up to X.
Show in the output section the sum X and the N primes in ascending order separated by plus (+) signs:
• partition 99809 with 1 prime.
... | #D | D | import std.array : array;
import std.range : take;
import std.stdio;
bool isPrime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d*d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return fal... |
http://rosettacode.org/wiki/Partition_function_P | Partition function P |
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers.
Example
P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1)
P(n) can be expressed as the recurrence relation:
P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)... | #FreeBASIC | FreeBASIC | Function PartitionsP(n As UInteger) As ULongInt
' if n > 416, the result becomes to large for a unsigned 64bit integer
Dim As ULongInt p(n)
Dim As UInteger k, j
p(0) = 1
For i As UInteger = 1 To n
k = 0
While TRUE
k += 1
j = (k * (3*k - 1)) \ 2
I... |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #Curry | Curry | import CLPFD
import Constraint (allC, andC)
import Findall (findall)
import List (init, last)
solve :: [[Int]] -> Success
solve body@([n]:rest) =
domain (concat body) 1 n
& andC (zipWith atop body rest)
& labeling [] (concat body)
where
xs `atop` ys = andC $ zipWith3 tri xs (init ys) (tail ys)
tri :... |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #D | D | import std.stdio, std.algorithm;
void iterate(bool doPrint=true)(double[] v, double[] diff) @safe {
static ref T E(T)(T[] x, in size_t row, in size_t col)
pure nothrow @safe @nogc {
return x[row * (row + 1) / 2 + col];
}
double tot = 0.0;
do {
// Enforce boundary conditions.
... |
http://rosettacode.org/wiki/Peaceful_chess_queen_armies | Peaceful chess queen armies | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ... | #Kotlin | Kotlin | import kotlin.math.abs
enum class Piece {
Empty,
Black,
White,
}
typealias Position = Pair<Int, Int>
fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean {
if (m == 0) {
return true
}
var placingBlack = true
for (i in 0 un... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Crystal | Crystal | require "random/secure"
special_chars = true
similar = 0
require_groups = true
length = 20
count = 1
def show_usage
puts <<-USAGE
Passwords generator
Usage: pass2 [count] [-l<length>] [-s{0|1|2}] [-ng] [-ns]
count: number of passwords to be generated (default: 1)
-l<length>: le... |
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... | #Run_BASIC | Run BASIC | list$ = "h,e,l,l,o" ' supply list seperated with comma's
while word$(list$,d+1,",") <> "" 'Count how many in the list
d = d + 1
wend
dim theList$(d) ' place list in array
for i = 1 to d
theList$(i) = word$(list$,i,",")
next i
for i = 1 to d ' print the Permutations
for j = 2 to d
perm$ = ""
for k =... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Racket | Racket |
/* Jens Axel Søgaard, 27th December 2018*/
#lang racket
(require metapict metapict/mat)
;;; Turtle State
(define p (pt 0 0)) ; current position
(define d (vec 0 1)) ; current direction
(define c '()) ; line segments drawn so far
;;; Turtle Operations
(define (jump q) (set! p q))
(define (move q) (se... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Raku | Raku | use SVG;
role Lindenmayer {
has %.rules;
method succ {
self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
}
}
my $peano = 'L' but Lindenmayer( { 'L' => 'LFRFL-F-RFLFR+F+LFRFL', 'R' => 'RFLFR+F+LFRFL-F-RFLFR' } );
$peano++ xx 4;
my @points = (10, 10);
for $peano.comb {
... |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #MiniScript | MiniScript | randomTorH = function()
if rnd < 0.5 then return "T" else return "H"
end function
if rnd < 0.5 then
playerSeq = input("Input your sequence (e.g. HTH): ").upper
if playerSeq[1] == "T" then compSeq = "H" else compSeq = "T"
compSeq = compSeq + playerSeq[:2]
print "I choose: " + compSeq
else
compS... |
http://rosettacode.org/wiki/Pathological_floating_point_problems | Pathological floating point problems | Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
0.1 + 0.2 = 0.30000000000000004
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological pro... | #Julia | Julia | using Printf
# arbitrary precision
setprecision(2000)
# Task 1
function seq(n)
len = maximum(n)
r = Vector{BigFloat}(len)
r[1] = 2
if len > 1 r[2] = -4 end
for i in 3:len
r[i] = 111 - 1130 / r[i-1] + 3000 / (r[i-1] * r[i-2])
end
return r[n]
end
n = [1, 2, 3, 5, 10, 100]
v = s... |
http://rosettacode.org/wiki/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for... | #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var solvePell = Fn.new { |n|
n = BigInt.new(n)
var x = n.isqrt
var y = x.copy()
var z = BigInt.one
var r = x * 2
var e1 = BigInt.one
var e2 = BigInt.zero
var f1 = BigInt.zero
var f2 = BigInt.one
while (true) {
y = r*z - y
... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Action.21 | Action! | BYTE FUNC Index(BYTE i,j,dim)
RETURN (i*dim+j)
PROC PascalUpper(BYTE ARRAY mat BYTE dim)
BYTE i,j
FOR i=0 TO dim-1
DO
FOR j=0 TO dim-1
DO
IF i>j THEN
mat(Index(i,j,dim))=0
ELSEIF i=j OR i=0 THEN
mat(Index(i,j,dim))=1
ELSE
mat(Index(i,j,dim))=mat(Index(i-1,j-1,... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #8th | 8th |
\ print the array
: .arr \ a -- a
( . space ) a:each ;
: pasc \ a --
\ print the row
.arr cr
dup
\ create two rows from the first, one with a leading the other with a trailing 0
[0] 0 a:insert swap 0 a:push
\ add the arrays together to make the new one
' n:+ a:op ;
\ print the first 16 rows:
[1... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #ALGOL_68 | ALGOL 68 | MODE SET = FLEX[0]INT;
MODE F = PROC(INT)INT,
FS = PROC(SET)SET;
PROC fs = (F f, SET set)SET: (
[LWB set:UPB set]INT out;
FOR i FROM LWB set TO UPB set DO out[i]:=f(set[i]) OD;
out
);
PROC f1 = (INT value)INT: value * 2,
f2 = (INT value)INT: value ** 2;
FS fsf1 = fs(f1,),
fsf2 = fs(f2,);
[4... |
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes | Partition an integer x into n primes | Task
Partition a positive integer X into N distinct primes.
Or, to put it in another way:
Find N unique primes such that they add up to X.
Show in the output section the sum X and the N primes in ascending order separated by plus (+) signs:
• partition 99809 with 1 prime.
... | #F.23 | F# |
// Partition an integer as the sum of n primes. Nigel Galloway: November 27th., 2017
let rcTask n ng =
let rec fN i g e l = seq{
match i with
|1 -> if isPrime g then yield Some (g::e) else yield None
|_ -> yield! Seq.mapi (fun n a->fN (i-1) (g-a) (a::e) (Seq.skip (n+1) l)) (l|>Seq.takeWhile(fun n->(g-n)... |
http://rosettacode.org/wiki/Partition_function_P | Partition function P |
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers.
Example
P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1)
P(n) can be expressed as the recurrence relation:
P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)... | #Go | Go | package main
import (
"fmt"
"math/big"
"time"
)
var p []*big.Int
var pd []int
func partDiffDiff(n int) int {
if n&1 == 1 {
return (n + 1) / 2
}
return n + 1
}
func partDiff(n int) int {
if n < 2 {
return 1
}
pd[n] = pd[n-1] + partDiffDiff(n-1)
return pd[n]... |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #F.23 | F# |
#load"Packages\MathNet.Numerics.FSharp\MathNet.Numerics.fsx"
open MathNet.Numerics.LinearAlgebra
let A = matrix [
[ 1.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0. ]
[ -1.; 0.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0. ]
[ 0.; -1.; 1.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0... |
http://rosettacode.org/wiki/Peaceful_chess_queen_armies | Peaceful chess queen armies | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[ValidSpots, VisibleByQueen, SolveQueen, GetSolution]
VisualizeState[state_] := Module[{q, cells},
q = MapIndexed[If[#["q"] == -1, {}, Text[Style[#["q"], 24], #2]] &, state, {2}];
cells = MapIndexed[{If[OddQ[Total[#2]], FaceForm[],
FaceForm[GrayLevel[0.8]]], EdgeForm[Black],
Rectangle[#2 - 0.... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Elixir | Elixir | defmodule Password do
@lower Enum.map(?a..?z, &to_string([&1]))
@upper Enum.map(?A..?Z, &to_string([&1]))
@digit Enum.map(?0..?9, &to_string([&1]))
@other ~S"""
!"#$%&'()*+,-./:;<=>?@[]^_{|}~
""" |> String.codepoints |> List.delete_at(-1)
@all @lower ++ @upper ++ @digit ++ @other
def generator do
{len... |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Uni... | #Rust | Rust | pub fn permutations(size: usize) -> Permutations {
Permutations { idxs: (0..size).collect(), swaps: vec![0; size], i: 0 }
}
pub struct Permutations {
idxs: Vec<usize>,
swaps: Vec<usize>,
i: usize,
}
impl Iterator for Permutations {
type Item = Vec<usize>;
fn next(&mut self) -> Option<Self:... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Ruby | Ruby |
load_library :grammar
# Peano class
class Peano
include Processing::Proxy
attr_reader :draw_length, :vec, :theta, :axiom, :grammar
DELTA = 60 # degrees
def initialize(vec)
@axiom = 'XF' # Axiom
rules = {
'X' => 'X+YF++YF-FX--FXFX-YF+', # LSystem Rules
'Y' => '-FX+YFYF++YF+FX--FX-Y'
}... |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #Nim | Nim | import os, random, sequtils, strutils
randomize()
let first = sample([false, true])
var you, me = ""
if first:
me = newSeqWith(3, sample("HT")).join()
echo "I choose first and will win on first seeing $# in the list of tosses." % me
while you.len != 3 or not allCharsInSet(you, {'H', 'T'}) or you == me:
... |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #Pascal | Pascal | PROGRAM Penney;
TYPE
CoinToss = (heads, tails);
Sequence = array [1..3] of CoinToss;
Player = record
bet: Sequence;
score: integer;
end;
VAR
Human, Computer: Player;
Rounds, Count: integer;
Function TossCoin: CoinToss;
{ Returns heads or tails at random }
Begin
if rando... |
http://rosettacode.org/wiki/Pathological_floating_point_problems | Pathological floating point problems | Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
0.1 + 0.2 = 0.30000000000000004
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological pro... | #Kotlin | Kotlin | // version 1.0.6
import java.math.*
const val LIMIT = 100
val con480 = MathContext(480)
val bigTwo = BigDecimal(2)
val bigE = BigDecimal("2.71828182845904523536028747135266249775724709369995") // precise enough!
fun main(args: Array<String>) {
// v(n) sequence task
val c1 = BigDecimal(111)
val ... |
http://rosettacode.org/wiki/Pell%27s_equation | Pell's equation | Pell's equation (also called the Pell–Fermat equation) is a Diophantine equation of the form:
x2 - ny2 = 1
with integer solutions for x and y, where n is a given non-square positive integer.
Task requirements
find the smallest solution in positive integers to Pell's equation for... | #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn solve_pell(n){
x,y,z,r := BI(n).root(2), x.copy(), BI(1), x*2;
e1,e2, f1,f2 := BI(1), BI(0), BI(0), BI(1);
reg t; // a,b = c,d is a=c; b=d
do(30_000){ // throttle this in case of screw up
y,z,r = (r*z - y), (n - y*y)/z, (x + y)/z;
t,e... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #Ada | Ada | -- for I/O
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
-- for estimating the maximum width of a column
with Ada.Numerics.Generic_Elementary_Functions;
procedure PascalMatrix is
type Matrix is array (Positive range <>, Posit... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #Action.21 | Action! | PROC Main()
BYTE count=[10],row,item
CHAR ARRAY s(5)
INT v
FOR row=0 TO count-1
DO
v=1
FOR item=0 TO row
DO
StrI(v,s)
Position(2*(count-row)+4*item-s(0),row+1)
Print(s)
v=v*(row-item)/(item+1)
OD
PutE()
OD
RETURN |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #AppleScript | AppleScript | -- PARTIAL APPLICATION --------------------------------------------
on f1(x)
x * 2
end f1
on f2(x)
x * x
end f2
on run
tell curry(map)
set fsf1 to |λ|(f1)
set fsf2 to |λ|(f2)
end tell
{fsf1's |λ|({0, 1, 2, 3}), ¬
fsf2's |λ|({0, 1, 2, 3}), ¬
fsf1's |λ|({2, 4,... |
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes | Partition an integer x into n primes | Task
Partition a positive integer X into N distinct primes.
Or, to put it in another way:
Find N unique primes such that they add up to X.
Show in the output section the sum X and the N primes in ascending order separated by plus (+) signs:
• partition 99809 with 1 prime.
... | #Factor | Factor | USING: formatting fry grouping kernel math.combinatorics
math.parser math.primes sequences ;
: partition ( x n -- str )
over [ primes-upto ] 2dip '[ sum _ = ] find-combination
[ number>string ] map "+" join ;
: print-partition ( x n seq -- )
[ "no solution" ] when-empty
"Partitioned %5d with %2d pri... |
http://rosettacode.org/wiki/Partition_function_P | Partition function P |
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers.
Example
P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1)
P(n) can be expressed as the recurrence relation:
P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)... | #Java | Java | import java.math.BigInteger;
public class PartitionFunction {
public static void main(String[] args) {
long start = System.currentTimeMillis();
BigInteger result = partitions(6666);
long end = System.currentTimeMillis();
System.out.println("P(6666) = " + result);
System.out... |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #Factor | Factor | USING: arrays backtrack combinators.extras fry grouping.extras
interpolate io kernel math math.ranges sequences ;
: base ( ?x ?z -- seq ) 2dup + swap '[ _ 11 _ 4 _ ] >array ;
: up ( seq -- seq' ) [ [ + ] 2clump-map ] twice ;
: find-solution ( -- x z )
10 [1,b] dup [ amb-lazy ] bi@ 2dup base
up dup first 4... |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #FreeBASIC | FreeBASIC | Function SolveForZ(x As Integer) As Integer
Dim As Integer a, b, c, d, e, f, g, h, z
For z = 0 To 20
e = x + 11
f = 11 + (x+z)
g = (x+z) + 4
h = 4 + z
If e + f = 40 Then
c = f + g
d = g + h
a = 40 + c
b = c + d
... |
http://rosettacode.org/wiki/Peaceful_chess_queen_armies | Peaceful chess queen armies | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ... | #Nim | Nim | import sequtils, strformat
type
Piece {.pure.} = enum Empty, Black, White
Position = tuple[x, y: int]
func isAttacking(queen, pos: Position): bool =
queen.x == pos.x or queen.y == pos.y or abs(queen.x - pos.x) == abs(queen.y - pos.y)
func place(m, n: int; blackQueens, whiteQueens: var seq[Position]): ... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #F.23 | F# |
// A function to generate passwords of a given length. Nigel Galloway: May 2nd., 2018
let N = (set)"qwertyuiopasdfghjklzxcvbnm"
let I = (set)"QWERTYUIOPASDFGHJKLZXCVBNM"
let G = (set)"7894561230"
let E = (set)"""!"#$%&'()*+,-./:;<=>?@[]^_{|}~[||]"""
let L = Array.ofSeq (Set.unionMany [N;I;G;E])
let y = System.Random ... |
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... | #SAS | SAS | /* Store permutations in a SAS dataset. Translation of Fortran 77 */
data perm;
n=6;
array a{6} p1-p6;
do i=1 to n;
a(i)=i;
end;
L1:
output;
link L2;
if next then goto L1;
stop;
L2:
next=0;
i=n-1;
L10:
if a(i)<a(i+1) then goto L20;
i=i-1;
if i=0 then goto L20;
goto L10;
L20:
j=i+1;
... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Rust | Rust | // [dependencies]
// svg = "0.8.0"
use svg::node::element::path::Data;
use svg::node::element::Path;
struct PeanoCurve {
current_x: f64,
current_y: f64,
current_angle: i32,
line_length: f64,
}
impl PeanoCurve {
fn new(x: f64, y: f64, length: f64, angle: i32) -> PeanoCurve {
PeanoCurve ... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Sidef | Sidef | var rules = Hash(
l => 'lFrFl-F-rFlFr+F+lFrFl',
r => 'rFlFr+F+lFrFl-F-rFlFr',
)
var lsys = LSystem(
width: 500,
height: 500,
xoff: -50,
yoff: -50,
len: 5,
angle: 90,
color: 'dark green',
)
lsys.execute('l', 4, "peano_curve.png", rules) |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #Perl | Perl |
#!usr/bin/perl
use 5.020;
use strict;
use warnings;
#Choose who goes first
binaryRand() == 0 ? flipCoin(userFirst()) : flipCoin(compFirst());
#Return a randomly generated 1 or 0
sub binaryRand
{
return int(rand(2));
}
#Converts 1's and 0's to H's and T's, respectively.
sub convert
{
my $randNum = binaryR... |
http://rosettacode.org/wiki/Pathological_floating_point_problems | Pathological floating point problems | Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
0.1 + 0.2 = 0.30000000000000004
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological pro... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | v[1] = 2;
v[2] = -4;
v[n_] := Once[111 - 1130/v[n - 1] + 3000/(v[n - 1]*v[n - 2])]
N[Map[v, {3, 4, 5, 6, 7, 8, 20, 30, 50, 100}], 80] |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns an upper Pascal matrix of size n #
PROC upper pascal matrix = ( INT n )[,]INT:
BEGIN
[ 1 : n, 1 : n ]INT result;
FOR j TO n DO result[ 1, j ] := 1 OD;
FOR i FROM 2 TO n DO
result[ i, 1 ] := 0;
FOR j FROM 2 TO n D... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #Ada | Ada | package Pascal is
type Row is array (Natural range <>) of Natural;
function Length(R: Row) return Positive;
function First_Row(Max_Length: Positive) return Row;
function Next_Row(R: Row) return Row;
end Pascal; |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #11l | 11l | -V ops = ‘-+/*^’
F postfix_to_infix(postfix)
T Expression
String op, ex
prec = 3
F (String e1, e2 = ‘’, o = ‘’)
I o == ‘’
.ex = e1
E
.ex = e1‘ ’o‘ ’e2
.op = o
.prec = :ops.index(o) I/ 2
F String()
R .ex
[Exp... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #BBC_BASIC | BBC BASIC | fsf1 = FNpartial(PROCfs(), FNf1())
fsf2 = FNpartial(PROCfs(), FNf2())
DIM seq(3)
PRINT "Calling function fsf1 with sequence 1:"
seq() = 0, 1, 2, 3 : PROC(fsf1)(seq())
FOR i% = 0 TO 3 : PRINT seq(i%); : NEXT : PRINT
PRINT "Calling function fsf1 with sequence 2:"
seq() = ... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #Bracmat | Bracmat | ( (fs=/('(x./('(y.map'($x.$y))))))
& (f1=/('(x.$x*2)))
& (f2=/('(x.$x^2)))
& (partial=/('(x./('(y.($x)$($y))))))
& (!partial$!fs)$!f1:?fsf1
& (!partial$!fs)$!f2:?fsf2
& out$(!fsf1$(0 1 2 3))
& out$(!fsf2$(0 1 2 3))
& out$(!fsf1$(2 4 6 8))
& out$(!fsf2$(2 4 6 8))
); |
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes | Partition an integer x into n primes | Task
Partition a positive integer X into N distinct primes.
Or, to put it in another way:
Find N unique primes such that they add up to X.
Show in the output section the sum X and the N primes in ascending order separated by plus (+) signs:
• partition 99809 with 1 prime.
... | #Go | Go | package main
import (
"fmt"
"log"
)
var (
primes = sieve(100000)
foundCombo = false
)
func sieve(limit uint) []uint {
primes := []uint{2}
c := make([]bool, limit+1) // composite = true
// no need to process even numbers > 2
p := uint(3)
for {
p2 := p * p
if ... |
http://rosettacode.org/wiki/Partition_function_P | Partition function P |
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers.
Example
P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1)
P(n) can be expressed as the recurrence relation:
P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)... | #JavaScript | JavaScript |
function p(n){
var a = new Array(n+1)
a[0] = 1n
for (let i = 1; i <= n; i++){
a[i] = 0n
for (let k = 1, s = 1; s <= i;){
a[i] += (k & 1 ? a[i-s]:-a[i-s])
k > 0 ? (s += k, k = -k):(k = -k+1, s = k*(3*k-1)/2)
}
}
return a[n]
}
var t = Date.now()
... |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #Go | Go | package main
import "fmt"
// representation of an expression in x, y, and z
type expr struct {
x, y, z float64 // coefficients
c float64 // constant term
}
// add two expressions
func addExpr(a, b expr) expr {
return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}
// subtract two expres... |
http://rosettacode.org/wiki/Peaceful_chess_queen_armies | Peaceful chess queen armies | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ... | #Perl | Perl | use strict;
use warnings;
my $m = shift // 4;
my $n = shift // 5;
my %seen;
my $gaps = join '|', qr/-*/, map qr/.{$_}(?:-.{$_})*/s, $n-1, $n, $n+1;
my $attack = qr/(\w)(?:$gaps)(?!\1)\w/;
place( scalar ('-' x $n . "\n") x $n );
print "No solution to $m $n\n";
sub place
{
local $_ = shift;
$seen{$_}++ || /$a... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #Factor | Factor | USING: arrays assocs combinators command-line continuations io
kernel math math.parser multiline namespaces peg.ebnf
prettyprint random sequences ;
FROM: sets => without ;
IN: rosetta-code.password-generator
STRING: usage
password-generator generates random passwords.
Commands:
-l [int>=4] Set password length ... |
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... | #Scala | Scala | List(1, 2, 3).permutations.foreach(println) |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #VBA | VBA | Const WIDTH = 243 'a power of 3 for a evenly spaced curve
Dim n As Long
Dim points() As Single
Dim flag As Boolean
'Store the coordinate pairs (x, y) generated by Peano into
'a SafeArrayOfPoints with lineto. The number of points
'generated depend on WIDTH. Peano is called twice. Once
'to count the number of points, and... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Wren | Wren | import "graphics" for Canvas, Color, Point
import "dome" for Window
class Game {
static init() {
Window.title = "Peano curve"
Canvas.resize(820, 820)
Window.resize(820, 820)
Canvas.cls(Color.white) // white background
__points = []
__width = 81
peano(0, 0, _... |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #Phix | Phix | function trio(integer pick)
return substitute_all(sprintf("%03b",pick),"10","HT")
end function
function getuser(integer bot)
integer user
while 1 do
user = 8 -- (a bit that clears after 3 shifts)
printf(1,"Enter your sequence of 3 (H/T):");
while user>7 do
integer c = upper... |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #PicoLisp | PicoLisp | (seed (in "/dev/urandom" (rd 8)))
(setq *S (list 0 0))
(de toss (N)
(make
(do N
(link (if (rand T) "T" "H")) ) ) )
(de comp (A Lst)
(or
(for ((I . L) Lst (cddr L) (cdr L))
(T (fully = A L) I) )
T ) )
(de score NIL
(prinl)
(prinl "Total score:")
(prinl "^Iuser: ... |
http://rosettacode.org/wiki/Pathological_floating_point_problems | Pathological floating point problems | Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
0.1 + 0.2 = 0.30000000000000004
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological pro... | #Nim | Nim | import math, strutils, strformat
import decimal
import bignum
####################################################################################################
# Utilities.
proc format[T: DecimalType|Rat](val: T; intLen, fractLen: Positive): string =
## Format a decimal or a rational with "intLen" integer digi... |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #11l | 11l | F infix_to_postfix(infix)
-V ops = ‘-+/*^’
V sb = ‘’
[Int] s
L(token) infix.split(re:‘\s’)
I token.empty
L.continue
V c = token[0]
V? idx = ops.find(c)
I idx != N
I s.empty
s.append(idx)
E
L !s.empty
V prec2 = s.la... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #ALGOL_W | ALGOL W | begin
% initialises m to an upper Pascal matrix of size n %
% the bounds of m must be at least 1 :: n, 1 :: n %
procedure upperPascalMatrix ( integer array m( *, * )
; integer value n
) ;
begin
for j := 1 until n do m( 1, j ) := 1... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #ALGOL_68 | ALGOL 68 | PRIO MINLWB = 8, MAXUPB = 8;
OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b),
MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);
OP + = ([]INT a,b)[]INT:(
[a MINLWB b:a MAXUPB b]INT out; FOR i FROM LWB out TO UPB out DO out[i]:= 0 OD;
out[LWB a:UPB a] := a; FOR i FROM LWB b TO UPB b DO out[i]+:= b[i] OD... |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #Ada | Ada |
type Priority is range 1..4;
type Infix is record
Precedence : Priority;
Expression : Unbounded_String;
end record;
package Expression_Stack is new Generic_Stack (Infix);
use Expression_Stack;
function Convert (RPN : String) return String is
Arguments : Stack;
procedure Pop... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #C | C | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <sys/wait.h>
#include <err.h>
typedef int (*intfunc)(int);
typedef void (*pfunc)(int*, int);
pfunc partial(intfunc fin)
{
pfunc f;
static int idx = 0;
char cc[256], lib[256];
FILE *fp;
sprintf(lib, "/tmp/stuff%d.so", ++idx);... |
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes | Partition an integer x into n primes | Task
Partition a positive integer X into N distinct primes.
Or, to put it in another way:
Find N unique primes such that they add up to X.
Show in the output section the sum X and the N primes in ascending order separated by plus (+) signs:
• partition 99809 with 1 prime.
... | #Haskell | Haskell | import Data.List (delete, intercalate)
import Data.Numbers.Primes (primes)
import Data.Bool (bool)
-------------------- PRIME PARTITIONS ---------------------
partitions :: Int -> Int -> [Int]
partitions x n
| n <= 1 =
[ x
| x == last ps ]
| otherwise = go ps x n
where
ps = takeWhile (<= x) primes
... |
http://rosettacode.org/wiki/Partition_function_P | Partition function P |
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers.
Example
P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1)
P(n) can be expressed as the recurrence relation:
P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)... | #Haskell | Haskell | {-# language DeriveFunctor #-}
------------------------------------------------------------
-- memoization utilities
data Memo a = Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2... |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the... | #Haskell | Haskell | puzzle = [["151"],["",""],["40","",""],["","","",""],["X","11","Y","4","Z"]] |
http://rosettacode.org/wiki/Peaceful_chess_queen_armies | Peaceful chess queen armies | In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour.
⇖
⇑
⇗
⇐
⇐
♛
⇒
⇒
⇙
⇓
⇘
⇙
⇓
⇘
⇓
The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ... | #Phix | Phix | --
-- demo\rosetta\Queen_Armies.exw
-- =============================
--
with javascript_semantics
requires("1.0.2") -- (puts(fn,x,false) for p2js.js)
string html = ""
constant as_html = true
constant queens = {``,
`♛`,
`<font color="green">♕</font>`,
`<span styl... |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above ch... | #FreeBASIC | FreeBASIC | Dim As String charS(4)
charS(1) = "0123456789"
charS(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
charS(3) = "abcdefghijklmnopqrstuvwxyz"
charS(4) = "!""#$%&'()*+,-./:;<=>?@[]^_{|}~"
charS(0) = charS(1) + charS(2) + charS(3) + charS(4)
Dim As Integer howBig, howMany
Do
Print !"------ Password Generator ------\n"
Input... |
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... | #Scheme | Scheme | (define (insert l n e)
(if (= 0 n)
(cons e l)
(cons (car l)
(insert (cdr l) (- n 1) e))))
(define (seq start end)
(if (= start end)
(list end)
(cons start (seq (+ start 1) end))))
(define (permute l)
(if (null? l)
'(())
(apply append (map (lambda (p)
... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #Yabasic | Yabasic | WIDTH = 243 //a power of 3 for a evenly spaced curve
open window 700, 700
Peano(0, 0, WIDTH, 0, 0)
Sub Peano(x, y, lg, i1, i2)
If (lg = 1) Then
line x * 3, y * 3
return
End If
lg = lg / 3
Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)
Peano(x + ((i1 - i2 + 1) * lg), y ... |
http://rosettacode.org/wiki/Peano_curve | Peano curve |
Task
Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
| #zkl | zkl | lsystem("L", // axiom
Dictionary("L","LFRFL-F-RFLFR+F+LFRFL", "R","RFLFR+F+LFRFL-F-RFLFR"), # rules
"+-F", 4) // constants, order
: turtle(_);
fcn lsystem(axiom,rules,consts,n){ // Lindenmayer system --> string
foreach k in (consts){ rules.add(k,k) }
buf1,buf2 := Data(Void,axiom).howza(3), Data().... |
http://rosettacode.org/wiki/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #Prolog | Prolog | play :- rand1(R), game(R).
game(h) :-
format('Your turn first!~n'), player_move(P),
response(P,C), format('I am choosing '), maplist(writec, C), nl,
rand3(R), maplist(writec,R),
roll(P, C, R).
game(t) :-
rand3(C),
format('I am choosing '), maplist(writec, C), nl,
player_move(P),
rand... |
http://rosettacode.org/wiki/Pathological_floating_point_problems | Pathological floating point problems | Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
0.1 + 0.2 = 0.30000000000000004
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological pro... | #PARI.2FGP | PARI/GP | V(n,a=2,v=-4.)=if(n < 3,return(v));V(n--,v,111-1130/v+3000/(v*a)) |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Gener... | #8th | 8th | \ Convert infix expression to postfix, using 'shunting-yard' algorithm
\ https://en.wikipedia.org/wiki/Shunting-yard_algorithm
\ precedence of infix tokens. negative means 'right-associative', otherwise left:
with: n
{
"+" : 2,
"-" : 2,
"/" : 3,
"*" : 3,
"^" : -4,
"(" : 1,
")" : -1
} var, tokens
... |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #APL | APL | upper ← ∘.!⍨¯1+⍳
lower ← ⍉(∘.!⍨¯1+⍳)
symmetric ← (⊢![1]∘.+⍨)¯1+⍳ |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi... | #AppleScript | AppleScript | -- PASCAL MATRIX -------------------------------------------------------------
-- pascalMatrix :: ((Int, Int) -> (Int, Int)) -> Int -> [[Int]]
on pascalMatrix(f, n)
chunksOf(n, map(compose(my bc, f), range({{0, 0}, {n - 1, n - 1}})))
end pascalMatrix
-- Binomial coefficient
-- bc :: (Int, Int) -> Int
on bc(nk)
... |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elemen... | #ALGOL_W | ALGOL W | begin
% prints the first n lines of Pascal's triangle lines %
% if n is <= 0, no output is produced %
procedure printPascalTriangle( integer value n ) ;
if n > 0 then begin
integer array pascalLine ( 1 :: n );
pascalLine( 1 ) := 1;
for line := 1 un... |
http://rosettacode.org/wiki/Parse_an_IP_Address | Parse an IP Address | The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.
Taking the following as inputs:
127.0.0.1
The "localhost" IPv4 address
127.0.0.1:80
The "localhost" IPv4 address, with a specified port (80)
::1
The "localhost" IPv6 address
[::1]:80
The "localhost" IPv6... | #AutoHotkey | AutoHotkey | ParseIP(Address){
return InStr(A_LoopField, ".") ? IPv4(Address) : IPv6(Address)
}
IPv4(Address){
for i, v in StrSplit(Address, "."){
x := StrSplit(v, ":")
num .= SubStr("00" . Format("{:X}", x.1), -1)
port := x.2 ? x.2 : ""
}
return [num, port]
}
IPv6(Address){
for i, v in StrSplit(Address, "]")
if i... |
http://rosettacode.org/wiki/Parametric_polymorphism | Parametric polymorphism | Parametric Polymorphism
type variables
Task
Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it.
A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ... | #Ada | Ada | generic
type Element_Type is private;
package Container is
type Tree is tagged private;
procedure Replace_All(The_Tree : in out Tree; New_Value : Element_Type);
private
type Node;
type Node_Access is access Node;
type Tree tagged record
Value : Element_type;
Left : Node_Access := null;
... |
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion | Parsing/RPN to infix conversion | Parsing/RPN to infix conversion
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation.... | #ALGOL_68 | ALGOL 68 |
# rpn to infix - parses an RPN expression and generates the equivalent #
# infix expression #
PROC rpn to infix = ( STRING rpn )STRING:
BEGIN
# we parse the string backwards using recursive descent #
INT rpn pos := UPB ... |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
class PartialFunctionApplication
{
static Func<T1, TResult> PartiallyApply<T1, T2, TResult>(Func<T1, T2, TResult> function, T2 argument2)
{
return argument1 => function(argument1, argument2);
}
static void Main()
{
... |
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes | Partition an integer x into n primes | Task
Partition a positive integer X into N distinct primes.
Or, to put it in another way:
Find N unique primes such that they add up to X.
Show in the output section the sum X and the N primes in ascending order separated by plus (+) signs:
• partition 99809 with 1 prime.
... | #J | J |
load 'format/printf'
NB. I don't know of any way to easily make an idiomatic lazy exploration,
NB. except falling back on explicit imperative control strutures.
NB. However this is clearly not where J shines neither with speed nor elegance.
primes_up_to =: monad def 'p: i. _1 p: 1 + y'
terms_as_text =: monad de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.