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/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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #J | J | pn =: -/@(+/)@:($:"0)@rec ` (x:@(0&=)) @. (0>:]) M.
rec=: - (-: (*"1) _1 1 +/ 3 * ]) @ (>:@i.@>.@%:@((2%3)&*)) |
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #jq | jq | def partitions($n):
def div2: (. - (.%2)) / 2;
reduce range(1; $n + 1) as $i ( {p: ([1] + [range(0;$n)|0])};
. + {k: 0, stop: false}
| until(.stop;
.k += 1
| (((.k * (3*.k - 1)) | div2) ) as $j
| if $j > $i then .stop=true
else if (.k % 2) == 1
then .p[$i] = .p[$i] + .p[$i - $j]
else .p[$i] = .p[$i] - .p[$i - $j]
end
| (((.k * (3*.k + 1)) | div2)) as $j
| if $j > $i then .stop=true
elif (.k % 2) == 1
then .p[$i] = .p[$i] + .p[$i - $j]
else .p[$i] = .p[$i] - .p[$i - $j]
end
end ))
| .p[$n] ;
[partitions(range(1;15))] |
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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #J | J | chk=:40 151&-:@(2 4{{."1) |
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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #Java | Java |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PascalsTrianglePuzzle {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d),
Arrays.asList(0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 1d, -1d),
Arrays.asList(0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d),
Arrays.asList(0d, 0d, 0d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, -1d),
Arrays.asList(1d, 1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, -1d, 0d, 1d, 0d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 1d, 1d, 0d, -1d, 0d, 0d, 0d),
Arrays.asList(0d, 0d, 0d, 0d, 0d, 0d, 1d, 1d, 0d, 0d, 0d));
List<Double> b = Arrays.asList(11d, 11d, 0d, 4d, 4d, 40d, 0d, 0d, 40d, 0d, 151d);
List<Double> solution = cramersRule(mat, b);
System.out.println("Solution = " + cramersRule(mat, b));
System.out.printf("X = %.2f%n", solution.get(8));
System.out.printf("Y = %.2f%n", solution.get(9));
System.out.printf("Z = %.2f%n", solution.get(10));
}
private static List<Double> cramersRule(Matrix matrix, List<Double> b) {
double denominator = matrix.determinant();
List<Double> result = new ArrayList<>();
for ( int i = 0 ; i < b.size() ; i++ ) {
result.add(matrix.replaceColumn(b, i).determinant() / denominator);
}
return result;
}
private static class Matrix {
private List<List<Double>> matrix;
@Override
public String toString() {
return matrix.toString();
}
@SafeVarargs
public Matrix(List<Double> ... lists) {
matrix = new ArrayList<>();
for ( List<Double> list : lists) {
matrix.add(list);
}
}
public Matrix(List<List<Double>> mat) {
matrix = mat;
}
public double determinant() {
if ( matrix.size() == 1 ) {
return get(0, 0);
}
if ( matrix.size() == 2 ) {
return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0);
}
double sum = 0;
double sign = 1;
for ( int i = 0 ; i < matrix.size() ; i++ ) {
sum += sign * get(0, i) * coFactor(0, i).determinant();
sign *= -1;
}
return sum;
}
private Matrix coFactor(int row, int col) {
List<List<Double>> mat = new ArrayList<>();
for ( int i = 0 ; i < matrix.size() ; i++ ) {
if ( i == row ) {
continue;
}
List<Double> list = new ArrayList<>();
for ( int j = 0 ; j < matrix.size() ; j++ ) {
if ( j == col ) {
continue;
}
list.add(get(i, j));
}
mat.add(list);
}
return new Matrix(mat);
}
private Matrix replaceColumn(List<Double> b, int column) {
List<List<Double>> mat = new ArrayList<>();
for ( int row = 0 ; row < matrix.size() ; row++ ) {
List<Double> list = new ArrayList<>();
for ( int col = 0 ; col < matrix.size() ; col++ ) {
double value = get(row, col);
if ( col == column ) {
value = b.get(row);
}
list.add(value);
}
mat.add(list);
}
return new Matrix(mat);
}
private double get(int row, int col) {
return matrix.get(row).get(col);
}
}
}
|
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 on an n-by-n square grid, (the board), so that no queen attacks another of a different colour.
Task
Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).
Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
Display here results for the m=4, n=5 case.
References
Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
A250000 OEIS
| #Python | Python | from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2)) # (x, y) tuples
placements = {frozenset(c) for c in combinations(board, m)}
for blacks in placements:
black_attacks = reduce(_or,
(queen_attacks_from(pos, n) for pos in blacks),
set())
for whites in {frozenset(c) # Never on blsck attacking squares
for c in combinations(board - black_attacks, m)}:
if not black_attacks & whites:
return blacks, whites
return set(), set()
@lru_cache(maxsize=None)
def queen_attacks_from(pos, n):
x0, y0 = pos
a = set([pos]) # Its position
a.update((x, y0) for x in range(n)) # Its row
a.update((x0, y) for y in range(n)) # Its column
# Diagonals
for x1 in range(n):
# l-to-r diag
y1 = y0 -x0 +x1
if 0 <= y1 < n:
a.add((x1, y1))
# r-to-l diag
y1 = y0 +x0 -x1
if 0 <= y1 < n:
a.add((x1, y1))
return a
def pboard(black_white, n):
"Print board"
if black_white is None:
blk, wht = set(), set()
else:
blk, wht = black_white
print(f"## {len(blk)} black and {len(wht)} white queens "
f"on a {n}-by-{n} board:", end='')
for x, y in product(range(n), repeat=2):
if y == 0:
print()
xy = (x, y)
ch = ('?' if xy in blk and xy in wht
else 'B' if xy in blk
else 'W' if xy in wht
else _bbullet if (x + y)%2 else _wbullet)
print('%s' % ch, end='')
print()
if __name__ == '__main__':
n=2
for n in range(2, 7):
print()
for m in count(1):
ans = place(m, n)
if ans[0]:
pboard(ans, n)
else:
print (f"# Can't place {m} queens on a {n}-by-{n} board")
break
#
print('\n')
m, n = 5, 7
ans = place(m, n)
pboard(ans, n) |
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 character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Gambas | Gambas | ' Gambas module file
' INSTRUCTIONS
' I have not used a GUI as you could not run this in the 'Gambas Playground'
' Click on the link above to run this program
' The user can specify the password length and the number of passwords
' to generate by altering the values of the 2 lines below.
Public Sub Main()
Dim siPasswordLength As Short = 20 'Password length
Dim siPasswordQuantity As Short = 20 'Password quantity
Dim sLower As String = "abcdefghijklmnopqrstuvwxyz" 'Lower case characters
Dim sUpper As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 'Upper case characters
Dim sNumber As String = "1234567890" 'Numbers
Dim sOther As String = "'!#$%&'()*+,-./:;<=>?@[]^_{|}~" & Chr(34) 'Other characters + quote
Dim sNoGo As String[] = ["I1", "1I", "l1", "1l", "Il",
"lI", "O0", "0O", "S5", "5S", "Z2", "2Z"] 'Undesirable string combinations (can be added to if required)
Dim sData As String = sLower & sUpper & sNumber & sOther 'Create 1 string to pick the password characters from
Dim sToCheck, sPassword As String 'To hold a possible password for checking, to hold the passwords
Dim siCount, siLoop, siCounter As Short 'Various counters
Dim bPass As Boolean 'To Pass or not to Pass!
For siCount = 1 To siPasswordQuantity 'Loop the amount of passwords required
For siLoop = 1 To siPasswordLength 'Loop for each charater of the required length
sToCheck &= Mid(sData, Rand(1, Len(sData)), 1) 'Get a random character from sData
Next
bPass = False 'Set bPass to False
For siCounter = 1 To Len(sToCheck) 'Loop through each character in the generated password
If InStr(sLower, Mid(sToCheck, siCounter, 1)) Then bPass = True 'If a LOWER CASE letter is included set bPass to True
Next
If bPass Then 'If bPass is True then
bPass = False 'bPass is False
For siCounter = 1 To Len(sToCheck) 'Loop through each character in the generated password
If InStr(sUpper, Mid(sToCheck, siCounter, 1)) Then bPass = True 'If an UPPER CASE letter is included set bPass to True
Next
End If
If bPass Then 'If bPass is True then
bPass = False 'bPass is False
For siCounter = 1 To Len(sToCheck) 'Loop through each character in the generated password
If InStr(sNumber, Mid(sToCheck, siCounter, 1)) Then bPass = True 'If a NUMBER is included set bPass to True
Next
End If
If bPass Then 'If bPass is True then
bPass = False 'bPass is False
For siCounter = 1 To Len(sToCheck) 'Loop through each character in the generated password
If InStr(sOther, Mid(sToCheck, siCounter, 1)) Then bPass = True 'If an 'OTHER CHARACTER' is included set bPass to True
Next
End If
If bPass Then
For siCounter = 1 To sNoGo.Max 'Loop through each undesirable strings e.g. "0O"
If InStr(sToCheck, sNoGo[siCounter]) Then bPass = False 'If an undesirable combination is located then set bPass to False
Next
Endif
If bPass = True Then 'If bPass is True (all checks have been passed) then
sPassword &= sToCheck & gb.NewLine 'Add the new password to sPassword with a newline
Else 'Else
Dec siCount 'Decrease the loop counter by one
Endif
sToCheck = "" 'Clear sToCheck
Next
Print sPassword 'Print the password list
End |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: permutations is array array integer;
const func permutations: permutations (in array integer: items) is func
result
var permutations: permsList is 0 times 0 times 0;
local
const proc: perms (in array integer: sequence, in array integer: prefix) is func
local
var integer: element is 0;
var integer: index is 0;
begin
if length(sequence) <> 0 then
for element key index range sequence do
perms(sequence[.. pred(index)] & sequence[succ(index) ..], prefix & [] (element));
end for;
else
permsList &:= prefix;
end if;
end func;
begin
perms(items, 0 times 0);
end func;
const proc: main is func
local
var array integer: perm is 0 times 0;
var integer: element is 0;
begin
for perm range permutations([] (1, 2, 3)) do
for element range perm do
write(element <& " ");
end for;
writeln;
end for;
end func; |
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 player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins.
Example
One player might choose the sequence HHT and the other THT.
Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence.
Task
Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent.
Who chooses and shows their sequence of three should be chosen randomly.
If going first, the computer should randomly choose its sequence of three.
If going second, the computer should automatically play the optimum sequence.
Successive coin tosses should be shown.
Show output of a game where the computer chooses first and a game where the user goes first here on this page.
See also
The Penney Ante Part 1 (Video).
The Penney Ante Part 2 (Video).
| #Python | Python | from __future__ import print_function
import random
from time import sleep
first = random.choice([True, False])
you = ''
if first:
me = ''.join(random.sample('HT'*3, 3))
print('I choose first and will win on first seeing {} in the list of tosses'.format(me))
while len(you) != 3 or any(ch not in 'HT' for ch in you) or you == me:
you = input('What sequence of three Heads/Tails will you win with: ')
else:
while len(you) != 3 or any(ch not in 'HT' for ch in you):
you = input('After you: What sequence of three Heads/Tails will you win with: ')
me = ('H' if you[1] == 'T' else 'T') + you[:2]
print('I win on first seeing {} in the list of tosses'.format(me))
print('Rolling:\n ', end='')
rolled = ''
while True:
rolled += random.choice('HT')
print(rolled[-1], end='')
if rolled.endswith(you):
print('\n You win!')
break
if rolled.endswith(me):
print('\n I win!')
break
sleep(1) # For dramatic effect |
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 problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.
This task's purpose is to show how your language deals with such classes of problems.
A sequence that seems to converge to a wrong limit.
Consider the sequence:
v1 = 2
v2 = -4
vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2)
As n grows larger, the series should converge to 6 but small amounts of error will cause it to approach 100.
Task 1
Display the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least 16 decimal places.
n = 3 18.5
n = 4 9.378378
n = 5 7.801153
n = 6 7.154414
n = 7 6.806785
n = 8 6.5926328
n = 20 6.0435521101892689
n = 30 6.006786093031205758530554
n = 50 6.0001758466271871889456140207471954695237
n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266
Task 2
The Chaotic Bank Society is offering a new investment account to their customers.
You first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.
After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed.
So ...
after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.
after 2 years your balance will be doubled and $1 removed.
after 3 years your balance will be tripled and $1 removed.
...
after 10 years, multiplied by 10 and $1 removed, and so on.
What will your balance be after 25 years?
Starting balance: $e-1
Balance = (Balance * year) - 1 for 25 years
Balance after 25 years: $0.0399387296732302
Task 3, extra credit
Siegfried Rump's example. Consider the following function, designed by Siegfried Rump in 1988.
f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b)
compute f(a,b) where a=77617.0 and b=33096.0
f(77617.0, 33096.0) = -0.827396059946821
Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.
See also;
Floating-Point Arithmetic Section 1.3.2 Difficult problems.
| #Perl | Perl | use bigrat;
@s = qw(2, -4);
for my $n (2..99) {
$s[$n]= 111.0 - 1130.0/$s[-1] + 3000.0/($s[-1]*$s[-2]);
}
for $n (3..8, 20, 30, 35, 50, 100) {
($nu,$de) = $s[$n-1] =~ m#^(\d+)/(\d+)#;;
printf "n = %3d %18.15f\n", $n, $nu/$de;
} |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #11l | 11l | [Float] a
[String = ((Float, Float) -> Float)] b
b[‘+’] = (x, y) -> y + x
b[‘-’] = (x, y) -> y - x
b[‘*’] = (x, y) -> y * x
b[‘/’] = (x, y) -> y / x
b[‘^’] = (x, y) -> y ^ x
L(c) ‘3 4 2 * 1 5 - 2 3 ^ ^ / +’.split(‘ ’)
I c C b
V first = a.pop()
V second = a.pop()
a.append(b[c](first, second))
E
a.append(Float(c))
print(c‘ ’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
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #ALGOL_68 | ALGOL 68 | BEGIN
# parses s and returns an RPN expression using Dijkstra's "Shunting Yard" algorithm #
# s is expected to contain a valid infix expression containing single-digit numbers and single-character operators #
PROC parse = ( STRING s )STRING:
BEGIN
# add to the output #
PROC output element = ( CHAR c )VOID:
BEGIN
output[ output pos +:= 1 ] := c;
output pos +:= 1
END # output element # ;
PROC stack op = ( CHAR c )VOID: stack[ stack pos +:= 1 ] := c;
# unstacks and returns the top operator on the stack - stops the program if the stack is empty #
PROC unstack = CHAR:
IF stack pos < 1 THEN
# empty stack #
print( ( "Stack underflow", newline ) );
stop
ELSE
# still something on the stack to unstack #
CHAR result = stack[ stack pos ];
stack[ stack pos ] := " ";
stack pos -:= 1;
result
FI # unstack # ;
# returns the priority of the operator o - which must be one of "(", "^", "*", "/", "+" or "-" #
PROC priority of = ( CHAR o )INT: IF o = "(" THEN -1 ELIF o = "^" THEN 4 ELIF o = "*" OR o = "/" THEN 3 ELSE 2 FI;
# returns TRUE if o is a right-associative operator, FALSE otherwise #
PROC right = ( CHAR c )BOOL: c = "^";
PROC lower or equal priority = ( CHAR c )BOOL:
IF stack pos < 1 THEN FALSE # empty stack #
ELSE priority of( c ) <= priority of( stack[ stack pos ] )
FI # lower or equal priority # ;
PROC lower priority = ( CHAR c )BOOL:
IF stack pos < 1 THEN FALSE # empty stack #
ELSE priority of( c ) < priority of( stack[ stack pos ] )
FI # lower priority # ;
# max stack size and output size #
INT max stack = 32;
# stack and output queue #
[ 1 : max stack ]CHAR stack;
[ 1 : max stack ]CHAR output;
FOR c pos TO max stack DO stack[ c pos ] := output[ c pos ] := " " OD;
# stack pointer and output queue pointer #
INT stack pos := 0;
INT output pos := 0;
print( ( "Parsing: ", s, newline ) );
print( ( "token output stack", newline ) );
FOR s pos FROM LWB s TO UPB s DO
CHAR c = s[ s pos ];
IF c /= " " THEN
IF c >= "0" AND c <= "9" THEN output element( c )
ELIF c = "(" THEN stack op( c )
ELIF c = ")" THEN
# close bracket - unstack to the matching "(" and unstack the "(" #
WHILE CHAR op char = unstack;
op char /= "("
DO
output element( op char )
OD
ELIF right( c ) THEN
# right associative operator #
WHILE lower priority( c ) DO output element( unstack ) OD;
stack op( c )
ELSE
# must be left associative #
WHILE lower or equal priority( c ) DO output element( unstack ) OD;
stack op( c )
FI;
print( ( c, " ", output, " ", stack, newline ) )
FI
OD;
WHILE stack pos >= 1 DO output element( unstack ) OD;
output[ 1 : output pos ]
END # parse # ;
print( ( "result: ", parse( "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" ), newline ) )
END |
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:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #AutoHotkey | AutoHotkey | n := 5
MsgBox, 262144, ,% ""
. "Pascal upper-triangular :`n" show(Pascal_Upper(n))
. "`n`nPascal lower-triangular :`n" show(Pascal_Lower(n))
. "`n`nPascal symmetric:`n" show(Pascal_Symm(n))
return
show(obj){
for i, o in obj{
line := ""
for j, v in o
line .= v ", "
res .= "[" Trim(line, ", ") "]`n,"
}
return "[" Trim(res, "`n,") "]"
}
Pascal_Upper(n){
obj := fillObj(n)
loop % n
obj[1, A_Index] := 1
loop % n-1
obj[A_Index+1, 1] := 0
for i, o in obj
for j, v in o
if !(i = 1 or j = 1)
obj[i, j] := obj[i, j-1] + obj[i-1, j-1]
return obj
}
Pascal_Lower(n){
obj := fillObj(n)
loop % n
obj[A_Index, 1] := 1
loop % n-1
obj[1, A_Index+1] := 0
for i, o in obj
for j, v in o
if !(i = 1 or j = 1)
obj[i, j] := obj[i-1, j] + obj[i-1, j-1]
return obj
}
Pascal_Symm(n){
obj := fillObj(n)
loop % n
obj[A_Index, 1] := 1
loop % n-1
obj[1, A_Index+1] := 1
for i, o in obj
for j, v in o
if !(i = 1 or j = 1)
obj[i, j] := obj[i-1, j] + obj[i, j-1]
return obj
}
fillObj(n){
obj := []
loop % n{
i := A_Index
loop % n
obj[i, A_Index] := 0
}
return obj
} |
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 elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #APL | APL |
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}
|
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 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #C | C |
#include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
//shift digit in
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor & 0x5f, //(collapses case, but mutilates digits)
(chNow >= ('0'&0x5f) && chNow <= ('9'&0x5f)) ||
(chNow >= 'A' && chNow <= 'F')
)
{
unsigned char nybbleValue;
chNow -= 0x10; //scootch digital values down; hex now offset by x31
nybbleValue = ( chNow > 9 ? chNow - (0x31-0x0a) : chNow );
//shift nybble in
nVal <<= 4;
nVal += nybbleValue;
++*pchCursor;
}
return nVal;
}
//Parse a textual IPv4 or IPv6 address, optionally with port, into a binary
//array (for the address, in network order), and an optionally provided port.
//Also, indicate which of those forms (4 or 6) was parsed. Return true on
//success. ppszText must be a nul-terminated ASCII string. It will be
//updated to point to the character which terminated parsing (so you can carry
//on with other things. abyAddr must be 16 bytes. You can provide NULL for
//abyAddr, nPort, bIsIPv6, if you are not interested in any of those
//informations. If we request port, but there is no port part, then nPort will
//be set to 0. There may be no whitespace leading or internal (though this may
//be used to terminate a successful parse.
//Note: the binary address and integer port are in network order.
int ParseIPv4OrIPv6 ( const char** ppszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
unsigned char* abyAddrLocal;
unsigned char abyDummyAddr[16];
//find first colon, dot, and open bracket
const char* pchColon = strchr ( *ppszText, ':' );
const char* pchDot = strchr ( *ppszText, '.' );
const char* pchOpenBracket = strchr ( *ppszText, '[' );
const char* pchCloseBracket = NULL;
//we'll consider this to (probably) be IPv6 if we find an open
//bracket, or an absence of dots, or if there is a colon, and it
//precedes any dots that may or may not be there
int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot ||
( NULL != pchColon && ( NULL == pchDot || pchColon < pchDot ) );
//OK, now do a little further sanity check our initial guess...
if ( bIsIPv6local )
{
//if open bracket, then must have close bracket that follows somewhere
pchCloseBracket = strchr ( *ppszText, ']' );
if ( NULL != pchOpenBracket && ( NULL == pchCloseBracket ||
pchCloseBracket < pchOpenBracket ) )
return 0;
}
else //probably ipv4
{
//dots must exist, and precede any colons
if ( NULL == pchDot || ( NULL != pchColon && pchColon < pchDot ) )
return 0;
}
//we figured out this much so far....
if ( NULL != pbIsIPv6 )
*pbIsIPv6 = bIsIPv6local;
//especially for IPv6 (where we will be decompressing and validating)
//we really need to have a working buffer even if the caller didn't
//care about the results.
abyAddrLocal = abyAddr; //prefer to use the caller's
if ( NULL == abyAddrLocal ) //but use a dummy if we must
abyAddrLocal = abyDummyAddr;
//OK, there should be no correctly formed strings which are miscategorized,
//and now any format errors will be found out as we continue parsing
//according to plan.
if ( ! bIsIPv6local ) //try to parse as IPv4
{
//4 dotted quad decimal; optional port if there is a colon
//since there are just 4, and because the last one can be terminated
//differently, I'm just going to unroll any potential loop.
unsigned char* pbyAddrCursor = abyAddrLocal;
unsigned int nVal;
const char* pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText ); //get first val
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText ) //must be in range and followed by dot and nonempty
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal; //stick it in addr
++(*ppszText); //past the dot
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText ); //get second val
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText); //past the dot
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText ); //get third val
if ( '.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText )
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
++(*ppszText); //past the dot
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText ); //get fourth val
if ( nVal > 255 || pszTextBefore == *ppszText ) //(we can terminate this one in several ways)
return 0;
*(pbyAddrCursor++) = (unsigned char) nVal;
if ( ':' == **ppszText && NULL != pnPort ) //have port part, and we want it
{
unsigned short usPortNetwork; //save value in network order
++(*ppszText); //past the colon
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else //finished just with ip address
{
if ( NULL != pnPort )
*pnPort = 0; //indicate we have no port part
return 1;
}
}
else //try to parse as IPv6
{
unsigned char* pbyAddrCursor;
unsigned char* pbyZerosLoc;
int bIPv4Detected;
int nIdx;
//up to 8 16-bit hex quantities, separated by colons, with at most one
//empty quantity, acting as a stretchy run of zeroes. optional port
//if there are brackets followed by colon and decimal port number.
//A further form allows an ipv4 dotted quad instead of the last two
//16-bit quantities, but only if in the ipv4 space ::ffff:x:x .
if ( NULL != pchOpenBracket ) //start past the open bracket, if it exists
*ppszText = pchOpenBracket + 1;
pbyAddrCursor = abyAddrLocal;
pbyZerosLoc = NULL; //if we find a 'zero compression' location
bIPv4Detected = 0;
for ( nIdx = 0; nIdx < 8; ++nIdx ) //we've got up to 8 of these, so we will use a loop
{
const char* pszTextBefore = *ppszText;
unsigned nVal =_parseHex ( ppszText ); //get value; these are hex
if ( pszTextBefore == *ppszText ) //if empty, we are zero compressing; note the loc
{
if ( NULL != pbyZerosLoc ) //there can be only one!
{
//unless it's a terminal empty field, then this is OK, it just means we're done with the host part
if ( pbyZerosLoc == pbyAddrCursor )
{
--nIdx;
break;
}
return 0; //otherwise, it's a format error
}
if ( ':' != **ppszText ) //empty field can only be via :
return 0;
if ( 0 == nIdx ) //leading zero compression requires an extra peek, and adjustment
{
++(*ppszText);
if ( ':' != **ppszText )
return 0;
}
pbyZerosLoc = pbyAddrCursor;
++(*ppszText);
}
else
{
if ( '.' == **ppszText ) //special case of ipv4 convenience notation
{
//who knows how to parse ipv4? we do!
const char* pszTextlocal = pszTextBefore; //back it up
unsigned char abyAddrlocal[16];
int bIsIPv6local;
int bParseResultlocal = ParseIPv4OrIPv6 ( &pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local );
*ppszText = pszTextlocal; //success or fail, remember the terminating char
if ( ! bParseResultlocal || bIsIPv6local ) //must parse and must be ipv4
return 0;
//transfer addrlocal into the present location
*(pbyAddrCursor++) = abyAddrlocal[0];
*(pbyAddrCursor++) = abyAddrlocal[1];
*(pbyAddrCursor++) = abyAddrlocal[2];
*(pbyAddrCursor++) = abyAddrlocal[3];
++nIdx; //pretend like we took another short, since the ipv4 effectively is two shorts
bIPv4Detected = 1; //remember how we got here for further validation later
break; //totally done with address
}
if ( nVal > 65535 ) //must be 16 bit quantity
return 0;
*(pbyAddrCursor++) = nVal >> 8; //transfer in network order
*(pbyAddrCursor++) = nVal & 0xff;
if ( ':' == **ppszText ) //typical case inside; carry on
{
++(*ppszText);
}
else //some other terminating character; done with this parsing parts
{
break;
}
}
}
//handle any zero compression we found
if ( NULL != pbyZerosLoc )
{
int nHead = (int)( pbyZerosLoc - abyAddrLocal ); //how much before zero compression
int nTail = nIdx * 2 - (int)( pbyZerosLoc - abyAddrLocal ); //how much after zero compression
int nZeros = 16 - nTail - nHead; //how much zeros
memmove ( &abyAddrLocal[16-nTail], pbyZerosLoc, nTail ); //scootch stuff down
memset ( pbyZerosLoc, 0, nZeros ); //clear the compressed zeros
}
//validation of ipv4 subspace ::ffff:x.x
if ( bIPv4Detected )
{
static const unsigned char abyPfx[] = { 0,0, 0,0, 0,0, 0,0, 0,0, 0xff,0xff };
if ( 0 != memcmp ( abyAddrLocal, abyPfx, sizeof(abyPfx) ) )
return 0;
}
//close bracket
if ( NULL != pchOpenBracket )
{
if ( ']' != **ppszText )
return 0;
++(*ppszText);
}
if ( ':' == **ppszText && NULL != pnPort ) //have port part, and we want it
{
const char* pszTextBefore;
unsigned int nVal;
unsigned short usPortNetwork; //save value in network order
++(*ppszText); //past the colon
pszTextBefore = *ppszText;
pszTextBefore = *ppszText;
nVal =_parseDecimal ( ppszText );
if ( nVal > 65535 || pszTextBefore == *ppszText )
return 0;
((unsigned char*)&usPortNetwork)[0] = ( nVal & 0xff00 ) >> 8;
((unsigned char*)&usPortNetwork)[1] = ( nVal & 0xff );
*pnPort = usPortNetwork;
return 1;
}
else //finished just with ip address
{
if ( NULL != pnPort )
*pnPort = 0; //indicate we have no port part
return 1;
}
}
}
//simple version if we want don't care about knowing how much we ate
int ParseIPv4OrIPv6_2 ( const char* pszText,
unsigned char* abyAddr, int* pnPort, int* pbIsIPv6 )
{
const char* pszTextLocal = pszText;
return ParseIPv4OrIPv6 ( &pszTextLocal, abyAddr, pnPort, pbIsIPv6);
}
|
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#define decl_tree_type(T) \
typedef struct node_##T##_t node_##T##_t, *node_##T; \
struct node_##T##_t { node_##T left, right; T value; }; \
\
node_##T node_##T##_new(T v) { \
node_##T node = malloc(sizeof(node_##T##_t)); \
node->value = v; \
node->left = node->right = 0; \
return node; \
} \
node_##T node_##T##_insert(node_##T root, T v) { \
node_##T n = node_##T##_new(v); \
while (root) { \
if (root->value < n->value) \
if (!root->left) return root->left = n; \
else root = root->left; \
else \
if (!root->right) return root->right = n; \
else root = root->right; \
} \
return 0; \
}
#define tree_node(T) node_##T
#define node_insert(T, r, x) node_##T##_insert(r, x)
#define node_new(T, x) node_##T##_new(x)
decl_tree_type(double);
decl_tree_type(int);
int main()
{
int i;
tree_node(double) root_d = node_new(double, (double)rand() / RAND_MAX);
for (i = 0; i < 10000; i++)
node_insert(double, root_d, (double)rand() / RAND_MAX);
tree_node(int) root_i = node_new(int, rand());
for (i = 0; i < 10000; i++)
node_insert(int, root_i, rand());
return 0;
} |
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #C.23 | C# | using System;
class BinaryTree<T>
{
public T value;
public BinaryTree<T> left;
public BinaryTree<T> right;
public BinaryTree(T value)
{
this.value = value;
}
public BinaryTree<U> Map<U>(Func<T, U> f)
{
BinaryTree<U> tree = new BinaryTree<U>(f(this.value));
if (this.left != null)
{
tree.left = this.left.Map(f);
}
if (this.right != null)
{
tree.right = this.right.Map(f);
}
return tree;
}
} |
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.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #AutoHotkey | AutoHotkey | expr := "3 4 2 * 1 5 - 2 3 ^ ^ / +"
stack := {push: func("ObjInsert"), pop: func("ObjRemove")}
out := "TOKEN`tACTION STACK (comma separated)`r`n"
Loop Parse, expr, %A_Space%
{
token := A_LoopField
if token is number
stack.push([0, token])
if isOp(token)
{
b := stack.pop(), a := stack.pop(), p := b.1 > a.1 ? b.1 : a.1
p := Precedence(token) > p ? precedence(token) : p
if (a.1 < b.1) and isRight(token)
stack.push([p, "( " . a.2 " ) " token " " b.2])
else if (a.1 > b.1) and isLeft(token)
stack.push([p, a.2 token " ( " b.2 " ) "])
else
stack.push([p, a.2 . " " . token . " " . b.2])
}
out .= token "`t" (isOp(token) ? "Push Partial expression "
: "Push num" space(16)) disp(stack) "`r`n"
}
out .= "`r`n The final output infix expression is: '" disp(stack) "'"
clipboard := out
isOp(t){
return (!!InStr("+-*/^", t) && t)
}
IsLeft(o){
return !!InStr("*/+-", o)
}
IsRight(o){
return o = "^"
}
Precedence(o){
return (InStr("+-/*^", o)+3)//2
}
Disp(obj){
for each, val in obj
if val[2]
o .= ", " val[2]
return SubStr(o,3)
}
Space(n){
return n>0 ? A_Space Space(n-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
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #C.2B.2B | C++ | #include <utility> // For declval.
#include <algorithm>
#include <array>
#include <iterator>
#include <iostream>
/* Partial application helper. */
template< class F, class Arg >
struct PApply
{
F f;
Arg arg;
template< class F_, class Arg_ >
PApply( F_&& f, Arg_&& arg )
: f(std::forward<F_>(f)), arg(std::forward<Arg_>(arg))
{
}
/*
* The return type of F only gets deduced based on the number of arguments
* supplied. PApply otherwise has no idea whether f takes 1 or 10 args.
*/
template< class ... Args >
auto operator() ( Args&& ...args )
-> decltype( f(arg,std::declval<Args>()...) )
{
return f( arg, std::forward<Args>(args)... );
}
};
template< class F, class Arg >
PApply<F,Arg> papply( F&& f, Arg&& arg )
{
return PApply<F,Arg>( std::forward<F>(f), std::forward<Arg>(arg) );
}
/* Apply f to cont. */
template< class F >
std::array<int,4> fs( F&& f, std::array<int,4> cont )
{
std::transform( std::begin(cont), std::end(cont), std::begin(cont),
std::forward<F>(f) );
return cont;
}
std::ostream& operator << ( std::ostream& out, const std::array<int,4>& c )
{
std::copy( std::begin(c), std::end(c),
std::ostream_iterator<int>(out, ", ") );
return out;
}
int f1( int x ) { return x * 2; }
int f2( int x ) { return x * x; }
int main()
{
std::array<int,4> xs = {{ 0, 1, 2, 3 }};
std::array<int,4> ys = {{ 2, 4, 6, 8 }};
auto fsf1 = papply( fs<decltype(f1)>, f1 );
auto fsf2 = papply( fs<decltype(f2)>, f2 );
std::cout << "xs:\n"
<< "\tfsf1: " << fsf1(xs) << '\n'
<< "\tfsf2: " << fsf2(xs) << "\n\n"
<< "ys:\n"
<< "\tfsf1: " << fsf1(ys) << '\n'
<< "\tfsf2: " << fsf2(ys) << '\n';
} |
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.
• partition 18 with 2 primes.
• partition 19 with 3 primes.
• partition 20 with 4 primes.
• partition 2017 with 24 primes.
• partition 22699 with 1, 2, 3, and 4 primes.
• partition 40355 with 3 primes.
The output could/should be shown in a format such as:
Partitioned 19 with 3 primes: 3+5+11
Use any spacing that may be appropriate for the display.
You need not validate the input(s).
Use the lowest primes possible; use 18 = 5+13, not 18 = 7+11.
You only need to show one solution.
This task is similar to factoring an integer.
Related tasks
Count in factors
Prime decomposition
Factors of an integer
Sieve of Eratosthenes
Primality by trial division
Factors of a Mersenne number
Factors of a Mersenne number
Sequence of primes by trial division
| #Java | Java | import java.util.Arrays;
import java.util.stream.IntStream;
public class PartitionInteger {
private static final int[] primes = IntStream.concat(IntStream.of(2), IntStream.iterate(3, n -> n + 2))
.filter(PartitionInteger::isPrime)
.limit(50_000)
.toArray();
private static boolean 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 false;
d += 4;
}
return true;
}
private static boolean findCombo(int k, int x, int m, int n, int[] combo) {
boolean foundCombo = false;
if (k >= m) {
if (Arrays.stream(combo).map(i -> primes[i]).sum() == x) {
String s = m > 1 ? "s" : "";
System.out.printf("Partitioned %5d with %2d prime%s: ", x, m, s);
for (int i = 0; i < m; ++i) {
System.out.print(primes[combo[i]]);
if (i < m - 1) System.out.print('+');
else System.out.println();
}
foundCombo = true;
}
} else {
for (int j = 0; j < n; ++j) {
if (k == 0 || j > combo[k - 1]) {
combo[k] = j;
if (!foundCombo) {
foundCombo = findCombo(k + 1, x, m, n, combo);
}
}
}
}
return foundCombo;
}
private static void partition(int x, int m) {
if (x < 2 || m < 1 || m >= x) {
throw new IllegalArgumentException();
}
int[] filteredPrimes = Arrays.stream(primes).filter(it -> it <= x).toArray();
int n = filteredPrimes.length;
if (n < m) throw new IllegalArgumentException("Not enough primes");
int[] combo = new int[m];
boolean foundCombo = findCombo(0, x, m, n, combo);
if (!foundCombo) {
String s = m > 1 ? "s" : " ";
System.out.printf("Partitioned %5d with %2d prime%s: (not possible)\n", x, m, s);
}
}
public static void main(String[] args) {
partition(99809, 1);
partition(18, 2);
partition(19, 3);
partition(20, 4);
partition(2017, 24);
partition(22699, 1);
partition(22699, 2);
partition(22699, 3);
partition(22699, 4);
partition(40355, 3);
}
} |
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Recursive | Recursive | def partDiffDiff($n):
if ($n % 2) == 1 then ($n+1) / 2 else $n+1 end;
# in: {n, partDiffMemo}
# out: object with possibly updated memoization
def partDiff:
.n as $n
| if .partDiffMemo[$n] then .
elif $n<2 then .partDiffMemo[$n]=1
else ((.n=($n-1)) | partDiff)
| .partDiffMemo[$n] = .partDiffMemo[$n-1] + partDiffDiff($n-1)
end;
# in: {n, memo, partDiffMemo}
# where `.memo[i]` memoizes partitions(i)
# and `.partDiffMemo[i]` memoizes partDiff(i)
# out: object with possibly updated memoization
def partitionsM:
.n as $n
| if .memo[$n] then .
elif $n<2 then .memo[$n] = 1
else label $out
| foreach range(1; $n+2) as $i (.emit = false | .psum = 0;
if $i > $n then .emit = true
else ((.n = $i) | partDiff)
| .partDiffMemo[$i] as $pd
| if $pd > $n then .emit=true, break $out
else {psum, emit} as $local # for restoring relevant state
| ((.n = ($n-$pd)) | partitionsM)
| .memo[$n-$pd] as $increment
| . + $local # restore
| if (($i-1)%4)<2
then .psum += $increment
else .psum -= $increment
end
end
end;
select(.emit) )
| .memo[$n] = .psum
end ;
def partitionsP:
. as $n
| {n: $n, memo:[], partDiffMemo:[]}
| partitionsM
| .memo[$n];
# Stretch goal:
6666 | partitionsP
|
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Julia | Julia | using Memoize
function partDiffDiff(n::Int)::Int
isodd(n) ? (n+1)÷2 : n+1
end
@memoize function partDiff(n::Int)::Int
n<2 ? 1 : partDiff(n-1)+partDiffDiff(n-1)
end
@memoize function partitionsP(n::Int)
T=BigInt
if n<2
one(T)
else
psum = zero(T)
for i ∈ 1:n
pd = partDiff(i)
if pd>n
break
end
if ((i-1)%4)<2
psum += partitionsP(n-pd)
else
psum -= partitionsP(n-pd)
end
end
psum
end
end
n=6666
@time println("p($n) = ", partitionsP(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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Maple | Maple | p:=proc(n)
option remember;
local k,s:=0,m;
for k from 1 while (m:=iquo(k*(3*k-1),2))<=n do
s-=(-1)^k*p(n-m);
od;
for k from 1 while (m:=iquo(k*(3*k+1),2))<=n do
s-=(-1)^k*p(n-m);
od;
s
end:
p(0):=1:
time(p(6666));
# 0.796
time(combinat[numbpart](6666));
# 0.406
p~([$1..20]);
# [1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135, 176, 231, 297, 385, 490, 627]
combinat[numbpart]~([$1..20]);
# [1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135, 176, 231, 297, 385, 490, 627]
p(1000)
# 24061467864032622473692149727991
combinat[numbpart](1000);
# 24061467864032622473692149727991 |
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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #Julia | Julia | function pascal(a::Integer, b::Integer, mid::Integer, top::Integer)
yd = round((top - 4 * (a + b)) / 7)
!isinteger(yd) && return 0, 0, 0
y = Int(yd)
x = mid - 2a - y
return x, y, y - x
end
x, y, z = pascal(11, 4, 40, 151)
if !iszero(x)
println("Solution: x = $x, y = $y, z = $z.")
else
println("There is no solution.")
end |
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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #Kotlin | Kotlin | // version 1.1.3
data class Solution(val x: Int, val y: Int, val z: Int)
fun Double.isIntegral(tolerance: Double = 0.0) =
(this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance
fun pascal(a: Int, b: Int, mid: Int, top: Int): Solution {
val yd = (top - 4 * (a + b)) / 7.0
if (!yd.isIntegral(0.0001)) return Solution(0, 0, 0)
val y = yd.toInt()
val x = mid - 2 * a - y
return Solution(x, y, y - x)
}
fun main(args: Array<String>) {
val (x, y, z) = pascal(11, 4, 40, 151)
if (x != 0)
println("Solution is: x = $x, y = $y, z = $z")
else
println("There is no solutuon")
} |
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 on an n-by-n square grid, (the board), so that no queen attacks another of a different colour.
Task
Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).
Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
Display here results for the m=4, n=5 case.
References
Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
A250000 OEIS
| #Raku | Raku | # recursively place the next queen
sub place ($board, $n, $m, $empty-square) {
my $cnt;
state (%seen,$attack);
state $solution = False;
# logic of regex: queen ( ... paths between queens containing only empty squares ... ) queen of other color
once {
my %Q = 'WBBW'.comb; # return the queen of alternate color
my $re =
'(<[WB]>)' ~ # 1st queen
'[' ~
join(' |',
qq/<[$empty-square]>*/,
map {
qq/ . ** {$_}[<[$empty-square]> . ** {$_}]*/
}, $n-1, $n, $n+1
) ~
']' ~
'<{%Q{$0}}>'; # 2nd queen
$attack = "rx/$re/".EVAL;
}
# return first result found (omit this line to get last result found)
return $solution if $solution;
# bail out if seen this configuration previously, or attack detected
return if %seen{$board}++ or $board ~~ $attack;
# success if queen count is m×2, set state variable and return from recursion
$solution = $board and return if $m * 2 == my $queens = $board.comb.Bag{<W B>}.sum;
# place the next queen (alternating colors each time)
place( $board.subst( /<[◦•]>/, {<W B>[$queens % 2]}, :nth($cnt) ), $n, $m, $empty-square )
while $board ~~ m:nth(++$cnt)/<[◦•]>/;
return $solution
}
my ($m, $n) = @*ARGS == 2 ?? @*ARGS !! (4, 5);
my $empty-square = '◦•';
my $board = ($empty-square x $n**2).comb.rotor($n)>>.join[^$n].join: "\n";
my $solution = place $board, $n, $m, $empty-square;
say $solution
?? "Solution to $m $n\n\n{S:g/(\N)/$0 / with $solution}"
!! "No solution to $m $n"; |
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 character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Go | Go |
package main
import (
"crypto/rand"
"math/big"
"strings"
"flag"
"math"
"fmt"
)
var lowercase = "abcdefghijklmnopqrstuvwxyz"
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var numbers = "0123456789"
var signs = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"
var similar = "Il1O05S2Z"
func check(e error){
if e != nil {
panic(e)
}
}
func randstr(length int, alphastr string) string{
alphabet := []byte(alphastr)
pass := make([]byte,length)
for i := 0; i < length; i++ {
bign, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet))))
check(err)
n := bign.Int64()
pass[i] = alphabet[n]
}
return string(pass)
}
func verify(pass string,checkUpper bool,checkLower bool, checkNumber bool, checkSign bool) bool{
isValid := true
if(checkUpper){
isValid = isValid && strings.ContainsAny(pass,uppercase)
}
if(checkLower){
isValid = isValid && strings.ContainsAny(pass,lowercase)
}
if(checkNumber){
isValid = isValid && strings.ContainsAny(pass,numbers)
}
if(checkSign){
isValid = isValid && strings.ContainsAny(pass,signs)
}
return isValid
}
func main() {
passCount := flag.Int("pc", 6, "Number of passwords")
passLength := flag.Int("pl", 10, "Passwordlength")
useUpper := flag.Bool("upper", true, "Enables or disables uppercase letters")
useLower := flag.Bool("lower", true, "Enables or disables lowercase letters")
useSign := flag.Bool("sign", true, "Enables or disables signs")
useNumbers := flag.Bool("number", true, "Enables or disables numbers")
useSimilar := flag.Bool("similar", true,"Enables or disables visually similar characters")
flag.Parse()
passAlphabet := ""
if *useUpper {
passAlphabet += uppercase
}
if *useLower {
passAlphabet += lowercase
}
if *useSign {
passAlphabet += signs
}
if *useNumbers {
passAlphabet += numbers
}
if !*useSimilar {
for _, r := range similar{
passAlphabet = strings.Replace(passAlphabet,string(r),"", 1)
}
}
fmt.Printf("Generating passwords with an average entropy of %.1f bits \n", math.Log2(float64(len(passAlphabet))) * float64(*passLength))
for i := 0; i < *passCount;i++{
passFound := false
pass := ""
for(!passFound){
pass = randstr(*passLength,passAlphabet)
passFound = verify(pass,*useUpper,*useLower,*useNumbers,*useSign)
}
fmt.Println(pass)
}
}
|
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Shen | Shen |
(define permute
[] -> []
[X] -> [[X]]
X -> (permute-helper [] X))
(define permute-helper
_ [] -> []
Done [X|Rest] -> (append (prepend-all X (permute (append Done Rest))) (permute-helper [X|Done] Rest))
)
(define prepend-all
_ [] -> []
X [Next|Rest] -> [[X|Next]|(prepend-all X Rest)]
)
(set *maximum-print-sequence-size* 50)
(permute [a b c d])
|
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 player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins.
Example
One player might choose the sequence HHT and the other THT.
Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence.
Task
Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent.
Who chooses and shows their sequence of three should be chosen randomly.
If going first, the computer should randomly choose its sequence of three.
If going second, the computer should automatically play the optimum sequence.
Successive coin tosses should be shown.
Show output of a game where the computer chooses first and a game where the user goes first here on this page.
See also
The Penney Ante Part 1 (Video).
The Penney Ante Part 2 (Video).
| #R | R | #===============================================================
# Penney's Game Task from Rosetta Code Wiki
# R implementation
#===============================================================
penneysgame <- function() {
#---------------------------------------------------------------
# Who goes first?
#---------------------------------------------------------------
first <- sample(c("PC", "Human"), 1)
#---------------------------------------------------------------
# Determine the sequences
#---------------------------------------------------------------
if (first == "PC") { # PC goes first
pc.seq <- sample(c("H", "T"), 3, replace = TRUE)
cat(paste("\nI choose first and will win on first seeing", paste(pc.seq, collapse = ""), "in the list of tosses.\n\n"))
human.seq <- readline("What sequence of three Heads/Tails will you win with: ")
human.seq <- unlist(strsplit(human.seq, ""))
} else if (first == "Human") { # Player goest first
cat(paste("\nYou can choose your winning sequence first.\n\n"))
human.seq <- readline("What sequence of three Heads/Tails will you win with: ")
human.seq <- unlist(strsplit(human.seq, "")) # Split the string into characters
pc.seq <- c(human.seq[2], human.seq[1:2]) # Append second element at the start
pc.seq[1] <- ifelse(pc.seq[1] == "H", "T", "H") # Switch first element to get the optimal guess
cat(paste("\nI win on first seeing", paste(pc.seq, collapse = ""), "in the list of tosses.\n"))
}
#---------------------------------------------------------------
# Start throwing the coin
#---------------------------------------------------------------
cat("\nThrowing:\n")
ran.seq <- NULL
while(TRUE) {
ran.seq <- c(ran.seq, sample(c("H", "T"), 1)) # Add a new coin throw to the vector of throws
cat("\n", paste(ran.seq, sep = "", collapse = "")) # Print the sequence thrown so far
if (length(ran.seq) >= 3 && all(tail(ran.seq, 3) == pc.seq)) {
cat("\n\nI win!\n")
break
}
if (length(ran.seq) >= 3 && all(tail(ran.seq, 3) == human.seq)) {
cat("\n\nYou win!\n")
break
}
Sys.sleep(0.5) # Pause for 0.5 seconds
}
}
|
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 problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.
This task's purpose is to show how your language deals with such classes of problems.
A sequence that seems to converge to a wrong limit.
Consider the sequence:
v1 = 2
v2 = -4
vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2)
As n grows larger, the series should converge to 6 but small amounts of error will cause it to approach 100.
Task 1
Display the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least 16 decimal places.
n = 3 18.5
n = 4 9.378378
n = 5 7.801153
n = 6 7.154414
n = 7 6.806785
n = 8 6.5926328
n = 20 6.0435521101892689
n = 30 6.006786093031205758530554
n = 50 6.0001758466271871889456140207471954695237
n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266
Task 2
The Chaotic Bank Society is offering a new investment account to their customers.
You first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.
After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed.
So ...
after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.
after 2 years your balance will be doubled and $1 removed.
after 3 years your balance will be tripled and $1 removed.
...
after 10 years, multiplied by 10 and $1 removed, and so on.
What will your balance be after 25 years?
Starting balance: $e-1
Balance = (Balance * year) - 1 for 25 years
Balance after 25 years: $0.0399387296732302
Task 3, extra credit
Siegfried Rump's example. Consider the following function, designed by Siegfried Rump in 1988.
f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b)
compute f(a,b) where a=77617.0 and b=33096.0
f(77617.0, 33096.0) = -0.827396059946821
Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.
See also;
Floating-Point Arithmetic Section 1.3.2 Difficult problems.
| #Phix | Phix | include builtins\bigatom.e
puts(1,"Task 1\n")
constant {fns,fmts} = columnize({{3,1},{4,6},{5,6},{6,6},{7,6},{8,7},{20,16},{30,24},{50,40},{100,78}})
{} = ba_scale(196)
sequence v = {2,-4}
for n=3 to 100 do
-- v = append(v,111 - 1130/v[n-1] + 3000/(v[n-1]*v[n-2]))
v = append(v,ba_add(ba_sub(111,ba_divide(1130,v[n-1])),ba_divide(3000,ba_multiply(v[n-1],v[n-2]))))
if n<9 or find(n,{20,30,50,100}) then
-- printf(1,"n = %-3d %20.16f\n", {n, v[n]})
string fmt = sprintf("%%.%dB",fmts[find(n,fns)])
printf(1,"n = %-3d %s\n", {n, ba_sprintf(fmt,v[n])})
end if
end for
puts(1,"\nTask 2\n")
--atom balance = exp(1)-1
--for i=1 to 25 do balance = balance*i-1 end for
--printf(1,"\nTask 2\nBalance after 25 years: $%12.10f", balance)
{} = ba_scale(41)
bigatom balance = ba_sub(ba_euler(42,true),1)
for i=1 to 25 do balance = ba_sub(ba_multiply(balance,i),1) end for
ba_printf(1,"Balance after 25 years: $%.16B\n\n", balance)
puts(1,"Task 3\n")
{} = ba_scale(15) -- fine!
integer a = 77617,
b = 33096
--atom pa2 = power(a,2),
-- pb2a211 = 11*pa2*power(b,2),
-- pb4121 = 121*power(b,4),
-- pb6 = power(b,6),
-- pb855 = 5.5*power(b,8),
-- f_ab = 333.75 * pb6 + pa2 * (pb2a211 - pb6 - pb4121 - 2) + pb855 + a/(2*b)
--printf(1,"f(%d, %d) = %.15f\n\n", {a, b, f_ab})
bigatom pa2 = ba_power(a,2),
pb2a211 = ba_multiply(11,ba_multiply(pa2,ba_power(b,2))),
pb4121 = ba_multiply(121,ba_power(b,4)),
pb6 = ba_power(b,6),
pa2mid = ba_multiply(pa2,ba_sub(ba_sub(ba_sub(pb2a211,pb6),pb4121),2)),
pb633375 = ba_multiply(333.75,pb6),
pb855 = ba_multiply(5.5,ba_power(b,8)),
f_ab = ba_add(ba_add(ba_add(pb633375,pa2mid),pb855),ba_divide(a,ba_multiply(2,b)))
printf(1,"f(%d, %d) = %s\n", {a, b, ba_sprintf("%.15B",f_ab)})
|
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #360_Assembly | 360 Assembly | * RPN calculator RC 25/01/2019
REVPOL CSECT
USING REVPOL,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
XPRNT TEXT,L'TEXT print expression !?
L R4,0 js=0 offset in stack
LA R5,0 ns=0 number of stack items
LA R6,0 jt=0 offset in text
LA R7,TEXT r7=@text
MVC CC,0(R7) cc first char of token
DO WHILE=(CLI,CC,NE,X'00') do while cc<>'0'x
MVC CTOK,=CL5' ' ctok=''
MVC CTOK(1),CC ctok=cc
CLI CC,C' ' if cc=' '
BE ITERATE then goto iterate
IF CLI,CC,GE,C'0',AND,CLI,CC,LE,C'9' THEN
MVC DEED,=C'Load' deed='Load'
XDECI R2,0(R7) r2=cint(text); r1=@text
ST R2,STACK(R4) stack(js)=cc
SR R1,R7 lt length of token
BCTR R1,0 lt-1
EX R1,MVCV MVC CTOK("R1"),0(R7)
AR R6,R1 jt+=lt-1
AR R7,R1 @text+=lt-1
LA R4,4(R4) js+=4
LA R5,1(R5) ns++
ELSE , else
MVC DEED,=C'Exec' deed='Exec'
LA R9,STACK-8(R4) @stack(j-1)
IF CLI,CC,EQ,C'+' THEN if cc='+' then
L R1,STACK-8(R4) stack(j-1)
A R1,STACK-4(R4) stack(j-1)+stack(j)
ST R1,0(R9) stack(j-1)=stack(j-1)+stack(j)
ENDIF , endif
IF CLI,CC,EQ,C'-' THEN if cc='-' then
L R1,STACK-8(R4) stack(j-1)
S R1,STACK-4(R4) stack(j-1)-stack(j)
ST R1,0(R9) stack(j-1)=stack(j-1)-stack(j)
ENDIF , endif
IF CLI,CC,EQ,C'*' THEN if cc='*' then
L R3,STACK-8(R4) stack(j-1)
M R2,STACK-4(R4) stack(j-1)*stack(j)
ST R3,0(R9) stack(j-1)=stack(j-1)*stack(j)
ENDIF , endif
IF CLI,CC,EQ,C'/' THEN if cc='/' then
L R2,STACK-8(R4) stack(j-1)
SRDA R2,32 for sign propagation
D R2,STACK-4(R4) stack(j-1)/stack(j)
ST R3,0(R9) stack(j-1)=stack(j-1)/stack(j)
ENDIF , endif
IF CLI,CC,EQ,C'^' THEN if cc='^' then
LA R3,1 r3=1
L R0,STACK-4(R4) r0=stack(j) [loop count]
EXPONENT M R2,STACK-8(R4) r3=r3*stack(j-1)
BCT R0,EXPONENT if r0--<>0 then goto exponent
ST R3,0(R9) stack(j-1)=stack(j-1)^stack(j)
ENDIF , endif
S R4,=F'4' js-=4
BCTR R5,0 ns--
ENDIF , endif
MVC PG,=CL80' ' clean buffer
MVC PG(4),DEED output deed
MVC PG+5(5),CTOK output cc
MVC PG+11(6),=C'Stack:' output
LA R2,1 i=1
LA R3,STACK @stack
LA R9,PG+18 @buffer
DO WHILE=(CR,R2,LE,R5) do i=1 to ns
L R1,0(R3) stack(i)
XDECO R1,XDEC edit stack(i)
MVC 0(5,R9),XDEC+7 output stack(i)
LA R2,1(R2) i=i+1
LA R3,4(R3) @stack+=4
LA R9,6(R9) @buffer+=6
ENDDO , enddo
XPRNT PG,L'PG print
ITERATE LA R6,1(R6) jt++
LA R7,1(R7) @text++
MVC CC,0(R7) cc next char
ENDDO , enddo
L R1,STACK stack(1)
XDECO R1,XDEC edit stack(1)
MVC XDEC(4),=C'Val=' output
XPRNT XDEC,L'XDEC print stack(1)
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
MVCV MVC CTOK(0),0(R7) patern mvc
TEXT DC C'3 4 2 * 1 5 - 2 3 ^ ^ / +',X'00'
STACK DS 16F stack(16)
DEED DS CL4
CC DS C
CTOK DS CL5
PG DS CL80
XDEC DS CL12
YREGS
END REVPOL |
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
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #AutoHotkey | AutoHotkey | SetBatchLines -1
#NoEnv
expr := "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
output := "Testing string '" expr "'`r`n`r`nToken`tOutput Queue"
. Space(StrLen(expr)-StrLen("Output Queue")+2) "OP Stack"
; define a stack with semantic .push() and .pop() funcs
stack := {push: func("ObjInsert"), pop: func("ObjRemove"), peek: func("Peek")}
Loop Parse, expr, %A_Space%
{
token := A_LoopField
if token is number
Q .= token A_Space
if isOp(token){
o1 := token
while isOp(o2 := stack.peek())
and ((isLeft(o1) and Precedence(o1) <= Precedence(o2))
or (isRight(o1) and Precedence(o1) < Precedence(o2)))
Q .= stack.pop() A_Space
stack.push(o1)
}
If ( token = "(" )
stack.push(token)
If ( token = ")" )
{
While ((t := stack.pop()) != "(") && (t != "")
Q .= t A_Space
if (t = "")
throw Exception("Unmatched parenthesis. "
. "Character number " A_Index)
}
output .= "`r`n" token Space(7) Q Space(StrLen(expr)+2-StrLen(Q))
. Disp(stack)
}
output .= "`r`n(empty stack to output)"
While (t := stack.pop()) != ""
if InStr("()", t)
throw Exception("Unmatched parenthesis.")
else Q .= t A_Space, output .= "`r`n" Space(8) Q
. Space(StrLen(expr)+2-StrLen(Q)) Disp(stack)
output .= "`r`n`r`nFinal string: '" Q "'"
clipboard := output
isOp(t){
return (!!InStr("+-*/^", t) && t)
}
Peek(this){
r := this.Remove(), this.Insert(r)
return r
}
IsLeft(o){
return !!InStr("*/+-", o)
}
IsRight(o){
return o = "^"
}
Precedence(o){
return (InStr("+-/*^", o)+3)//2
}
Disp(obj){
for each, val in obj
o := val . o
return o
}
Space(n){
return n>0 ? A_Space Space(n-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:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #BASIC | BASIC | 10 DEFINT A-Z: S=5: DIM M(S,S)
20 PRINT "Lower-triangular matrix:": GOSUB 200: GOSUB 100
30 PRINT "Upper-triangular matrix:": GOSUB 300: GOSUB 100
40 PRINT "Symmetric matrix:": GOSUB 400: GOSUB 100
50 END
100 REM *** Print the matrix M ***
110 FOR Y=1 TO S
120 FOR X=1 TO S
130 PRINT USING " ##";M(X,Y);
140 NEXT X
150 PRINT
160 NEXT Y
170 PRINT
180 RETURN
200 REM *** Generate the lower-triangular matrix ***
210 FOR X=1 TO S: FOR Y=1 TO S
220 ON -(X>Y)-2*(X=Y OR X=1) GOTO 240,250
230 M(X,Y)=M(X-1,Y-1)+M(X,Y-1): GOTO 260
240 M(X,Y)=0: GOTO 260
250 M(X,Y)=1: GOTO 260
260 NEXT Y,X
270 RETURN
300 REM *** Generate the upper-triangular matrix ***
310 FOR X=1 TO S: FOR Y=1 TO S
320 ON -(X<Y)-2*(X=Y OR Y=1) GOTO 340,350
330 M(X,Y)=M(X-1,Y-1)+M(X-1,Y): GOTO 360
340 M(X,Y)=0: GOTO 360
350 M(X,Y)=1: GOTO 360
360 NEXT Y,X
370 RETURN
400 REM *** Generate the symmetric matrix ***
410 FOR X=1 TO S: FOR Y=1 TO S
420 IF X=1 OR Y=1 THEN M(X,Y)=1 ELSE M(X,Y)=M(X-1,Y)+M(X,Y-1)
430 NEXT Y,X
440 RETURN |
http://rosettacode.org/wiki/Parameterized_SQL_statement | Parameterized SQL statement | SQL injection
Using a SQL update statement like this one (spacing is optional):
UPDATE players
SET name = 'Smith, Steve', score = 42, active = TRUE
WHERE jerseyNum = 99
Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either. | #8th | 8th | \ assuming the var 'db' contains an opened database with a schema matching the problem:
db @
"UPDATE players SET name=?1,score=?2,active=?3 WHERE jerseyNum=?4"
db:prepare var, stmt
\ bind values to the statement:
stmt @ 1 "Smith, Steve" db:bind
2 42 db:bind
3 true db:bind
4 99 db:bind
\ execute the query
db @ swap db:exec |
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 elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #AppleScript | AppleScript | -------------------- PASCAL'S TRIANGLE -------------------
-- pascal :: Generator [[Int]]
on pascal()
script nextRow
on |λ|(row)
zipWith(my plus, {0} & row, row & {0})
end |λ|
end script
iterate(nextRow, {1})
end pascal
--------------------------- TEST -------------------------
on run
showPascal(take(7, pascal()))
end run
------------------------ FORMATTING ----------------------
-- showPascal :: [[Int]] -> String
on showPascal(xs)
set w to length of intercalate(" ", item -1 of xs)
script align
on |λ|(x)
|center|(w, space, intercalate(" ", x))
end |λ|
end script
unlines(map(align, xs))
end showPascal
------------------------- GENERIC ------------------------
-- center :: Int -> Char -> String -> String
on |center|(n, cFiller, strText)
set lngFill to n - (length of strText)
if lngFill > 0 then
set strPad to replicate(lngFill div 2, cFiller) as text
set strCenter to strPad & strText & strPad
if lngFill mod 2 > 0 then
cFiller & strCenter
else
strCenter
end if
else
strText
end if
end |center|
-- intercalate :: String -> [String] -> String
on intercalate(sep, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, sep}
set s to xs as text
set my text item delimiters to dlm
return s
end intercalate
-- iterate :: (a -> a) -> a -> Generator [a]
on iterate(f, x)
script
property v : missing value
property g : mReturn(f)'s |λ|
on |λ|()
if missing value is v then
set v to x
else
set v to g(v)
end if
return v
end |λ|
end script
end iterate
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
2 ^ 30 -- (simple proxy for non-finite)
end if
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- plus :: Num -> Num -> Num
on plus(a, b)
a + b
end plus
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set end of ys to xs's |λ|()
end repeat
return ys
else
missing value
end if
end take
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
-- unwords :: [String] -> String
on unwords(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, space}
set s to xs as text
set my text item delimiters to dlm
return s
end unwords
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith |
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 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #C.2B.2B | C++ | #include <boost/asio/ip/address.hpp>
#include <cstdint>
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
using boost::asio::ip::address;
using boost::asio::ip::address_v4;
using boost::asio::ip::address_v6;
using boost::asio::ip::make_address;
using boost::asio::ip::make_address_v4;
using boost::asio::ip::make_address_v6;
template<typename uint>
bool parse_int(const std::string& str, int base, uint& n) {
try {
size_t pos = 0;
unsigned long u = stoul(str, &pos, base);
if (pos != str.length() || u > std::numeric_limits<uint>::max())
return false;
n = static_cast<uint>(u);
return true;
} catch (const std::exception& ex) {
return false;
}
}
//
// Parse an IP address and port from the given input string.
//
// Throws an exception if the input is not valid.
//
// Valid formats are:
// [ipv6_address]:port
// ipv4_address:port
// ipv4_address
// ipv6_address
//
void parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) {
size_t pos = input.rfind(':');
if (pos != std::string::npos && pos > 1 && pos + 1 < input.length()
&& parse_int(input.substr(pos + 1), 10, port) && port > 0) {
if (input[0] == '[' && input[pos - 1] == ']') {
// square brackets so can only be an IPv6 address
addr = make_address_v6(input.substr(1, pos - 2));
return;
} else {
try {
// IPv4 address + port?
addr = make_address_v4(input.substr(0, pos));
return;
} catch (const std::exception& ex) {
// nope, might be an IPv6 address
}
}
}
port = 0;
addr = make_address(input);
}
void print_address_and_port(const address& addr, uint16_t port) {
std::cout << std::hex << std::uppercase << std::setfill('0');
if (addr.is_v4()) {
address_v4 addr4 = addr.to_v4();
std::cout << "address family: IPv4\n";
std::cout << "address number: " << std::setw(8) << addr4.to_uint() << '\n';
} else if (addr.is_v6()) {
address_v6 addr6 = addr.to_v6();
address_v6::bytes_type bytes(addr6.to_bytes());
std::cout << "address family: IPv6\n";
std::cout << "address number: ";
for (unsigned char byte : bytes)
std::cout << std::setw(2) << static_cast<unsigned int>(byte);
std::cout << '\n';
}
if (port != 0)
std::cout << "port: " << std::dec << port << '\n';
else
std::cout << "port not specified\n";
}
void test(const std::string& input) {
std::cout << "input: " << input << '\n';
try {
address addr;
uint16_t port = 0;
parse_ip_address_and_port(input, addr, port);
print_address_and_port(addr, port);
} catch (const std::exception& ex) {
std::cout << "parsing failed\n";
}
std::cout << '\n';
}
int main(int argc, char** argv) {
test("127.0.0.1");
test("127.0.0.1:80");
test("::ffff:127.0.0.1");
test("::1");
test("[::1]:80");
test("1::80");
test("2605:2700:0:3::4713:93e3");
test("[2605:2700:0:3::4713:93e3]:80");
return 0;
} |
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #C.2B.2B | C++ | template<class T>
class tree
{
T value;
tree *left;
tree *right;
public:
void replace_all (T new_value);
}; |
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #C3 | C3 | module tree<Type>;
struct Tree
{
Type value;
Tree* left;
Tree* right;
}
fn void Tree.replaceAll(Tree* a_tree, Type new_value)
{
a_tree.value = new_value;
if (a_tree.left) a_tree.left.replaceAll(new_value);
if (a_tree.right) a_tree.right.replaceAll(new_value);
}
|
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #Ceylon | Ceylon | class BinaryTree<Data>(shared Data data, shared BinaryTree<Data>? left = null, shared BinaryTree<Data>? right = null) {
shared BinaryTree<NewData> myMap<NewData>(NewData f(Data d)) =>
BinaryTree {
data = f(data);
left = left?.myMap(f);
right = right?.myMap(f);
};
}
shared void run() {
value tree1 = BinaryTree {
data = 3;
left = BinaryTree {
data = 4;
};
right = BinaryTree {
data = 5;
left = BinaryTree {
data = 6;
};
};
};
tree1.myMap(print);
print("");
value tree2 = tree1.myMap((x) => x * 333.33);
tree2.myMap(print);
} |
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.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
initStack()
initOpers()
print "Infix: " toInfix("3 4 2 * 1 5 - 2 3 ^ ^ / +")
print ""
print "Infix: " toInfix("1 2 + 3 4 + ^ 5 6 + ^")
print ""
print "Infix: " toInfix("moon stars mud + * fire soup * ^")
exit
}
function initStack() {
delete stack
stackPtr = 0
}
function initOpers() {
VALPREC = "9"
LEFT = "l"
RIGHT = "r"
operToks = "+" "-" "/" "*" "^"
operPrec = "2" "2" "3" "3" "4"
operAssoc = LEFT LEFT LEFT LEFT RIGHT
}
function toInfix(rpn, t, toks, tok, a, ap, b, bp, tp, ta) {
print "Postfix: " rpn
split(rpn, toks, / +/)
for (t = 1; t <= length(toks); t++) {
tok = toks[t]
if (!isOper(tok)) {
push(VALPREC tok)
}
else {
b = pop()
bp = prec(b)
b = tail(b)
a = pop()
ap = prec(a)
a = tail(a)
tp = tokPrec(tok)
ta = tokAssoc(tok)
if (ap < tp || (ap == tp && ta == RIGHT)) {
a = "(" a ")"
}
if (bp < tp || (bp == tp && ta == LEFT)) {
b = "(" b ")"
}
push(tp a " " tok " " b)
}
print " " tok " -> " stackToStr()
}
return tail(pop())
}
function push(expr) {
stack[stackPtr] = expr
stackPtr++
}
function pop() {
stackPtr--
return stack[stackPtr]
}
function isOper(tok) {
return index(operToks, tok) != 0
}
function prec(expr) {
return substr(expr, 1, 1)
}
function tokPrec(tok) {
return substr(operPrec, operIdx(tok), 1)
}
function tokAssoc(tok) {
return substr(operAssoc, operIdx(tok), 1)
}
function operIdx(tok) {
return index(operToks, tok)
}
function tail(s) {
return substr(s, 2)
}
function stackToStr( s, i, t, p) {
s = ""
for (i = 0; i < stackPtr; i++) {
t = stack[i]
p = prec(t)
if (index(t, " ")) t = "{" tail(t) "}"
else t = tail(t)
s = s "{" p " " t "} "
}
return s
}
|
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
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Ceylon | Ceylon | shared void run() {
function fs(Integer f(Integer n), {Integer*} s) => s.map(f);
function f1(Integer n) => n * 2;
function f2(Integer n) => n ^ 2;
value fsCurried = curry(fs);
value fsf1 = fsCurried(f1);
value fsf2 = fsCurried(f2);
value ints = 0..3;
print("fsf1(``ints``) is ``fsf1(ints)`` and fsf2(``ints``) is ``fsf2(ints)``");
value evens = (2..8).by(2);
print("fsf1(``evens``) is ``fsf1(evens)`` and fsf2(``evens``) is ``fsf2(evens)``");
} |
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
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Clojure | Clojure | (defn fs [f s] (map f s))
(defn f1 [x] (* 2 x))
(defn f2 [x] (* x x))
(def fsf1 (partial fs f1))
(def fsf2 (partial fs f2))
(doseq [s [(range 4) (range 2 9 2)]]
(println "seq: " s)
(println " fsf1: " (fsf1 s))
(println " fsf2: " (fsf2 s))) |
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.
• partition 18 with 2 primes.
• partition 19 with 3 primes.
• partition 20 with 4 primes.
• partition 2017 with 24 primes.
• partition 22699 with 1, 2, 3, and 4 primes.
• partition 40355 with 3 primes.
The output could/should be shown in a format such as:
Partitioned 19 with 3 primes: 3+5+11
Use any spacing that may be appropriate for the display.
You need not validate the input(s).
Use the lowest primes possible; use 18 = 5+13, not 18 = 7+11.
You only need to show one solution.
This task is similar to factoring an integer.
Related tasks
Count in factors
Prime decomposition
Factors of an integer
Sieve of Eratosthenes
Primality by trial division
Factors of a Mersenne number
Factors of a Mersenne number
Sequence of primes by trial division
| #jq | jq |
# Is the input integer a prime?
def is_prime:
if . == 2 then true
else 2 < . and . % 2 == 1 and
. as $in
| (($in + 1) | sqrt) as $m
| (((($m - 1) / 2) | floor) + 1) as $max
| all( range(1; $max) ; $in % ((2 * .) + 1) > 0 )
end;
# Is the input integer a prime?
# `previous` should be a sorted array of consecutive primes
# greater than 1 and at least including the greatest prime less than (.|sqrt)
def is_prime(previous):
. as $in
| (($in + 1) | sqrt) as $sqrt
| first(previous[]
| if . > $sqrt then 1
elif 0 == ($in % .) then 0
else empty
end) // 1
| . == 1;
# This assumes . is an array of consecutive primes beginning with [2,3]
def next_prime:
. as $previous
| (2 + .[-1] )
| until(is_prime($previous); . + 2) ;
# Emit primes from 2 up
def primes:
# The helper function has arity 0 for TCO
# It expects its input to be an array of previously found primes, in order:
def next:
. as $previous
| ($previous|next_prime) as $next
| $next, (($previous + [$next]) | next) ;
2, 3, ([2,3] | next);
# The primes less than or equal to $x
def primes($x):
label $out
| primes | if . > $x then break $out else . end;
|
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.
• partition 18 with 2 primes.
• partition 19 with 3 primes.
• partition 20 with 4 primes.
• partition 2017 with 24 primes.
• partition 22699 with 1, 2, 3, and 4 primes.
• partition 40355 with 3 primes.
The output could/should be shown in a format such as:
Partitioned 19 with 3 primes: 3+5+11
Use any spacing that may be appropriate for the display.
You need not validate the input(s).
Use the lowest primes possible; use 18 = 5+13, not 18 = 7+11.
You only need to show one solution.
This task is similar to factoring an integer.
Related tasks
Count in factors
Prime decomposition
Factors of an integer
Sieve of Eratosthenes
Primality by trial division
Factors of a Mersenne number
Factors of a Mersenne number
Sequence of primes by trial division
| #Julia | Julia | using Primes, Combinatorics
function primepartition(x::Int64, n::Int64)
if n == oftype(n, 1)
return isprime(x) ? [x] : Int64[]
else
for combo in combinations(primes(x), n)
if sum(combo) == x
return combo
end
end
end
return Int64[]
end
for (x, n) in [[ 18, 2], [ 19, 3], [ 20, 4], [99807, 1], [99809, 1],
[ 2017, 24],[22699, 1], [22699, 2], [22699, 3], [22699, 4] ,[40355, 3]]
ans = primepartition(x, n)
println("Partition of ", x, " into ", n, " primes: ",
isempty(ans) ? "impossible" : join(ans, " + "))
end |
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | PartitionsP /@ Range[15]
PartitionsP[666]
PartitionsP[6666] |
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Nim | Nim | import sequtils, strformat, times
import bignum
func partitions(n: int): Int =
var p = newSeqWith(n + 1, newInt())
p[0] = newInt(1)
for i in 1..n:
var k = 1
while true:
var j = k * (3 * k - 1) div 2
if j > i: break
if (k and 1) != 0:
inc p[i], p[i - j]
else:
dec p[i], p[i - j]
j = k * (3 * k + 1) div 2
if j > i: break
if (k and 1) != 0:
inc p[i], p[i - j]
else:
dec p[i], p[i - j]
inc k
result = p[n]
let t0 = cpuTime()
echo partitions(6666)
echo &"Elapsed time: {(cpuTime() - t0) * 1000:.2f} ms" |
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Perl | Perl | use strict;
use warnings;
no warnings qw(recursion);
use Math::AnyNum qw(:overload);
use Memoize;
memoize('partitionsP');
memoize('partDiff');
sub partDiffDiff { my($n) = @_; $n%2 != 0 ? ($n+1)/2 : $n+1 }
sub partDiff { my($n) = @_; $n<2 ? 1 : partDiff($n-1) + partDiffDiff($n-1) }
sub partitionsP {
my($n) = @_;
return 1 if $n < 2;
my $psum = 0;
for my $i (1..$n) {
my $pd = partDiff($i);
last if $pd > $n;
if ( (($i-1)%4) < 2 ) { $psum += partitionsP($n-$pd) }
else { $psum -= partitionsP($n-$pd) }
}
return $psum
}
print partitionsP($_) . ' ' for 0..25; print "\n";
print partitionsP(6666) . "\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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #Maple | Maple |
sys := {22 + x + y = 40, 78 + 5*y + z = 151, x + z = y}:
solve(sys, {x,y,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 on an n-by-n square grid, (the board), so that no queen attacks another of a different colour.
Task
Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).
Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
Display here results for the m=4, n=5 case.
References
Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
A250000 OEIS
| #Ruby | Ruby | class Position
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
self.x == other.x &&
self.y == other.y
end
def to_s
'(%d, %d)' % [@x, @y]
end
def to_str
to_s
end
end
def isAttacking(queen, pos)
return queen.x == pos.x ||
queen.y == pos.y ||
(queen.x - pos.x).abs() == (queen.y - pos.y).abs()
end
def place(m, n, blackQueens, whiteQueens)
if m == 0 then
return true
end
placingBlack = true
for i in 0 .. n-1
for j in 0 .. n-1
catch :inner do
pos = Position.new(i, j)
for queen in blackQueens
if pos == queen || !placingBlack && isAttacking(queen, pos) then
throw :inner
end
end
for queen in whiteQueens
if pos == queen || placingBlack && isAttacking(queen, pos) then
throw :inner
end
end
if placingBlack then
blackQueens << pos
placingBlack = false
else
whiteQueens << pos
if place(m - 1, n, blackQueens, whiteQueens) then
return true
end
blackQueens.pop
whiteQueens.pop
placingBlack = true
end
end
end
end
if !placingBlack then
blackQueens.pop
end
return false
end
def printBoard(n, blackQueens, whiteQueens)
# initialize the board
board = Array.new(n) { Array.new(n) { ' ' } }
for i in 0 .. n-1
for j in 0 .. n-1
if i % 2 == j % 2 then
board[i][j] = '•'
else
board[i][j] = '◦'
end
end
end
# insert the queens
for queen in blackQueens
board[queen.y][queen.x] = 'B'
end
for queen in whiteQueens
board[queen.y][queen.x] = 'W'
end
# print the board
for row in board
for cell in row
print cell, ' '
end
print "\n"
end
print "\n"
end
nms = [
[2, 1],
[3, 1], [3, 2],
[4, 1], [4, 2], [4, 3],
[5, 1], [5, 2], [5, 3], [5, 4], [5, 5],
[6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6],
[7, 1], [7, 2], [7, 3], [7, 4], [7, 5], [7, 6], [7, 7]
]
for nm in nms
m = nm[1]
n = nm[0]
print "%d black and %d white queens on a %d x %d board:\n" % [m, m, n, n]
blackQueens = []
whiteQueens = []
if place(m, n, blackQueens, whiteQueens) then
printBoard(n, blackQueens, whiteQueens)
else
print "No solution exists.\n\n"
end
end |
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 character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Haskell | Haskell | import Control.Monad
import Control.Monad.Random
import Data.List
password :: MonadRandom m => [String] -> Int -> m String
password charSets n = do
parts <- getPartition n
chars <- zipWithM replicateM parts (uniform <$> charSets)
shuffle (concat chars)
where
getPartition n = adjust <$> replicateM (k-1) (getRandomR (1, n `div` k))
k = length charSets
adjust p = (n - sum p) : p
shuffle :: (Eq a, MonadRandom m) => [a] -> m [a]
shuffle [] = pure []
shuffle lst = do
x <- uniform lst
xs <- shuffle (delete x lst)
return (x : xs) |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Sidef | Sidef | [0,1,2].permutations { |p|
say p
} |
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 player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins.
Example
One player might choose the sequence HHT and the other THT.
Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence.
Task
Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent.
Who chooses and shows their sequence of three should be chosen randomly.
If going first, the computer should randomly choose its sequence of three.
If going second, the computer should automatically play the optimum sequence.
Successive coin tosses should be shown.
Show output of a game where the computer chooses first and a game where the user goes first here on this page.
See also
The Penney Ante Part 1 (Video).
The Penney Ante Part 2 (Video).
| #Racket | Racket | #lang racket
;; Penney's Game. Tim Brown 2014-10-15
(define (flip . _) (match (random 2) (0 "H") (1 "T")))
(define (get-human-sequence) ; no sanity checking here!
(display "choose your winning sequence of 3 H or T > ")
(drop-right (drop (string-split (string-upcase (read-line)) "") 1) 1))
(define flips->string (curryr string-join "."))
(define (game-on p1 p2)
(printf "~a chooses: ~a. ~a chooses: ~a~%"
(car p1) (flips->string (cdr p1)) (car p2) (flips->string (cdr p2)))
(match-define (list (list name.1 p1.1 p1.2 p1.3) (list name.2 p2.1 p2.2 p2.3)) (list p1 p2))
(let turn ((seq null))
(match seq
[(list-rest (== p1.3) (== p1.2) (== p1.1) _) name.1]
[(list-rest (== p2.3) (== p2.2) (== p2.1) _) name.2]
[else
(let* ((flp (flip)) (seq+ (cons flp else)))
(printf "new-flip: ~a -> ~a~%" flp (flips->string (reverse seq+))) (turn seq+))])))
(define (play-game)
(define-values
(player-1 player-2)
(match (flip)
["H" (printf "Human chooses first: ")
(define p1 (cons 'Hom-Sap (get-human-sequence)))
(values p1 (cons 'Computer
(match p1
[(list _ f1 (and f2 (app (match-lambda ("H" "T") ("T" "H")) ¬f2)) _)
(list ¬f2 f1 f2)])))]
["T" (printf "Computer chooses first. ")
(define p1 (cons 'Computer (build-list 3 flip)))
(printf "~a chooses: ~a~%" (car p1) (flips->string (cdr p1)))
(values p1 (cons 'Hom-Sap (get-human-sequence)))]))
(printf "~a wins!~%" (game-on player-1 player-2))) |
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 player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins.
Example
One player might choose the sequence HHT and the other THT.
Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence.
Task
Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent.
Who chooses and shows their sequence of three should be chosen randomly.
If going first, the computer should randomly choose its sequence of three.
If going second, the computer should automatically play the optimum sequence.
Successive coin tosses should be shown.
Show output of a game where the computer chooses first and a game where the user goes first here on this page.
See also
The Penney Ante Part 1 (Video).
The Penney Ante Part 2 (Video).
| #Raku | Raku | enum Coin <Heads Tails>;
enum Yay <Yay Good Super Hah Ooh Yipee Sweet Cool Yes Haha>;
enum Boo <Drat Darn Crumb Oops Rats Bah Criminy Argh Shards>;
enum Bozo «'Dude' 'Cha' 'Bzzt' 'Hey' 'Silly dilly' 'Say what!?' 'You numbskull'»;
sub flipping {
for 1..4 {
print "-\b"; sleep .1;
print "\\\b"; sleep .1;
print "|\b"; sleep .1;
print "/\b"; sleep .1;
}
}
sub your-choice($p is copy) {
loop (my @seq; @seq != 3; $p = "{Bozo.pick}! Please pick exactly 3: ") {
@seq = prompt($p).uc.comb(/ H | T /).map: {
when 'H' { Heads }
when 'T' { Tails }
}
}
@seq;
}
repeat until prompt("Wanna play again? ").lc ~~ /^n/ {
my $mefirst = Coin.roll;
print tc "$mefirst I start, {Coin(+!$mefirst).lc} you start, flipping...\n\t";
flipping;
say my $flip = Coin.roll;
my @yours;
my @mine;
if $flip == $mefirst {
print "{Yay.pick}! I get to choose first, and I choose: "; sleep 2; say @mine = |Coin.roll(3);
@yours = your-choice("Now you gotta choose: ");
while @yours eqv @mine {
say "{Bozo.pick}! We'd both win at the same time if you pick that!";
@yours = your-choice("Pick something different from me: ");
}
say "So, you'll win if we see: ", @yours;
}
else {
@yours = your-choice("{Boo.pick}! First you choose: ");
say "OK, you'll win if we see: ", @yours;
print "In that case, I'll just randomly choose: "; sleep 2; say @mine = Coin(+!@yours[1]), |@yours[0,1];
}
sub check($a,$b,$c) {
given [$a,$b,$c] {
when @mine { say "\n{Yay.pick}, I win, and you lose!"; Nil }
when @yours { say "\n{Boo.pick}, you win, but I'll beat you next time!"; Nil }
default { Coin.roll }
}
}
sleep 1;
say < OK! Ready? Right... So... Yo!>.pick;
sleep .5;
say ("Pay attention now!",
"Watch closely!",
"Let's do it...",
"You feeling lucky?",
"No way you gonna win this...",
"Can I borrow that coin again?").pick;
sleep 1;
print "Here we go!\n\t";
for |Coin.roll(3), &check ...^ :!defined {
flipping;
print "$_ ";
}
} |
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 problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.
This task's purpose is to show how your language deals with such classes of problems.
A sequence that seems to converge to a wrong limit.
Consider the sequence:
v1 = 2
v2 = -4
vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2)
As n grows larger, the series should converge to 6 but small amounts of error will cause it to approach 100.
Task 1
Display the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least 16 decimal places.
n = 3 18.5
n = 4 9.378378
n = 5 7.801153
n = 6 7.154414
n = 7 6.806785
n = 8 6.5926328
n = 20 6.0435521101892689
n = 30 6.006786093031205758530554
n = 50 6.0001758466271871889456140207471954695237
n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266
Task 2
The Chaotic Bank Society is offering a new investment account to their customers.
You first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.
After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed.
So ...
after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.
after 2 years your balance will be doubled and $1 removed.
after 3 years your balance will be tripled and $1 removed.
...
after 10 years, multiplied by 10 and $1 removed, and so on.
What will your balance be after 25 years?
Starting balance: $e-1
Balance = (Balance * year) - 1 for 25 years
Balance after 25 years: $0.0399387296732302
Task 3, extra credit
Siegfried Rump's example. Consider the following function, designed by Siegfried Rump in 1988.
f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b)
compute f(a,b) where a=77617.0 and b=33096.0
f(77617.0, 33096.0) = -0.827396059946821
Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.
See also;
Floating-Point Arithmetic Section 1.3.2 Difficult problems.
| #PicoLisp | PicoLisp | (scl 150)
(de task1 (N)
(cache '(NIL) N
(cond
((= N 1) 2.0)
((= N 2) -4.0)
(T
(+
(- 111.0 (*/ 1.0 1130.0 (task1 (- N 1))))
(*/
1.0
3000.0
(*/
(task1 (- N 2))
(task1 (- N 1))
1.0 ) ) ) ) ) ) )
(for N (list 3 4 5 6 7 8 20 30 50 100)
(println 'N: N (round (task1 N) 20)) )
# task 2
(setq B (- 2.7182818284590452353602874713526624977572470 1.0))
(for N 25
(setq B
(-
(* N B)
1.0 ) ) )
(prinl "bank balance after 25 years: " (round B 20))
# task 3
(de pow (A B) # fixedpoint
(*/ 1.0 (** A B) (** 1.0 B)) )
(de task3 (A B)
(let
(A2 (pow A 2)
B2 (pow B 2)
B4 (pow B 4)
B6 (pow B 6)
B8 (pow B 8) )
(+
(*/ 333.75 B6 1.0)
(*/
A2
(-
(*/ 11.0 A2 B2 (** 1.0 2))
B6
(* 121 B4)
2.0 )
1.0 )
(*/ 5.5 B8 1.0)
(*/ 1.0 A (*/ 2.0 B 1.0)) ) ) )
(prinl "Rump's example: " (round (task3 77617.0 33096.0) 20)) |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #Ada | Ada | with Ada.Text_IO;
with CryptAda.Digests.Message_Digests.SHA_256;
with CryptAda.Digests.Hashes;
with CryptAda.Pragmatics;
procedure Brute_Force is
use CryptAda.Digests.Message_Digests;
use CryptAda.Digests.Hashes;
use CryptAda.Digests;
use CryptAda.Pragmatics;
Wanted_Sums : constant array (1 .. 3) of String (1 .. 64) :=
(1 => "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
2 => "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
3 => "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f");
Wanted_Hash : constant array (1 .. 3) of Hashes.Hash :=
(1 => Hashes.To_Hash (Wanted_Sums (1)),
2 => Hashes.To_Hash (Wanted_Sums (2)),
3 => Hashes.To_Hash (Wanted_Sums (3)));
subtype Ciffer is Byte range Character'Pos ('a') .. Character'Pos ('z');
subtype Code is Byte_Array (1 .. 5);
task type Worker (First : Byte) is
end Worker;
procedure Compare (Hash : in Hashes.Hash; Bytes : in Code) is
begin
for I in Wanted_Hash'Range loop
if Hash = Wanted_Hash (I) then
Ada.Text_IO.Put (Wanted_Sums (I) & " ");
for C of Bytes loop
Ada.Text_IO.Put (Character'Val (C));
end loop;
Ada.Text_IO.New_Line;
end if;
end loop;
end Compare;
task body Worker is
Handle : constant Message_Digest_Handle := SHA_256.Get_Message_Digest_Handle;
Digest : constant Message_Digest_Ptr := Get_Message_Digest_Ptr (Handle);
Bytes : Code;
Hash : Hashes.Hash;
begin
Bytes (Bytes'First) := First;
for B2 in Ciffer'Range loop
for B3 in Ciffer'Range loop
for B4 in Ciffer'Range loop
Bytes (2 .. 4) := B2 & B3 & B4;
for B5 in Ciffer'Range loop
Bytes (5) := B5;
Digest_Start (Digest);
Digest_Update (Digest, Bytes);
Digest_End (Digest, Hash);
Compare (Hash, Bytes);
end loop;
end loop;
end loop;
end loop;
end Worker;
type Worker_Access is access Worker;
Work : Worker_Access;
pragma Unreferenced (Work);
begin
for C in Ciffer'Range loop
Work := new Worker (First => C);
end loop;
end Brute_Force; |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #Ada | Ada | generic
type Number is private;
Zero : Number;
One : Number;
Two : Number;
with function Image (X : Number) return String is <>;
with function "+" (X, Y : Number) return Number is <>;
with function "/" (X, Y : Number) return Number is <>;
with function "mod" (X, Y : Number) return Number is <>;
with function ">=" (X, Y : Number) return Boolean is <>;
package Prime_Numbers is
type Number_List is array (Positive range <>) of Number;
procedure Put (List : Number_List);
task type Calculate_Factors is
entry Start (The_Number : in Number);
entry Get_Size (Size : out Natural);
entry Get_Result (List : out Number_List);
end Calculate_Factors;
end Prime_Numbers; |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE PTR="CARD"
DEFINE BUFFER_SIZE="60"
DEFINE ENTRY_SIZE="6"
DEFINE MAX_SIZE="10"
BYTE ARRAY stack(BUFFER_SIZE)
BYTE stackSize=[0]
BYTE FUNC IsEmpty()
IF stackSize=0 THEN
RETURN (1)
FI
RETURN (0)
PTR FUNC GetPtr(BYTE i)
RETURN (stack+i*ENTRY_SIZE)
PROC Push(REAL POINTER v)
REAL POINTER p
IF stackSize=MAX_SIZE THEN
PrintE("Error: stack is full!")
Break()
FI
p=GetPtr(stackSize)
RealAssign(v,p)
stackSize==+1
RETURN
PROC Pop(REAL POINTER v)
REAL POINTER p
IF IsEmpty() THEN
PrintE("Error: stack is empty!")
Break()
FI
stackSize==-1
p=GetPtr(stackSize)
RealAssign(p,v)
RETURN
PROC PrintStack()
INT i
REAL POINTER p
FOR i=0 TO stackSize-1
DO
p=GetPtr(i)
PrintR(p) Put(32)
OD
PutE()
RETURN
BYTE FUNC GetToken(CHAR ARRAY s BYTE start CHAR ARRAY t)
BYTE pos
pos=start
WHILE pos<=s(0) AND s(pos)#'
DO
pos==+1
OD
SCopyS(t,s,start,pos-1)
RETURN (pos)
PROC MyPower(REAL POINTER base,exp,res)
INT i,expI
REAL tmp
expI=RealToInt(exp)
IF expI<0 THEN Break() FI
IntToReal(1,res)
FOR i=1 TO expI
DO
RealMult(res,base,tmp)
RealAssign(tmp,res)
OD
RETURN
PROC Process(CHAR ARRAY s)
DEFINE Pop21="Pop(v2) Pop(v1)"
CHAR ARRAY t(100)
BYTE i,j
CHAR c
REAL v1,v2,v3
i=1
WHILE i<=s(0)
DO
WHILE i<=s(0) AND s(i)='
DO i==+1 OD
IF i>s(0) THEN EXIT FI
i=GetToken(s,i,t)
IF SCompare(t,"+")=0 THEN
Pop21 RealAdd(v1,v2,v3)
Print("calc +: ")
ELSEIF SCompare(t,"-")=0 THEN
Pop21 RealSub(v1,v2,v3)
Print("calc -: ")
ELSEIF SCompare(t,"*")=0 THEN
Pop21 RealMult(v1,v2,v3)
Print("calc *: ")
ELSEIF SCompare(t,"/")=0 THEN
Pop21 RealDiv(v1,v2,v3)
Print("calc /: ")
ELSEIF SCompare(t,"^")=0 THEN
Pop21 MyPower(v1,v2,v3)
Print("calc ^: ")
ELSE
ValR(t,v3)
PrintF("push %S: ",t)
FI
Push(v3)
PrintStack()
OD
RETURN
PROC Test(CHAR ARRAY s)
PrintE(s) PutE()
Process(s)
RETURN
PROC Main()
Put(125) PutE() ;clear the screen
Test("3 4 2 * 1 5 - 2 3 ^ ^ / +")
RETURN |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Ada | Ada | with Ada.Text_IO, Ada.Containers.Vectors;
procedure RPN_Calculator is
package IIO is new Ada.Text_IO.Float_IO(Float);
package Float_Vec is new Ada.Containers.Vectors
(Index_Type => Positive, Element_Type => Float);
Stack: Float_Vec.Vector;
Input: String := Ada.Text_IO.Get_Line;
Cursor: Positive := Input'First;
New_Cursor: Positive;
begin
loop
-- read spaces
while Cursor <= Input'Last and then Input(Cursor)=' ' loop
Cursor := Cursor + 1;
end loop;
exit when Cursor > Input'Last;
New_Cursor := Cursor;
while New_Cursor <= Input'Last and then Input(New_Cursor) /= ' ' loop
New_Cursor := New_Cursor + 1;
end loop;
-- try to read a number and push it to the stack
declare
Last: Positive;
Value: Float;
X, Y: Float;
begin
IIO.Get(From => Input(Cursor .. New_Cursor - 1),
Item => Value,
Last => Last);
Stack.Append(Value);
Cursor := New_Cursor;
exception -- if reading the number fails, try to read an operator token
when others =>
Y := Stack.Last_Element; Stack.Delete_Last; -- pick two elements
X := Stack.Last_Element; Stack.Delete_Last; -- from the stack
case Input(Cursor) is
when '+' => Stack.Append(X+Y);
when '-' => Stack.Append(X-Y);
when '*' => Stack.Append(X*Y);
when '/' => Stack.Append(X/Y);
when '^' => Stack.Append(X ** Integer(Float'Rounding(Y)));
when others => raise Program_Error with "unecpected token '"
& Input(Cursor) & "' at column" & Integer'Image(Cursor);
end case;
Cursor := New_Cursor;
end;
for I in Stack.First_Index .. Stack.Last_Index loop
Ada.Text_IO.Put(" ");
IIO.Put(Stack.Element(I), Aft => 5, Exp => 0);
end loop;
Ada.Text_IO.New_Line;
end loop;
Ada.Text_IO.Put("Result = ");
IIO.Put(Item => Stack.Last_Element, Aft => 5, Exp => 0);
end RPN_Calculator; |
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
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #C | C | #include <sys/types.h>
#include <regex.h>
#include <stdio.h>
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {"", A_NONE, 0};
pat_t pat_ops[] = {
{"^\\)", A_NONE, -1},
{"^\\*\\*", A_R, 3},
{"^\\^", A_R, 3},
{"^\\*", A_L, 2},
{"^/", A_L, 2},
{"^\\+", A_L, 1},
{"^-", A_L, 1},
{0}
};
pat_t pat_arg[] = {
{"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"},
{"^[a-zA-Z_][a-zA-Z_0-9]*"},
{"^\\(", A_L, -1},
{0}
};
str_tok_t stack[256]; /* assume these are big enough */
str_tok_t queue[256];
int l_queue, l_stack;
#define qpush(x) queue[l_queue++] = x
#define spush(x) stack[l_stack++] = x
#define spop() stack[--l_stack]
void display(const char *s)
{
int i;
printf("\033[1;1H\033[JText | %s", s);
printf("\nStack| ");
for (i = 0; i < l_stack; i++)
printf("%.*s ", stack[i].len, stack[i].s); // uses C99 format strings
printf("\nQueue| ");
for (i = 0; i < l_queue; i++)
printf("%.*s ", queue[i].len, queue[i].s);
puts("\n\n<press enter>");
getchar();
}
int prec_booster;
#define fail(s1, s2) {fprintf(stderr, "[Error %s] %s\n", s1, s2); return 0;}
int init(void)
{
int i;
pat_t *p;
for (i = 0, p = pat_ops; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
for (i = 0, p = pat_arg; p[i].str; i++)
if (regcomp(&(p[i].re), p[i].str, REG_NEWLINE|REG_EXTENDED))
fail("comp", p[i].str);
return 1;
}
pat_t* match(const char *s, pat_t *p, str_tok_t * t, const char **e)
{
int i;
regmatch_t m;
while (*s == ' ') s++;
*e = s;
if (!*s) return &pat_eos;
for (i = 0; p[i].str; i++) {
if (regexec(&(p[i].re), s, 1, &m, REG_NOTEOL))
continue;
t->s = s;
*e = s + (t->len = m.rm_eo - m.rm_so);
return p + i;
}
return 0;
}
int parse(const char *s) {
pat_t *p;
str_tok_t *t, tok;
prec_booster = l_queue = l_stack = 0;
display(s);
while (*s) {
p = match(s, pat_arg, &tok, &s);
if (!p || p == &pat_eos) fail("parse arg", s);
/* Odd logic here. Don't actually stack the parens: don't need to. */
if (p->prec == -1) {
prec_booster += 100;
continue;
}
qpush(tok);
display(s);
re_op: p = match(s, pat_ops, &tok, &s);
if (!p) fail("parse op", s);
tok.assoc = p->assoc;
tok.prec = p->prec;
if (p->prec > 0)
tok.prec = p->prec + prec_booster;
else if (p->prec == -1) {
if (prec_booster < 100)
fail("unmatched )", s);
tok.prec = prec_booster;
}
while (l_stack) {
t = stack + l_stack - 1;
if (!(t->prec == tok.prec && t->assoc == A_L)
&& t->prec <= tok.prec)
break;
qpush(spop());
display(s);
}
if (p->prec == -1) {
prec_booster -= 100;
goto re_op;
}
if (!p->prec) {
display(s);
if (prec_booster)
fail("unmatched (", s);
return 1;
}
spush(tok);
display(s);
}
if (p->prec > 0)
fail("unexpected eol", s);
return 1;
}
int main()
{
int i;
const char *tests[] = {
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3", /* RC mandated: OK */
"123", /* OK */
"3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14", /* OK */
"(((((((1+2+3**(4 + 5))))))", /* bad parens */
"a^(b + c/d * .1e5)!", /* unknown op */
"(1**2)**3", /* OK */
"2 + 2 *", /* unexpected eol */
0
};
if (!init()) return 1;
for (i = 0; tests[i]; i++) {
printf("Testing string `%s' <enter>\n", tests[i]);
getchar();
printf("string `%s': %s\n\n", tests[i],
parse(tests[i]) ? "Ok" : "Error");
}
return 0;
} |
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:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #BCPL | BCPL | get "libhdr"
manifest $( size = 5 $)
// Matrix index
let ix(mat, n, x, y) = mat+y*n+x
let lower(m, n) be
for y=0 to n-1
for x=0 to n-1 do
!ix(m,n,x,y) :=
x>y -> 0,
x=y | x=0 -> 1,
!ix(m,n,x-1,y-1) + !ix(m,n,x,y-1)
let upper(m, n) be
for y=0 to n-1
for x=0 to n-1 do
!ix(m,n,x,y) :=
x<y -> 0,
x=y | y=0 -> 1,
!ix(m,n,x-1,y-1) + !ix(m,n,x-1,y)
let symmetric(m, n) be
for y=0 to n-1
for x=0 to n-1 do
!ix(m,n,x,y) :=
x=0 | y=0 -> 1,
!ix(m,n,x-1,y) + !ix(m,n,x,y-1)
// Print matrix
let writemat(m, n, d) be
for y=0 to n-1
$( for x=0 to n-1
$( writed(!ix(m,n,x,y), d)
wrch(' ')
$)
wrch('*N')
$)
// Generate and print 5-by-5 matrices
let start() be
$( let mat = vec size * size
writes("Upper-triangular matrix:*N")
upper(mat, size) ; writemat(mat, size, 2)
writes("*NLower-triangular matrix:*N")
lower(mat, size) ; writemat(mat, size, 2)
writes("*NSymmetric matrix:*N")
symmetric(mat, size) ; writemat(mat, size, 2)
$) |
http://rosettacode.org/wiki/Parameterized_SQL_statement | Parameterized SQL statement | SQL injection
Using a SQL update statement like this one (spacing is optional):
UPDATE players
SET name = 'Smith, Steve', score = 42, active = TRUE
WHERE jerseyNum = 99
Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either. | #Ada | Ada | -- Version for sqlite
with GNATCOLL.SQL_Impl; use GNATCOLL.SQL_Impl;
with GNATCOLL.SQL.Exec; use GNATCOLL.SQL.Exec;
with GNATCOLL.SQL.Sqlite; use GNATCOLL.SQL;
procedure Prepared_Query is
DB_Descr : Database_Description;
Conn : Database_Connection;
Query : Prepared_Statement;
--sqlite does not support boolean fields
True_Str : aliased String := "TRUE";
Param : SQL_Parameters (1 .. 4) :=
(1 => (Parameter_Text, null),
2 => (Parameter_Integer, 0),
3 => (Parameter_Text, null),
4 => (Parameter_Integer, 0));
begin
-- Allocate and initialize the description of the connection
Setup_Database (DB_Descr, "rosetta.db", "", "", "", DBMS_Sqlite);
-- Allocate the connection
Conn := Sqlite.Build_Sqlite_Connection (DB_Descr);
-- Initialize the connection
Reset_Connection (DB_Descr, Conn);
Query :=
Prepare
("UPDATE players SET name = ?, score = ?, active = ? " &
" WHERE jerseyNum = ?");
declare
Name : aliased String := "Smith, Steve";
begin
Param := ("+" (Name'Access), "+" (42), "+" (True_Str'Access), "+" (99));
Execute (Conn, Query, Param);
end;
Commit_Or_Rollback (Conn);
Free (Conn);
Free (DB_Descr);
end Prepared_Query; |
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 elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Arturo | Arturo | pascalTriangle: function [n][
triangle: new [[1]]
loop 1..dec n 'x [
'triangle ++ @[map couple (last triangle)++[0] [0]++(last triangle) 'x -> x\[0] + x\[1]]
]
return triangle
]
loop pascalTriangle 10 'row [
print pad.center join.with: " " map to [:string] row 'x -> pad.center x 5 60
] |
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 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #F.23 | F# |
// Parse IP addresses: Nigel Galloway. May 29th., 2021
open System.Text.RegularExpressions
type ipv6= Complete |Composite |Compressed |CompressedComposite
let ip4n,ip6i,ip6g,ip6e,ip6l=let n,g="[0-9a-fA-F]{1,4}","(25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?[0-9])" in (
sprintf "^(%s)\.(%s)\.(%s)\.(%s)$" g g g g, sprintf "^(%s):(%s):(%s):(%s):(%s):(%s):(%s):(%s)$" n n n n n n n n,
sprintf "^((%s):)?((%s):)?((%s):)?((%s):)?((%s):)?((%s):)?(^|%s)::(%s|$)(:(%s))?(:(%s))?(:(%s))?(:(%s))?(:(%s))?(:(%s))?$" n n n n n n n n n n n n n n,
sprintf "^(%s):(%s):(%s):(%s):(%s):(%s):(%s)\.(%s)\.(%s)\.(%s)$" n n n n n n g g g g,
sprintf "^((%s):)?((%s):)?((%s):)?((%s):)?(^|%s)::((%s):)?((%s):)?((%s):)?((%s):)?((%s):)?(%s)\.(%s)\.(%s)\.(%s)$" n n n n n n n n n n g g g g)
let mn,mi,mg,me,ml=[2;4;6;8;10;12;13], [14..2..26], [2;4;6;8;9], [11..2..19], [20..5..35]
let fN(n:Match) g=g|>List.filter(fun(g:int)->n.Groups.[g].Length>0)
let fI n (g:Match)=n|>List.fold(fun Σ (n:int)->(Σ<<<16)+((int>>bigint)(sprintf "0x%s" g.Groups.[n].Value)))0I
let rec fG n g=let a="0123456789abcdef" in match bigint.DivRem(n,16I) with (n,r) when n=0I->a.[int r]::g|>Array.ofList|>System.String |(n,r)->fG n (a.[int r]::g)
let fE(m:Match) n g=(fN m n,fN m g)
let fL n (g:Match)=n|>List.fold(fun Σ (n:int)->(Σ<<<8)+int(g.Groups.[n].Value))0
let (|IP4 |_|) n=let g=Regex.Match(n,ip4n) in if g.Success then Some(fL [1..5..16] g) else None
let (|IP6n|_|) i=let g=Regex.Match(i,ip6i) in if g.Success then Some(fI [1..8] g) else None
let (|IP6i|_|) g=let g=Regex.Match(g,ip6g) in if g.Success then let n,l=fE g mn mi in (if n.Length+l.Length<8 then Some(((fI n g)<<<((8-n.Length)*16))+(fI l g)) else None) else None
let (|IP6g|_|) e=let g=Regex.Match(e,ip6e) in if g.Success then Some(((fI [1..6] g)<<<32)+bigint(fL [7..5..22] g)) else None
let (|IP6e|_|) l=let g=Regex.Match(l,ip6l) in if g.Success then let n,l=fE g mg me in (if n.Length+l.Length<6 then Some(((fI n g)<<<((8-n.Length)*16))+((fI l g)<<<32)+bigint(fL ml g)) else None) else None
let (|IP6l|_|) n=match n with IP6n n->Some(Complete,fG n []) |IP6i n->Some(Compressed,fG n []) |IP6g n->Some(Composite,fG n []) |IP6e n->Some(CompressedComposite,fG n []) |_->None
let (|IP4p|_|) n=let g=Regex.Match(n,"^(.+):(\d{1,4})$") in if g.Success then match g.Groups.[1].Value with IP4 n->Some(n,int g.Groups.[2].Value) |_->None else None
let (|IP6p|_|) n=let g=Regex.Match(n,"^\[(.+)\]:(\d{1,4})$") in if g.Success then match g.Groups.[1].Value with IP6l n->Some(n,int g.Groups.[2].Value) |_->None else None
let pIP n=match n with IP6p((t,g),p)->printfn "%s is a %A IPv6 address value 0x%s using port %d" n t g p
|IP4 g->printfn "%s is an IPv4 address value %0x" n g
|IP6l(t,g)->printfn "%s is a %A IPv6 address value 0x%s" n t g
|IP4p(g,p)->printfn "%s is an IPv4 address value %0x using port %d" n g p
|_->printfn "%s not matched" n
["127.0.0.1";"127.0.0.1:80";"2605:2700:0:3::4713:93e3";"::1";"[::1]:80";"2605:2700:0:3::4713:93e3";"[2605:2700:0:3::4713:93e3]:80";
"::ffff:127.0.0.1";"1:2:3:4:5:6:7:8";"1:2:3:4:5:6:7:8:9";"1:2:3:4:5:6:127.0.0.1"]|>List.iter pIP
|
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #Clean | Clean | ::Tree a = Empty | Node a (Tree a) (Tree a)
mapTree :: (a -> b) (Tree a) -> (Tree b)
mapTree f Empty = Empty
mapTree f (Node x l r) = Node (f x) (mapTree f l) (mapTree f r) |
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #Common_Lisp | Common Lisp | (deftype pair (&key (car 't) (cdr 't))
`(cons ,car ,cdr)) |
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #D | D | class ArrayTree(T, uint N) {
T[N] data;
typeof(this) left, right;
this(T initValue) { this.data[] = initValue; }
void tmap(const void delegate(ref typeof(data)) dg) {
dg(this.data);
if (left) left.tmap(dg);
if (right) right.tmap(dg);
}
}
void main() { // Demo code.
import std.stdio;
// Instantiate the template ArrayTree of three doubles.
alias AT3 = ArrayTree!(double, 3);
// Allocate the tree root.
auto root = new AT3(1.00);
// Add some nodes.
root.left = new AT3(1.10);
root.left.left = new AT3(1.11);
root.left.right = new AT3(1.12);
root.right = new AT3(1.20);
root.right.left = new AT3(1.21);
root.right.right = new AT3(1.22);
// Now the tree has seven nodes.
// Show the arrays of the whole tree.
//root.tmap(x => writefln("%(%.2f %)", x));
root.tmap((ref x) => writefln("%(%.2f %)", x));
// Modify the arrays of the whole tree.
//root.tmap((x){ x[] += 10; });
root.tmap((ref x){ x[] += 10; });
// Show the arrays of the whole tree again.
writeln();
//root.tmap(x => writefln("%(%.2f %)", x));
root.tmap((ref x) => writefln("%(%.2f %)", x));
} |
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.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #C | C |
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
char** components;
int counter = 0;
typedef struct elem{
char data[10];
struct elem* left;
struct elem* right;
}node;
typedef node* tree;
int precedenceCheck(char oper1,char oper2){
return (oper1==oper2)? 0:(oper1=='^')? 1:(oper2=='^')? 2:(oper1=='/')? 1:(oper2=='/')? 2:(oper1=='*')? 1:(oper2=='*')? 2:(oper1=='+')? 1:(oper2=='+')? 2:(oper1=='-')? 1:2;
}
int isOperator(char c){
return (c=='+'||c=='-'||c=='*'||c=='/'||c=='^');
}
void inorder(tree t){
if(t!=NULL){
if(t->left!=NULL && isOperator(t->left->data[0])==1 && (precedenceCheck(t->data[0],t->left->data[0])==1 || (precedenceCheck(t->data[0],t->left->data[0])==0 && t->data[0]=='^'))){
printf("(");
inorder(t->left);
printf(")");
}
else
inorder(t->left);
printf(" %s ",t->data);
if(t->right!=NULL && isOperator(t->right->data[0])==1 && (precedenceCheck(t->data[0],t->right->data[0])==1 || (precedenceCheck(t->data[0],t->right->data[0])==0 && t->data[0]!='^'))){
printf("(");
inorder(t->right);
printf(")");
}
else
inorder(t->right);
}
}
char* getNextString(){
if(counter<0){
printf("\nInvalid RPN !");
exit(0);
}
return components[counter--];
}
tree buildTree(char* obj,char* trace){
tree t = (tree)malloc(sizeof(node));
strcpy(t->data,obj);
t->right = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;
t->left = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL;
if(trace!=NULL){
printf("\n");
inorder(t);
}
return t;
}
int checkRPN(){
int i, operSum = 0, numberSum = 0;
if(isOperator(components[counter][0])==0)
return 0;
for(i=0;i<=counter;i++)
(isOperator(components[i][0])==1)?operSum++:numberSum++;
return (numberSum - operSum == 1);
}
void buildStack(char* str){
int i;
char* token;
for(i=0;str[i]!=00;i++)
if(str[i]==' ')
counter++;
components = (char**)malloc((counter + 1)*sizeof(char*));
token = strtok(str," ");
i = 0;
while(token!=NULL){
components[i] = (char*)malloc(strlen(token)*sizeof(char));
strcpy(components[i],token);
token = strtok(NULL," ");
i++;
}
}
int main(int argC,char* argV[]){
int i;
tree t;
if(argC==1)
printf("Usage : %s <RPN expression enclosed by quotes> <optional parameter to trace the build process>",argV[0]);
else{
buildStack(argV[1]);
if(checkRPN()==0){
printf("\nInvalid RPN !");
return 0;
}
t = buildTree(getNextString(),argV[2]);
printf("\nFinal infix expression : ");
inorder(t);
}
return 0;
}
|
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
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #CoffeeScript | CoffeeScript |
partial = (f, g) ->
(s) -> f(g, s)
fs = (f, s) -> (f(a) for a in s)
f1 = (a) -> a * 2
f2 = (a) -> a * a
fsf1 = partial(fs, f1)
fsf2 = partial(fs, f2)
do ->
for seq in [[0..3], [2,4,6,8]]
console.log fsf1 seq
console.log fsf2 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
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Common_Lisp | Common Lisp | (defun fs (f s)
(mapcar f s))
(defun f1 (i)
(* i 2))
(defun f2 (i)
(expt i 2))
(defun partial (func &rest args1)
(lambda (&rest args2)
(apply func (append args1 args2))))
(setf (symbol-function 'fsf1) (partial #'fs #'f1))
(setf (symbol-function 'fsf2) (partial #'fs #'f2))
(dolist (seq '((0 1 2 3) (2 4 6 8)))
(format t
"~%seq: ~A~% fsf1 seq: ~A~% fsf2 seq: ~A"
seq
(fsf1 seq)
(fsf2 seq)))
|
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.
• partition 18 with 2 primes.
• partition 19 with 3 primes.
• partition 20 with 4 primes.
• partition 2017 with 24 primes.
• partition 22699 with 1, 2, 3, and 4 primes.
• partition 40355 with 3 primes.
The output could/should be shown in a format such as:
Partitioned 19 with 3 primes: 3+5+11
Use any spacing that may be appropriate for the display.
You need not validate the input(s).
Use the lowest primes possible; use 18 = 5+13, not 18 = 7+11.
You only need to show one solution.
This task is similar to factoring an integer.
Related tasks
Count in factors
Prime decomposition
Factors of an integer
Sieve of Eratosthenes
Primality by trial division
Factors of a Mersenne number
Factors of a Mersenne number
Sequence of primes by trial division
| #Kotlin | Kotlin | // version 1.1.2
// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning
import kotlin.coroutines.experimental.*
val primes = generatePrimes().take(50_000).toList() // generate first 50,000 say
var foundCombo = false
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun generatePrimes() =
buildSequence {
yield(2)
var p = 3
while (p <= Int.MAX_VALUE) {
if (isPrime(p)) yield(p)
p += 2
}
}
fun findCombo(k: Int, x: Int, m: Int, n: Int, combo: IntArray) {
if (k >= m) {
if (combo.sumBy { primes[it] } == x) {
val s = if (m > 1) "s" else " "
print("Partitioned ${"%5d".format(x)} with ${"%2d".format(m)} prime$s: ")
for (i in 0 until m) {
print(primes[combo[i]])
if (i < m - 1) print("+") else println()
}
foundCombo = true
}
}
else {
for (j in 0 until n) {
if (k == 0 || j > combo[k - 1]) {
combo[k] = j
if (!foundCombo) findCombo(k + 1, x, m, n, combo)
}
}
}
}
fun partition(x: Int, m: Int) {
require(x >= 2 && m >= 1 && m < x)
val filteredPrimes = primes.filter { it <= x }
val n = filteredPrimes.size
if (n < m) throw IllegalArgumentException("Not enough primes")
val combo = IntArray(m)
foundCombo = false
findCombo(0, x, m, n, combo)
if (!foundCombo) {
val s = if (m > 1) "s" else " "
println("Partitioned ${"%5d".format(x)} with ${"%2d".format(m)} prime$s: (not possible)")
}
}
fun main(args: Array<String>) {
val a = arrayOf(
99809 to 1,
18 to 2,
19 to 3,
20 to 4,
2017 to 24,
22699 to 1,
22699 to 2,
22699 to 3,
22699 to 4,
40355 to 3
)
for (p in a) partition(p.first, p.second)
} |
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Phix | Phix | with javascript_semantics
function partDiffDiff(integer n)
return (n+1)/(1+and_bits(n,1))
end function
sequence pd = {1}
function partDiff(integer n)
while n>length(pd) do
pd &= pd[$] + partDiffDiff(length(pd))
end while
return pd[max(1,n)]
end function
include mpfr.e
sequence pn = {mpz_init(1)}
function partitionsP(integer n)
mpz res = mpz_init(1)
while n>length(pn) do
integer nn = length(pn)+1
mpz psum = mpz_init(0)
for i=1 to nn do
integer pd = partDiff(i)
if pd>nn then exit end if
integer sgn = iff(remainder(i-1,4)<2 ? 1 : -1)
mpz pnmpd = pn[max(1,nn-pd)]
if sgn=-1 then
mpz_sub(psum,psum,pnmpd)
else
mpz_add(psum,psum,pnmpd)
end if
end for
pn = append(pn,psum)
end while
return pn[max(1,n)]
end function
atom t0 = time()
integer n=6666
printf(1,"p(%d) = %s (%s)\n",{n,mpz_get_str(partitionsP(n)),elapsed(time()-t0)})
|
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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | b+c==a
d+e==b
e+f==c
g+h==d
h+i==e
i+j==f
l+X==g
l+Y==h
n+Y==i
n+Z==j
X+Z==Y |
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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #MiniZinc | MiniZinc |
%Pascal's Triangle Puzzle. Nigel Galloway, February 17th., 2020
int: N11=151; constraint N11=N21+N22;
var 1..N11: N21=N31+N32;
var 1..N11: N22=N32+N33;
int: N31=40; constraint N31=N41+N42;
var 1..N11: N32=N42+N43;
var 1..N11: N33=N43+N44;
var 1..N11: N41=X+11;
var 1..N11: N42=Y+11;
var 1..N11: N43=Y+4;
var 1..N11: N44=Z+4;
var 1..N11: X;
var 1..N11: Y=X+Z;
var 1..N11: 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 on an n-by-n square grid, (the board), so that no queen attacks another of a different colour.
Task
Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).
Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
Display here results for the m=4, n=5 case.
References
Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
A250000 OEIS
| #Scheme | Scheme | ;;;
;;; Solutions to the Peaceful Chess Queen Armies puzzle, in R7RS
;;; Scheme (using also SRFI-132).
;;;
;;; https://rosettacode.org/wiki/Peaceful_chess_queen_armies
;;;
(cond-expand
(r7rs)
(chicken (import (r7rs))))
(import (scheme process-context))
(import (only (srfi 132) list-sort))
(define-record-type <&fail>
(make-the-one-unique-&fail-that-you-must-not-make-twice)
do-not-use-this:&fail?)
(define &fail
(make-the-one-unique-&fail-that-you-must-not-make-twice))
(define (failure? f)
(eq? f &fail))
(define (success? f)
(not (failure? f)))
(define *suspend*
(make-parameter (lambda (x) x)))
(define (suspend v)
((*suspend*) v))
(define (fail-forever)
(let loop ()
(suspend &fail)
(loop)))
(define (make-generator-procedure thunk)
;;
;; Make a suspendable procedure that takes no arguments. It is a
;; simple generator of values. (One can elaborate on this to have
;; the procedure accept an argument upon resumption, like an Icon
;; co-expression.)
;;
(define (next-run return)
(define (my-suspend v)
(set! return
(call/cc
(lambda (resumption-point)
(set! next-run resumption-point)
(return v)))))
(parameterize ((*suspend* my-suspend))
(suspend (thunk))
(fail-forever)))
(lambda ()
(call/cc next-run)))
(define BLACK 'B)
(define WHITE 'W)
(define (flip-color c)
(if (eq? c BLACK) WHITE BLACK))
(define-record-type <queen>
(make-queen color rank file)
queen?
(color queen-color)
(rank queen-rank)
(file queen-file))
(define (serialize-queen queen)
(string-append (if (eq? (queen-color queen) BLACK) "B" "W")
"(" (number->string (queen-rank queen))
"," (number->string (queen-file queen)) ")"))
(define (serialize-queens queens)
(apply string-append
(list-sort string<? (map serialize-queen queens))))
(define (queens->string n queens)
(define board
(let ((board (make-vector (* n n) #f)))
(do ((q queens (cdr q)))
((null? q))
(let* ((color (queen-color (car q)))
(i (queen-rank (car q)))
(j (queen-file (car q))))
(vector-set! board (ij->index n i j) color)))
board))
(define rule
(let ((str "+"))
(do ((j 1 (+ j 1)))
((= j (+ n 1)))
(set! str (string-append str "----+")))
str))
(define str "")
(when (< 0 n)
(set! str rule)
(do ((i n (- i 1)))
((= i 0))
(set! str (string-append str "\n"))
(do ((j 1 (+ j 1)))
((= j (+ n 1)))
(let* ((color (vector-ref board (ij->index n i j)))
(representation
(cond ((eq? color #f) " ")
((eq? color BLACK) " B ")
((eq? color WHITE) " W ")
(else " ?? "))))
(set! str (string-append str "|" representation))))
(set! str (string-append str "|\n" rule))))
str)
(define (queen-fits-in? queen other-queens)
(or (null? other-queens)
(let ((other (car other-queens)))
(let ((colorq (queen-color queen))
(rankq (queen-rank queen))
(fileq (queen-file queen))
(coloro (queen-color other))
(ranko (queen-rank other))
(fileo (queen-file other)))
(if (eq? colorq coloro)
(and (or (not (= rankq ranko))
(not (= fileq fileo)))
(queen-fits-in? queen (cdr other-queens)))
(and (not (= rankq ranko))
(not (= fileq fileo))
(not (= (+ rankq fileq) (+ ranko fileo)))
(not (= (- rankq fileq) (- ranko fileo)))
(queen-fits-in? queen (cdr other-queens))))))))
(define (latest-queen-fits-in? queens)
(or (null? (cdr queens))
(queen-fits-in? (car queens) (cdr queens))))
(define (make-peaceful-queens-generator m n)
(make-generator-procedure
(lambda ()
(define solutions '())
(let loop ((queens (list (make-queen BLACK 1 1)))
(num-queens 1))
(define (add-another-queen)
(let ((color (flip-color (queen-color (car queens)))))
(loop (cons (make-queen color 1 1) queens)
(+ num-queens 1))))
(define (move-a-queen)
(let drop-one ((queens queens)
(num-queens num-queens))
(if (zero? num-queens)
(loop '() 0)
(let* ((latest (car queens))
(color (queen-color latest))
(rank (queen-rank latest))
(file (queen-file latest)))
(if (and (= rank n) (= file n))
(drop-one (cdr queens) (- num-queens 1))
(let-values (((rank^ file^)
(advance-ij n rank file)))
(loop (cons (make-queen color rank^ file^)
(cdr queens))
num-queens)))))))
(cond ((zero? num-queens)
;; There are no more solutions.
&fail)
((latest-queen-fits-in? queens)
(if (= num-queens (* 2 m))
(let ((str (serialize-queens queens)))
;; The current "queens" is a solution.
(unless (member str solutions)
;; The current "queens" is a *new* solution.
(set! solutions (cons str solutions))
(suspend queens))
(move-a-queen))
(add-another-queen)))
(else
(move-a-queen)))))))
(define (ij->index n i j)
(let ((i1 (- i 1))
(j1 (- j 1)))
(+ i1 (* n j1))))
(define (index->ij n index)
(let-values (((q r) (floor/ index n)))
(values (+ r 1) (+ q 1))))
(define (advance-ij n i j)
(index->ij n (+ (ij->index n i j) 1)))
(define args (command-line))
(unless (or (= (length args) 3)
(= (length args) 4))
(display "Usage: ")
(display (list-ref args 0))
(display " M N [MAX_SOLUTIONS]")
(newline)
(exit 1))
(define m (string->number (list-ref args 1)))
(define n (string->number (list-ref args 2)))
(define max-solutions
(if (= (length args) 4)
(string->number (list-ref args 3))
+inf.0))
(define generate-peaceful-queens
(make-peaceful-queens-generator m n))
(let loop ((next-solution-number 1))
(when (<= next-solution-number max-solutions)
(let ((solution (generate-peaceful-queens)))
(when (success? solution)
(display "Solution ")
(display next-solution-number)
(newline)
(display (queens->string n solution))
(newline)
(newline)
(loop (+ next-solution-number 1)))))) |
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 character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #J | J | thru=: <. + i.@(+*)@-~
chr=: a.&i.
lower=: 'a' thru&.chr 'z'
upper=: 'A' thru&.chr 'Z'
digit=: '0' thru&.chr '9'
other=: ('!' thru&.chr '~')-.lower,upper,digit,'`\'
all=: lower,upper,digit,other
pwgen =:verb define"0 :: pwhelp
NB. pick one of each, remainder from all, then shuffle
(?~y) { (?@# { ])every lower;upper;digit;other;(y-4)#<all
:
pwgen x#y
)
pwhelp =:echo bind (noun define)
[x] pwgen y - generates passwords of length y
optional x says how many to generate (if you want more than 1)
y must be at least 4 because
passwords must contain four different kinds of characters.
) |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Smalltalk | Smalltalk | (1 to: 4) permutationsDo: [ :x |
Transcript show: x printString; cr ]. |
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 player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins.
Example
One player might choose the sequence HHT and the other THT.
Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence.
Task
Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent.
Who chooses and shows their sequence of three should be chosen randomly.
If going first, the computer should randomly choose its sequence of three.
If going second, the computer should automatically play the optimum sequence.
Successive coin tosses should be shown.
Show output of a game where the computer chooses first and a game where the user goes first here on this page.
See also
The Penney Ante Part 1 (Video).
The Penney Ante Part 2 (Video).
| #REXX | REXX | /*REXX program plays/simulates Penney's Game, a two─player coin toss sequence game. */
__= copies('─', 9) /*literal for eye─catching fence. */
signal on halt /*a clean way out if CLBF quits. */
parse arg # seed . /*obtain optional arguments from the CL*/
if #=='' | #=="," then #= 3 /*Not specified? Then use the default.*/
if datatype(seed,'W') then call random ,,seed /*use seed for RANDOM #s repeatability.*/
wins=0; do games=1 /*simulate a number of Penney's games. */
call game /*simulate a single inning of a game. */
end /*games*/ /*keep at it until QUIT or halt. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
halt: say; say __ "Penney's Game was halted."; say; exit 13
r: arg ,$; do arg(1); $=$ || random(100, 9991) // 2; end; return $
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
game: @.=; tosses=@. /*the coin toss sequence so far. */
toss1= r(1) /*result: 0=computer, 1=CBLF.*/
if \toss1 then call randComp /*maybe let the computer go first*/
if toss1 then say __ "You win the first toss, so you pick your sequence first."
else say __ "The computer won first toss, the pick was: " @.comp
call prompter /*get the human's guess from C.L.*/
call randComp /*get computer's guess if needed.*/
/*CBLF: carbon-based life form. */
say __ " your pick:" @.CBLF /*echo human's pick to terminal. */
say __ "computer's pick:" @.comp /* " comp.'s " " " */
say /* [↓] flip the coin 'til a win.*/
do flips=1 until pos(@.CBLF, tosses)\==0 | pos(@.comp, tosses)\==0
tosses= tosses || translate( r(1), 'HT', 10)
end /*flips*/ /* [↑] this is a flipping coin,*/
/* [↓] series of tosses*/
say __ "The tossed coin series was: " tosses
say
@@@="won this toss with " flips ' coin tosses.'
if pos(@.CBLF,tosses)\==0 then do; say __ "You" @@@; wins=wins+1; end
else say __ "The computer" @@@
_=wins; if _==0 then _='no'
say __ "You've won" _ "game"s(wins) 'out of ' games"."
say; say copies('╩╦', 79 % 2)'╩'; say
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
prompter: oops= __ 'Oops! '; a= /*define some handy REXX literals*/
@a_z= 'ABCDEFG-IJKLMNOPQRS+UVWXYZ' /*the extraneous alphabetic chars*/
p=__ 'Pick a sequence of' # "coin tosses of H or T (Heads or Tails) or Quit:"
do until ok; say; say p; pull a /*uppercase the answer. */
if abbrev('QUIT', a, 1) then exit 1 /*the human wants to quit. */
a= space( translate(a,,@a_z',./\;:_'), 0) /*elide extraneous characters. */
b= translate(a, 10, 'HT'); L= length(a) /*translate ───► bin; get length.*/
ok= 0 /*the response is OK (so far). */
select /*verify the user response. */
when \datatype(b, 'B') then say oops "Illegal response."
when \datatype(a, 'M') then say oops "Illegal characters in response."
when L==0 then say oops "No choice was given."
when L<# then say oops "Not enough coin choices."
when L># then say oops "Too many coin choices."
when a==@.comp then say oops "You can't choose the computer's" ,
"choice: " @.comp
otherwise ok= 1
end /*select*/
end /*until ok*/
@.CBLF= a; @.CBLF!= b /*we have the human's guess now. */
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
randComp: if @.comp\=='' then return /*the computer already has a pick*/
_= @.CBLF! /* [↓] use best-choice algorithm.*/
if _\=='' then g= left((\substr(_, min(2, #), 1))left(_, 1)substr(_, 3), #)
do until g\==@.CBLF!; g= r(#); end /*otherwise, generate a choice. */
@.comp= translate(g, 'HT', 10)
return |
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 problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.
This task's purpose is to show how your language deals with such classes of problems.
A sequence that seems to converge to a wrong limit.
Consider the sequence:
v1 = 2
v2 = -4
vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2)
As n grows larger, the series should converge to 6 but small amounts of error will cause it to approach 100.
Task 1
Display the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least 16 decimal places.
n = 3 18.5
n = 4 9.378378
n = 5 7.801153
n = 6 7.154414
n = 7 6.806785
n = 8 6.5926328
n = 20 6.0435521101892689
n = 30 6.006786093031205758530554
n = 50 6.0001758466271871889456140207471954695237
n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266
Task 2
The Chaotic Bank Society is offering a new investment account to their customers.
You first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.
After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed.
So ...
after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.
after 2 years your balance will be doubled and $1 removed.
after 3 years your balance will be tripled and $1 removed.
...
after 10 years, multiplied by 10 and $1 removed, and so on.
What will your balance be after 25 years?
Starting balance: $e-1
Balance = (Balance * year) - 1 for 25 years
Balance after 25 years: $0.0399387296732302
Task 3, extra credit
Siegfried Rump's example. Consider the following function, designed by Siegfried Rump in 1988.
f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b)
compute f(a,b) where a=77617.0 and b=33096.0
f(77617.0, 33096.0) = -0.827396059946821
Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.
See also;
Floating-Point Arithmetic Section 1.3.2 Difficult problems.
| #Python | Python | from fractions import Fraction
def muller_seq(n:int) -> float:
seq = [Fraction(0), Fraction(2), Fraction(-4)]
for i in range(3, n+1):
next_value = (111 - 1130/seq[i-1]
+ 3000/(seq[i-1]*seq[i-2]))
seq.append(next_value)
return float(seq[n])
for n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100]:
print("{:4d} -> {}".format(n, muller_seq(n))) |
http://rosettacode.org/wiki/Parallel_brute_force | Parallel brute force | Task
Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes:
1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash.
Related task: SHA-256
| #BaCon | BaCon | PRAGMA INCLUDE <openssl/sha.h>
PRAGMA LDFLAGS -lcrypto
OPTION MEMTYPE unsigned char
LOCAL buffer[32], passwd[5] TYPE unsigned char
LOCAL result TYPE unsigned char*
LOCAL a,b,c,d,e TYPE NUMBER
DATA "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b", "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f", "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"
WHILE TRUE
READ secret$
IF NOT(LEN(secret$)) THEN BREAK
FOR i = 0 TO 31
buffer[i] = DEC(MID$(secret$, i*2+1, 2))
NEXT
FOR a = 97 TO 122
FOR b = 97 TO 122
FOR c = 97 TO 122
FOR d = 97 TO 122
FOR e = 97 TO 122
passwd[0] = a
passwd[1] = b
passwd[2] = c
passwd[3] = d
passwd[4] = e
result = SHA256(passwd, 5, 0)
FOR i = 0 TO SHA256_DIGEST_LENGTH-1
IF PEEK(result+i) != buffer[i] THEN BREAK
NEXT
IF i = SHA256_DIGEST_LENGTH THEN
PRINT a,b,c,d,e,secret$ FORMAT "%c%c%c%c%c:%s\n"
BREAK 5
END IF
NEXT
NEXT
NEXT
NEXT
NEXT
WEND |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest minimal prime factor
(that is, the one that contains relatively large factors).
To speed up the search, the factorization should be done
in parallel using separate threads or processes,
to take advantage of multi-core CPUs.
Show how this can be formulated in your language.
Parallelize the factorization of those numbers,
then search the returned list of numbers and factors
for the largest minimal factor,
and return that number and its prime factors.
For the prime number decomposition
you may use the solution of the Prime decomposition task.
| #C | C | #include <stdio.h>
#include <omp.h>
int main()
{
int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519};
int largest, largest_factor = 0;
omp_set_num_threads(4);
/* "omp parallel for" turns the for loop multithreaded by making each thread
* iterating only a part of the loop variable, in this case i; variables declared
* as "shared" will be implicitly locked on access
*/
#pragma omp parallel for shared(largest_factor, largest)
for (int i = 0; i < 7; i++) {
int p, n = data[i];
for (p = 3; p * p <= n && n % p; p += 2);
if (p * p > n) p = n;
if (p > largest_factor) {
largest_factor = p;
largest = n;
printf("thread %d: found larger: %d of %d\n",
omp_get_thread_num(), p, n);
} else {
printf("thread %d: not larger: %d of %d\n",
omp_get_thread_num(), p, n);
}
}
printf("Largest factor: %d of %d\n", largest_factor, largest);
return 0;
} |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #ALGOL_68 | ALGOL 68 | # RPN Expression evaluator - handles numbers and + - * / ^ #
# the right-hand operand for ^ is converted to an integer #
# expression terminator #
CHAR end of expression character = REPR 12;
# evaluates the specified rpn expression #
PROC evaluate = ( STRING rpn expression )VOID:
BEGIN
[ 256 ]REAL stack;
INT stack pos := 0;
# pops an element off the stack #
PROC pop = REAL:
BEGIN
stack pos -:= 1;
stack[ stack pos + 1 ]
END; # pop #
INT rpn pos := LWB rpn expression;
# evaluate tokens from the expression until we get the end of expression #
WHILE
# get the next token from the string #
STRING token type;
REAL value;
# skip spaces #
WHILE rpn expression[ rpn pos ] = " "
DO
rpn pos +:= 1
OD;
# handle the token #
IF rpn expression[ rpn pos ] = end of expression character
THEN
# no more tokens #
FALSE
ELSE
# have a token #
IF rpn expression[ rpn pos ] >= "0"
AND rpn expression[ rpn pos ] <= "9"
THEN
# have a number #
# find where the nmumber is in the expression #
INT number start = rpn pos;
WHILE ( rpn expression[ rpn pos ] >= "0"
AND rpn expression[ rpn pos ] <= "9"
)
OR rpn expression[ rpn pos ] = "."
DO
rpn pos +:= 1
OD;
# read the number from the expression #
FILE number f;
associate( number f
, LOC STRING := rpn expression[ number start : rpn pos - 1 ]
);
get( number f, ( value ) );
close( number f );
token type := "number"
ELSE
# must be an operator #
CHAR op = rpn expression[ rpn pos ];
rpn pos +:= 1;
REAL arg1 := pop;
REAL arg2 := pop;
token type := op;
value := IF op = "+"
THEN
# add the top two stack elements #
arg1 + arg2
ELIF op = "-"
THEN
# subtract the top two stack elements #
arg2 - arg1
ELIF op = "*"
THEN
# multiply the top two stack elements #
arg2 * arg1
ELIF op = "/"
THEN
# divide the top two stack elements #
arg2 / arg1
ELIF op = "^"
THEN
# raise op2 to the power of op1 #
arg2 ^ ENTIER arg1
ELSE
# unknown operator #
print( ( "Unknown operator: """ + op + """", newline ) );
0
FI
FI;
TRUE
FI
DO
# push the new value on the stack and show the new stack #
stack[ stack pos +:= 1 ] := value;
print( ( ( token type + " " )[ 1 : 8 ] ) );
FOR element FROM LWB stack TO stack pos
DO
print( ( " ", fixed( stack[ element ], 8, 4 ) ) )
OD;
print( ( newline ) )
OD;
print( ( "Result is: ", fixed( stack[ stack pos ], 12, 8 ), newline ) )
END; # evaluate #
main: (
# get the RPN expresson from the user #
STRING rpn expression;
print( ( "Enter expression: " ) );
read( ( rpn expression, newline ) );
# add a space to terminate the final token and an expression terminator #
rpn expression +:= " " + end of expression character;
# execute the expression #
evaluate( rpn expression )
) |
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
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main() {
string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
Console.WriteLine(infix.ToPostfix());
}
}
public static class ShuntingYard
{
private static readonly Dictionary<string, (string symbol, int precedence, bool rightAssociative)> operators
= new (string symbol, int precedence, bool rightAssociative) [] {
("^", 4, true),
("*", 3, false),
("/", 3, false),
("+", 2, false),
("-", 2, false)
}.ToDictionary(op => op.symbol);
public static string ToPostfix(this string infix) {
string[] tokens = infix.Split(' ');
var stack = new Stack<string>();
var output = new List<string>();
foreach (string token in tokens) {
if (int.TryParse(token, out _)) {
output.Add(token);
Print(token);
} else if (operators.TryGetValue(token, out var op1)) {
while (stack.Count > 0 && operators.TryGetValue(stack.Peek(), out var op2)) {
int c = op1.precedence.CompareTo(op2.precedence);
if (c < 0 || !op1.rightAssociative && c <= 0) {
output.Add(stack.Pop());
} else {
break;
}
}
stack.Push(token);
Print(token);
} else if (token == "(") {
stack.Push(token);
Print(token);
} else if (token == ")") {
string top = "";
while (stack.Count > 0 && (top = stack.Pop()) != "(") {
output.Add(top);
}
if (top != "(") throw new ArgumentException("No matching left parenthesis.");
Print(token);
}
}
while (stack.Count > 0) {
var top = stack.Pop();
if (!operators.ContainsKey(top)) throw new ArgumentException("No matching right parenthesis.");
output.Add(top);
}
Print("pop");
return string.Join(" ", output);
//Yikes!
void Print(string action) => Console.WriteLine($"{action + ":",-4} {$"stack[ {string.Join(" ", stack.Reverse())} ]",-18} {$"out[ {string.Join(" ", output)} ]"}");
//A little more readable?
void Print(string action) => Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {string.Join(" ", stack.Reverse())} ]", $"out[ {string.Join(" ", output)} ]");
}
} |
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:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #C | C |
#include <stdio.h>
#include <stdlib.h>
void pascal_low(int **mat, int n) {
int i, j;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
if (i < j)
mat[i][j] = 0;
else if (i == j || j == 0)
mat[i][j] = 1;
else
mat[i][j] = mat[i - 1][j - 1] + mat[i - 1][j];
}
void pascal_upp(int **mat, int n) {
int i, j;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
if (i > j)
mat[i][j] = 0;
else if (i == j || i == 0)
mat[i][j] = 1;
else
mat[i][j] = mat[i - 1][j - 1] + mat[i][j - 1];
}
void pascal_sym(int **mat, int n) {
int i, j;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
if (i == 0 || j == 0)
mat[i][j] = 1;
else
mat[i][j] = mat[i - 1][j] + mat[i][j - 1];
}
int main(int argc, char * argv[]) {
int **mat;
int i, j, n;
/* Input size of the matrix */
n = 5;
/* Matrix allocation */
mat = calloc(n, sizeof(int *));
for (i = 0; i < n; ++i)
mat[i] = calloc(n, sizeof(int));
/* Matrix computation */
printf("=== Pascal upper matrix ===\n");
pascal_upp(mat, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');
printf("=== Pascal lower matrix ===\n");
pascal_low(mat, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');
printf("=== Pascal symmetric matrix ===\n");
pascal_sym(mat, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');
return 0;
}
|
http://rosettacode.org/wiki/Parameterized_SQL_statement | Parameterized SQL statement | SQL injection
Using a SQL update statement like this one (spacing is optional):
UPDATE players
SET name = 'Smith, Steve', score = 42, active = TRUE
WHERE jerseyNum = 99
Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either. | #Arturo | Arturo | ; Helper functions
createTable: function [][
query db {!sql DROP TABLE IF EXISTS users}
query db {!sql
CREATE TABLE users (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
email TEXT NOT NULL,
age INTEGER
)
}
]
addUser: function [name, email, age][
query.id db .with:@[name,email,age] {!sql
INSERT INTO users (username, email, age)
VALUES (?,?,?)
}
]
findUser: function [name][
query db .with:@[name] ~{!sql
SELECT *
FROM users
WHERE username=?
}
]
db: open.sqlite "users.db"
createTable
print ["added user with id:" addUser "JohnDoe" "jodoe@gmail.com" 35]
print ["added user with id:" addUser "JaneDoe" "jadoe@gmail.com" 14]
print ["getting user with name: JohnDoe =>" findUser "JohnDoe"]
close db |
http://rosettacode.org/wiki/Parameterized_SQL_statement | Parameterized SQL statement | SQL injection
Using a SQL update statement like this one (spacing is optional):
UPDATE players
SET name = 'Smith, Steve', score = 42, active = TRUE
WHERE jerseyNum = 99
Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either. | #C | C | gcc example.c -lsqlite3
|
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 elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #AutoHotkey | AutoHotkey | n := 8, p0 := "1" ; 1+n rows of Pascal's triangle
Loop %n% {
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1
Loop Parse, %q%, %A_Space%
If (A_Index > 1)
%p% .= " " v+A_LoopField, v := A_LoopField
%p% .= " 1"
}
; Triangular Formatted output
VarSetCapacity(tabs,n,Asc("`t"))
t .= tabs "`t1"
Loop %n% {
t .= "`n" SubStr(tabs,A_Index)
Loop Parse, p%A_Index%, %A_Space%
t .= A_LoopField "`t`t"
}
Gui Add, Text,, %t% ; Show result in a GUI
Gui Show
Return
GuiClose:
ExitApp |
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 address, with a specified port (80)
2605:2700:0:3::4713:93e3
Rosetta Code's primary server's public IPv6 address
[2605:2700:0:3::4713:93e3]:80
Rosetta Code's primary server's public IPv6 address, with a specified port (80)
Task
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.
Example
127.0.0.1 has the address number 7F000001 (2130706433 decimal)
in the ipv4 address space.
::ffff:127.0.0.1 represents the same address in the ipv6 address space where it has the
address number FFFF7F000001 (281472812449793 decimal).
::1 has address number 1 and serves the same purpose in the ipv6 address
space that 127.0.0.1 serves in the ipv4 address space.
| #Go | Go | package main
import (
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"text/tabwriter"
)
// parseIPPort parses an IP with an optional port, returning an IP and a port (or nil
// if no port was present in the given address).
func parseIPPort(address string) (net.IP, *uint64, error) {
ip := net.ParseIP(address)
if ip != nil {
return ip, nil, nil
}
host, portStr, err := net.SplitHostPort(address)
if err != nil {
return nil, nil, fmt.Errorf("splithostport failed: %w", err)
}
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse port: %w", err)
}
ip = net.ParseIP(host)
if ip == nil {
return nil, nil, fmt.Errorf("failed to parse ip address")
}
return ip, &port, nil
}
func ipVersion(ip net.IP) int {
if ip.To4() == nil {
return 6
}
return 4
}
func main() {
testCases := []string{
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:443",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80",
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
writeTSV := func(w io.Writer, args ...interface{}) {
fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...)
fmt.Fprintf(w, "\n")
}
writeTSV(w, "Input", "Address", "Space", "Port")
for _, addr := range testCases {
ip, port, err := parseIPPort(addr)
if err != nil {
panic(err)
}
portStr := "n/a"
if port != nil {
portStr = fmt.Sprint(*port)
}
ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip))
writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)
}
w.Flush()
}
|
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #Dart | Dart | class TreeNode<T> {
T value;
TreeNode<T> left;
TreeNode<T> right;
TreeNode(this.value);
TreeNode map(T f(T t)) {
var node = new TreeNode(f(value));
if(left != null) {
node.left = left.map(f);
}
if(right != null) {
node.right = right.map(f);
}
return node;
}
void forEach(void f(T t)) {
f(value);
if(left != null) {
left.forEach(f);
}
if(right != null) {
right.forEach(f);
}
}
}
void main() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(4);
print('first tree');
root.forEach(print);
var newRoot = root.map((t) => t * 222);
print('second tree');
newRoot.forEach(print);
} |
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, say, a map-function that operates on every element of the tree.
This language feature only applies to statically-typed languages.
| #E | E | interface TreeAny guards TreeStamp {}
def Tree {
to get(Value) {
def Tree1 {
to coerce(specimen, ejector) {
def tree := TreeAny.coerce(specimen, ejector)
if (tree.valueType() != Value) {
throw.eject(ejector, "Tree value type mismatch")
}
return tree
}
}
return Tree1
}
}
def makeTree(T, var value :T, left :nullOk[Tree[T]], right :nullOk[Tree[T]]) {
def tree implements TreeStamp {
to valueType() { return T }
to map(f) {
value := f(value) # the declaration of value causes this to be checked
if (left != null) {
left.map(f)
}
if (right != null) {
right.map(f)
}
}
}
return tree
} |
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.
Assume an input of a correct, space separated, string of tokens
Generate a space separated output string representing the same expression in infix notation
Show how the major datastructure of your algorithm changes with each new token parsed.
Test with the following input RPN strings then print and display the output here.
RPN input
sample output
3 4 2 * 1 5 - 2 3 ^ ^ / +
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
1 2 + 3 4 + ^ 5 6 + ^
( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
Operator precedence and operator associativity is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Postfix to infix from the RubyQuiz site.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace PostfixToInfix
{
class Program
{
class Operator
{
public Operator(char t, int p, bool i = false)
{
Token = t;
Precedence = p;
IsRightAssociative = i;
}
public char Token { get; private set; }
public int Precedence { get; private set; }
public bool IsRightAssociative { get; private set; }
}
static IReadOnlyDictionary<char, Operator> operators = new Dictionary<char, Operator>
{
{ '+', new Operator('+', 2) },
{ '-', new Operator('-', 2) },
{ '/', new Operator('/', 3) },
{ '*', new Operator('*', 3) },
{ '^', new Operator('^', 4, true) }
};
class Expression
{
public String ex;
public Operator op;
public Expression(String e)
{
ex = e;
}
public Expression(String e1, String e2, Operator o)
{
ex = String.Format("{0} {1} {2}", e1, o.Token, e2);
op = o;
}
}
static String PostfixToInfix(String postfix)
{
var stack = new Stack<Expression>();
foreach (var token in Regex.Split(postfix, @"\s+"))
{
char c = token[0];
var op = operators.FirstOrDefault(kv => kv.Key == c).Value;
if (op != null && token.Length == 1)
{
Expression rhs = stack.Pop();
Expression lhs = stack.Pop();
int opPrec = op.Precedence;
int lhsPrec = lhs.op != null ? lhs.op.Precedence : int.MaxValue;
int rhsPrec = rhs.op != null ? rhs.op.Precedence : int.MaxValue;
if ((lhsPrec < opPrec || (lhsPrec == opPrec && c == '^')))
lhs.ex = '(' + lhs.ex + ')';
if ((rhsPrec < opPrec || (rhsPrec == opPrec && c != '^')))
rhs.ex = '(' + rhs.ex + ')';
stack.Push(new Expression(lhs.ex, rhs.ex, op));
}
else
{
stack.Push(new Expression(token));
}
// print intermediate result
Console.WriteLine("{0} -> [{1}]", token,
string.Join(", ", stack.Reverse().Select(e => e.ex)));
}
return stack.Peek().ex;
}
static void Main(string[] args)
{
string[] inputs = { "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^" };
foreach (var e in inputs)
{
Console.WriteLine("Postfix : {0}", e);
Console.WriteLine("Infix : {0}", PostfixToInfix(e));
Console.WriteLine(); ;
}
Console.ReadLine();
}
}
} |
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
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #D | D | import std.stdio, std.algorithm, std.traits;
auto fs(alias f)(in int[] s) pure nothrow
if (isCallable!f && ParameterTypeTuple!f.length == 1) {
return s.map!f;
}
int f1(in int x) pure nothrow { return x * 2; }
int f2(in int x) pure nothrow { return x ^^ 2; }
alias fsf1 = fs!f1;
alias fsf2 = fs!f2;
void main() {
foreach (const d; [[0, 1, 2, 3], [2, 4, 6, 8]]) {
d.fsf1.writeln;
d.fsf2.writeln;
}
} |
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
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #E | E | def pa(f, args1) {
return def partial {
match [`run`, args2] {
E.call(f, "run", args1 + args2)
}
}
}
def fs(f, s) {
var r := []
for n in s {
r with= f(n)
}
return r
}
def f1(n) { return n * 2 }
def f2(n) { return n ** 2 }
def fsf1 := pa(fs, [f1])
def fsf2 := pa(fs, [f2])
for s in [0..3, [2, 4, 6, 8]] {
for f in [fsf1, fsf2] {
println(f(s))
}
} |
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.
• partition 18 with 2 primes.
• partition 19 with 3 primes.
• partition 20 with 4 primes.
• partition 2017 with 24 primes.
• partition 22699 with 1, 2, 3, and 4 primes.
• partition 40355 with 3 primes.
The output could/should be shown in a format such as:
Partitioned 19 with 3 primes: 3+5+11
Use any spacing that may be appropriate for the display.
You need not validate the input(s).
Use the lowest primes possible; use 18 = 5+13, not 18 = 7+11.
You only need to show one solution.
This task is similar to factoring an integer.
Related tasks
Count in factors
Prime decomposition
Factors of an integer
Sieve of Eratosthenes
Primality by trial division
Factors of a Mersenne number
Factors of a Mersenne number
Sequence of primes by trial division
| #Lingo | Lingo | ----------------------------------------
-- returns a sorted list of the <cnt> smallest unique primes that add up to <n>,
-- or FALSE if there is no such partition of primes for <n>
----------------------------------------
on getPrimePartition (n, cnt, primes, ptr, res)
if voidP(primes) then
primes = _global.sieve.getPrimesInRange(2, n)
ptr = 1
res = []
end if
if cnt=1 then
if primes.getPos(n)>=ptr then
res.addAt(1, n)
if res.count=cnt+ptr-1 then
return res
end if
return TRUE
end if
else
repeat with i = ptr to primes.count
p = primes[i]
ok = getPrimePartition(n-p, cnt-1, primes, i+1, res)
if ok then
res.addAt(1, p)
if res.count=cnt+ptr-1 then
return res
end if
return TRUE
end if
end repeat
end if
return FALSE
end
----------------------------------------
-- gets partition, prints formatted result
----------------------------------------
on showPrimePartition (n, cnt)
res = getPrimePartition(n, cnt)
if res=FALSE then res = "not prossible"
else res = implode("+", res)
put "Partitioned "&n&" with "&cnt&" primes: " & res
end
----------------------------------------
-- implodes list into string
----------------------------------------
on implode (delim, tList)
str = ""
repeat with i=1 to tList.count
put tList[i]&delim after str
end repeat
delete char (str.length+1-delim.length) to str.length of str
return str
end |
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.
• partition 18 with 2 primes.
• partition 19 with 3 primes.
• partition 20 with 4 primes.
• partition 2017 with 24 primes.
• partition 22699 with 1, 2, 3, and 4 primes.
• partition 40355 with 3 primes.
The output could/should be shown in a format such as:
Partitioned 19 with 3 primes: 3+5+11
Use any spacing that may be appropriate for the display.
You need not validate the input(s).
Use the lowest primes possible; use 18 = 5+13, not 18 = 7+11.
You only need to show one solution.
This task is similar to factoring an integer.
Related tasks
Count in factors
Prime decomposition
Factors of an integer
Sieve of Eratosthenes
Primality by trial division
Factors of a Mersenne number
Factors of a Mersenne number
Sequence of primes by trial division
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | NextPrimeMemo[n_] := (NextPrimeMemo[n] = NextPrime[n]);(*This improves performance by 30% or so*)
PrimeList[count_] := Prime/@Range[count];(*Just a helper to create an initial list of primes of the desired length*)
AppendPrime[list_] := Append[list,NextPrimeMemo[Last@list]];(*Another helper that makes creating the next candidate less verbose*)
NextCandidate[{list_, target_}] :=
With[
{len = Length@list, nextHead = NestWhile[Drop[#, -1] &, list, Total[#] > target &]},
Which[
{} == nextHead, {{}, target},
Total[nextHead] == target && Length@nextHead == len, {nextHead, target},
True, {NestWhile[AppendPrime, MapAt[NextPrimeMemo, nextHead, -1], Length[#] < Length[list] &], target}
]
];(*This is the meat of the matter. If it determines that the job is impossible, it returns a structure with an empty list of summands. If the input satisfies the success criteria, it just returns it (this will be our fixed point). Otherwise, it generates a subsequent candidate.*)
FormatResult[{list_, number_}, targetCount_] :=
StringForm[
"Partitioned `1` with `2` prime`4`: `3`",
number,
targetCount,
If[0 == Length@list, "no solutions found", StringRiffle[list, "+"]],
If[1 == Length@list, "", "s"]]; (*Just a helper for pretty-printing the output*)
PrimePartition[number_, count_] := FixedPoint[NextCandidate, {PrimeList[count], number}];(*This is where things kick off. NextCandidate will eventually return the failure format or a success, and either of those are fixed points of the function.*)
TestCases =
{
{99809, 1},
{18, 2},
{19, 3},
{20, 4},
{2017, 24},
{22699, 1},
{22699, 2},
{22699, 3},
{22699, 4},
{40355, 3}
};
TimedResults = ReleaseHold[Hold[AbsoluteTiming[FormatResult[PrimePartition @@ #, Last@#]]] & /@TestCases](*I thought it would be interesting to include the timings, which are in seconds*)
TimedResults // TableForm |
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Picat | Picat |
/* Picat 3.0#5 */
/* Author: Hakan Kjellerstrand */
table
partition1(0) = 1.
partition1(N) = P =>
S = 0,
K = 1,
M = (K*(3*K-1)) // 2,
while (M <= N)
S := S - ((-1)**K)*partition1(N-M),
K := K + 1,
M := (K*(3*K-1)) // 2
end,
K := 1,
M := (K*(3*K+1)) // 2,
while (M <= N)
S := S - ((-1)**K)*partition1(N-M),
K := K + 1,
M := (K*(3*K+1)) // 2
end,
P = S.
Picat> time(println('p(6666)'=partition1(6666)))
p(6666) = 193655306161707661080005073394486091998480950338405932486880600467114423441282418165863
CPU time 0.206 seconds.
|
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Picolisp | Picolisp |
(de gpentagonals (Max)
(make
(let (N 0 M 1)
(loop
(inc 'N (if (=0 (& M 1)) (>> 1 M) M))
(T (> N Max))
(link N)
(inc 'M)))))
(de p (N)
(cache '(NIL) N
(if (=0 N)
1
(let (Sum 0 Sgn 0)
(for G (gpentagonals N)
((if (< Sgn 2) 'inc 'dec) 'Sum (p (- N G)))
(setq Sgn (& 3 (inc Sgn))))
Sum))))
|
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) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ...
The successive numbers in the above equation have the differences: 1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ...
This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release.
In Wolfram Language, this function has been implemented as PartitionsP.
Task
Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive.
Bonus task: show how long it takes to compute PartitionsP(6666).
References
The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest.
Partition Function P Mathworld entry for the Partition function.
Partition function (number theory) Wikipedia entry for the Partition function.
Related tasks
9 billion names of God the integer
| #Prolog | Prolog |
/* SWI-Prolog 8.3.21 */
/* Author: Jan Burse */
:- table p/2.
p(0, 1) :- !.
p(N, X) :-
aggregate_all(sum(Z), (between(1,inf,K), M is K*(3*K-1)//2,
(M>N, !, fail; L is N-M, p(L,Y), Z is (-1)^K*Y)), A),
aggregate_all(sum(Z), (between(1,inf,K), M is K*(3*K+1)//2,
(M>N, !, fail; L is N-M, p(L,Y), Z is (-1)^K*Y)), B),
X is -A-B.
?- time(p(6666,X)).
% 13,962,294 inferences, 2.610 CPU in 2.743 seconds (95% CPU, 5350059 Lips)
X = 1936553061617076610800050733944860919984809503384
05932486880600467114423441282418165863.
|
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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #Nim | Nim | import strutils
type
BlockValue = object
known: int
x, y, z: int
Variables = tuple[x, y, z: int]
func `+=`(left: var BlockValue; right: BlockValue) =
## Symbolically add one block to another.
left.known += right.known
left.x += right.x - right.z # Z is excluded as n(Y - X - Z) = 0.
left.y += right.y + right.z
proc toString(n: BlockValue; vars: Variables): string =
## Return the representation of the block value, when X, Y, Z are known.
result = $(n.known + n.x * vars.x + n.y * vars.y + n.z * vars.z)
proc Solve2x2(a11, a12, b1, a21, a22, b2: int): Variables =
## Solve a puzzle, supposing an integer solution exists.
if a22 == 0:
result.x = b2 div a21
result.y = (b1 - a11 * result.x) div a12
else:
result.x = (b1 * a22 - b2 * a12) div (a11 * a22 - a21 * a12)
result.y = (b1 - a11 * result.x) div a12
result.z = result.y - result.x
var blocks : array[1..5, array[1..5, BlockValue]] # The lower triangle contains blocks.
# The bottom blocks.
blocks[5][1] = BlockValue(x: 1)
blocks[5][2] = BlockValue(known: 11)
blocks[5][3] = BlockValue(y: 1)
blocks[5][4] = BlockValue(known: 4)
blocks[5][5] = BlockValue(z: 1)
# Upward run.
for row in countdown(4, 1):
for column in 1..row:
blocks[row][column] += blocks[row + 1][column]
blocks[row][column] += blocks[row + 1][column + 1]
# Now have known blocks 40=[3][1], 151=[1][1] and Y=X+Z to determine X,Y,Z.
let vars = Solve2x2(blocks[1][1].x,
blocks[1][1].y,
151 - blocks[1][1].known,
blocks[3][1].x,
blocks[3][1].y,
40 - blocks[3][1].known)
# Print the results.
for row in 1..5:
var line = ""
for column in 1..row:
line.addSep(" ")
line.add toString(blocks[row][column], vars)
echo line |
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 middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #Oz | Oz | %% to compile : ozc -x <file.oz>
functor
import
System Application FD Search
define
proc{Quest Root Rules}
proc{Limit Rc Ls}
case Ls of nil then skip
[] X|Xs then
{Limit Rc Xs}
case X of N#V then
Rc.N =: V
[] N1#N2#N3 then
Rc.N1 =: Rc.N2 + Rc.N3
end
end
end
proc {Pyramid R}
{FD.tuple solution 15 0#FD.sup R} %% non-negative integers domain
%% 01 , pyramid format
%% 02 03
%% 04 05 06
%% 07 08 09 10
%% 11 12 13 14 15
R.1 =: R.2 + R.3 %% constraints of Pyramid of numbers
R.2 =: R.4 + R.5
R.3 =: R.5 + R.6
R.4 =: R.7 + R.8
R.5 =: R.8 + R.9
R.6 =: R.9 + R.10
R.7 =: R.11 + R.12
R.8 =: R.12 + R.13
R.9 =: R.13 + R.14
R.10 =: R.14 + R.15
{Limit R Rules} %% additional constraints
{FD.distribute ff R}
end
in
{Search.base.one Pyramid Root} %% search for solution
end
local
Root R
in
{Quest Root [1#151 4#40 12#11 14#4 13#11#15]} %% supply additional constraint rules
if {Length Root} >= 1 then
R = Root.1
{For 1 15 1
proc{$ I}
if {Member I [1 3 6 10]} then
{System.printInfo R.I#'\n'}
else
{System.printInfo R.I#' '}
end
end
}
else
{System.showInfo 'No solution found.'}
end
end
{Application.exit 0}
end |
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 on an n-by-n square grid, (the board), so that no queen attacks another of a different colour.
Task
Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).
Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
Display here results for the m=4, n=5 case.
References
Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
A250000 OEIS
| #Swift | Swift | enum Piece {
case empty, black, white
}
typealias Position = (Int, Int)
func place(_ m: Int, _ n: Int, pBlackQueens: inout [Position], pWhiteQueens: inout [Position]) -> Bool {
guard m != 0 else {
return true
}
var placingBlack = true
for i in 0..<n {
inner: for j in 0..<n {
let pos = (i, j)
for queen in pBlackQueens where queen == pos || !placingBlack && isAttacking(queen, pos) {
continue inner
}
for queen in pWhiteQueens where queen == pos || placingBlack && isAttacking(queen, pos) {
continue inner
}
if placingBlack {
pBlackQueens.append(pos)
placingBlack = false
} else {
placingBlack = true
pWhiteQueens.append(pos)
if place(m - 1, n, pBlackQueens: &pBlackQueens, pWhiteQueens: &pWhiteQueens) {
return true
} else {
pBlackQueens.removeLast()
pWhiteQueens.removeLast()
}
}
}
}
if !placingBlack {
pBlackQueens.removeLast()
}
return false
}
func isAttacking(_ queen: Position, _ pos: Position) -> Bool {
queen.0 == pos.0 || queen.1 == pos.1 || abs(queen.0 - pos.0) == abs(queen.1 - pos.1)
}
func printBoard(n: Int, pBlackQueens: [Position], pWhiteQueens: [Position]) {
var board = Array(repeating: Piece.empty, count: n * n)
for queen in pBlackQueens {
board[queen.0 * n + queen.1] = .black
}
for queen in pWhiteQueens {
board[queen.0 * n + queen.1] = .white
}
for (i, p) in board.enumerated() {
if i != 0 && i % n == 0 {
print()
}
switch p {
case .black:
print("B ", terminator: "")
case .white:
print("W ", terminator: "")
case .empty:
let j = i / n
let k = i - j * n
if j % 2 == k % 2 {
print("• ", terminator: "")
} else {
print("◦ ", terminator: "")
}
}
}
print("\n")
}
let nms = [
(2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3),
(5, 1), (5, 2), (5, 3), (5, 4), (5, 5),
(6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6),
(7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7)
]
for (n, m) in nms {
print("\(m) black and white queens on \(n) x \(n) board")
var blackQueens = [Position]()
var whiteQueens = [Position]()
if place(m, n, pBlackQueens: &blackQueens, pWhiteQueens: &whiteQueens) {
printBoard(n: n, pBlackQueens: blackQueens, pWhiteQueens: whiteQueens)
} else {
print("No solution")
}
} |
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 character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Java | Java | import java.util.*;
public class PasswordGenerator {
final static Random rand = new Random();
public static void main(String[] args) {
int num, len;
try {
if (args.length != 2)
throw new IllegalArgumentException();
len = Integer.parseInt(args[0]);
if (len < 4 || len > 16)
throw new IllegalArgumentException();
num = Integer.parseInt(args[1]);
if (num < 1 || num > 10)
throw new IllegalArgumentException();
for (String pw : generatePasswords(num, len))
System.out.println(pw);
} catch (IllegalArgumentException e) {
String s = "Provide the length of the passwords (min 4, max 16) you "
+ "want to generate,\nand how many (min 1, max 10)";
System.out.println(s);
}
}
private static List<String> generatePasswords(int num, int len) {
final String s = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";
List<String> result = new ArrayList<>();
for (int i = 0; i < num; i++) {
StringBuilder sb = new StringBuilder();
sb.append(s.charAt(rand.nextInt(s.length())));
sb.append((char) (rand.nextInt(10) + '0'));
sb.append((char) (rand.nextInt(26) + 'a'));
sb.append((char) (rand.nextInt(26) + 'A'));
for (int j = 4; j < len; j++) {
int r = rand.nextInt(93) + '!';
if (r == 92 || r == 96) {
j--;
} else {
sb.append((char) r);
}
}
result.add(shuffle(sb));
}
return result;
}
public static String shuffle(StringBuilder sb) {
int len = sb.length();
for (int i = len - 1; i > 0; i--) {
int r = rand.nextInt(i);
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(r));
sb.setCharAt(r, tmp);
}
return sb.toString();
}
} |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.