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/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.
| #Go | Go | package main
import (
"fmt"
"strings"
)
var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
var opa = map[string]struct {
prec int
rAssoc bool
}{
"^": {4, true},
"*": {3, false},
"/": {3, false},
"+": {2, false},
"-": {2, false},
}
func main() {
fmt.Println("infix: ", input)
fmt.Println("postfix:", parseInfix(input))
}
func parseInfix(e string) (rpn string) {
var stack []string // holds operators and left parenthesis
for _, tok := range strings.Fields(e) {
switch tok {
case "(":
stack = append(stack, tok) // push "(" to stack
case ")":
var op string
for {
// pop item ("(" or operator) from stack
op, stack = stack[len(stack)-1], stack[:len(stack)-1]
if op == "(" {
break // discard "("
}
rpn += " " + op // add operator to result
}
default:
if o1, isOp := opa[tok]; isOp {
// token is an operator
for len(stack) > 0 {
// consider top item on stack
op := stack[len(stack)-1]
if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec ||
o1.prec == o2.prec && o1.rAssoc {
break
}
// top item is an operator that needs to come off
stack = stack[:len(stack)-1] // pop it
rpn += " " + op // add it to result
}
// push operator (the new one) to stack
stack = append(stack, tok)
} else { // token is an operand
if rpn > "" {
rpn += " "
}
rpn += tok // add operand to result
}
}
}
// drain stack to result
for len(stack) > 0 {
rpn += " " + stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
return
} |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #Haskell | Haskell | -- polynomial utils
a `nmul` n = map (*n) a
a `ndiv` n = map (`div` n) a
instance (Integral a) => Num [a] where
(+) = zipWith (+)
negate = map negate
a * b = foldr f undefined b where
f x z = (a `nmul` x) + (0 : z)
abs _ = undefined
signum _ = undefined
fromInteger n = fromInteger n : repeat 0
-- replace x in polynomial with x^n
repl a n = concatMap (: replicate (n-1) 0) a
-- S2: (a^2 + b)/2
cycleIndexS2 a b = (a*a + b)`ndiv` 2
-- S4: (a^4 + 6 a^2 b + 8 a c + 3 b^2 + 6 d) / 24
cycleIndexS4 a b c d = ((a ^ 4) +
(a ^ 2 * b) `nmul` 6 +
(a * c) `nmul` 8 +
(b ^ 2) `nmul` 3 +
d `nmul` 6) `ndiv` 24
a598 = x1
-- A000598: A(x) = 1 + (1/6)*x*(A(x)^3 + 3*A(x)*A(x^2) + 2*A(x^3))
x1 = 1 : ((x1^3) + ((x2*x1)`nmul` 3) + (x3`nmul`2)) `ndiv` 6
x2 = x1`repl`2
x3 = x1`repl`3
x4 = x1`repl`4
-- A000678 = x CycleIndex(S4, A000598(x))
a678 = 0 : cycleIndexS4 x1 x2 x3 x4
-- A000599 = CycleIndex(S2, A000598(x) - 1)
a599 = cycleIndexS2 (0 : tail x1) (0 : tail x2)
-- A000602 = A000678(x) - A000599(x) + A000599(x^2)
a602 = a678 - a599 + x2
main = mapM_ print $ take 200 $ zip [0 ..] a602 |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #APL | APL |
a←'abcdefghijklmnopqrstuvwxyz'
A←'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Panagram←{∧/ ∨⌿ 2 26⍴(a,A) ∊ ⍵}
Panagram 'This should fail'
0
Panagram 'The quick brown fox jumps over the lazy dog'
1
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #AppleScript | AppleScript | use framework "Foundation" -- ( for case conversion function )
--------------------- PANGRAM CHECKER --------------------
-- isPangram :: String -> Bool
on isPangram(s)
script charUnUsed
property lowerCaseString : my toLower(s)
on |λ|(c)
lowerCaseString does not contain c
end |λ|
end script
0 = length of filter(charUnUsed, ¬
"abcdefghijklmnopqrstuvwxyz")
end isPangram
--------------------------- TEST -------------------------
on run
map(isPangram, {¬
"is this a pangram", ¬
"The quick brown fox jumps over the lazy dog"})
--> {false, true}
end run
-------------------- GENERIC FUNCTIONS -------------------
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- 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
-- Lift 2nd class handler function into
-- 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- toLower :: String -> String
on toLower(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower |
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.
| #Elixir | Elixir | defmodule Pascal do
defp ij(n), do: for i <- 1..n, j <- 1..n, do: {i,j}
def upper_triangle(n) do
Enum.reduce(ij(n), Map.new, fn {i,j},acc ->
val = cond do
i==1 -> 1
j<i -> 0
true -> Map.get(acc, {i-1, j-1}) + Map.get(acc, {i, j-1})
end
Map.put(acc, {i,j}, val)
end) |> print(1..n)
end
def lower_triangle(n) do
Enum.reduce(ij(n), Map.new, fn {i,j},acc ->
val = cond do
j==1 -> 1
i<j -> 0
true -> Map.get(acc, {i-1, j-1}) + Map.get(acc, {i-1, j})
end
Map.put(acc, {i,j}, val)
end) |> print(1..n)
end
def symmetic_triangle(n) do
Enum.reduce(ij(n), Map.new, fn {i,j},acc ->
val = if i==1 or j==1, do: 1,
else: Map.get(acc, {i-1, j}) + Map.get(acc, {i, j-1})
Map.put(acc, {i,j}, val)
end) |> print(1..n)
end
def print(matrix, range) do
Enum.each(range, fn i ->
Enum.map(range, fn j -> Map.get(matrix, {i,j}) end) |> IO.inspect
end)
end
end
IO.puts "Pascal upper-triangular matrix:"
Pascal.upper_triangle(5)
IO.puts "Pascal lower-triangular matrix:"
Pascal.lower_triangle(5)
IO.puts "Pascal symmetric matrix:"
Pascal.symmetic_triangle(5) |
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. | #Nim | Nim | import db_sqlite
let db = open(":memory:", "", "", "")
# Setup
db.exec(sql"CREATE TABLE players (name, score, active, jerseyNum)")
db.exec(sql"INSERT INTO players VALUES (?, ?, ?, ?)", "name", 0, "false", 99)
# Update the row.
db.exec(sql"UPDATE players SET name=?, score=?, active=? WHERE jerseyNum=?",
"Smith, Steve", 42, true, 99)
# Display result.
for row in db.fastRows(sql"SELECT * FROM players"):
echo row
db.close() |
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. | #Objeck | Objeck | use IO;
use ODBC;
bundle Default {
class Sql {
function : Main(args : String[]) ~ Nil {
conn := Connection->New("ds", "user", "password");
if(conn <> Nil) {
sql := "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?";
pstmt := conn->CreateParameterStatement(sql);
pstmt->SetVarchar(1, "Smith, Steve");
pstmt->SetInt(2, 42);
pstmt->SetBit(3, true);
pstmt->SetInt(4, 99);
pstmt->Update()->PrintLine();
conn->Close();
};
}
} |
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
| #Bracmat | Bracmat | ( out$"Number of rows? "
& get':?R
& -1:?I
& whl
' ( 1+!I:<!R:?I
& 1:?C
& -1:?K
& !R+-1*!I:?tabs
& whl'(!tabs+-1:>0:?tabs&put$\t)
& whl
' ( 1+!K:~>!I:?K
& put$(!C \t\t)
& !C*(!I+-1*!K)*(!K+1)^-1:?C
)
& put$\n
)
&
) |
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.
| #PicoLisp | PicoLisp | # Return a cons pair of address and port: (address . port)
(de ipAddress (Adr)
(use (@A @B @C @D @Port)
(cond
((match '("[" @A "]" ":" @Port) Adr)
(adrIPv6 (split @A ":") @Port) )
((match '("[" @A "]") Adr)
(adrIPv6 (split @A ":")) )
((match '(@A ":" @B ":" @C) Adr)
(adrIPv6 (cons @A @B (split @C ":"))) )
((match '(@A "." @B "." @C "." @D ":" @Port) Adr)
(adrIPv4 (list @A @B @C @D) @Port) )
((match '(@A "." @B "." @C "." @D) Adr)
(adrIPv4 (list @A @B @C @D)) )
(T (quit "Bad IP address" (pack Adr))) ) ) )
(de adrIPv4 (Lst Port)
(cons
(sum >> (-24 -16 -8 0) (mapcar format Lst))
(format Port) ) )
(de adrIPv6 (Lst Port)
(cons
(sum >>
(-112 -96 -80 -64 -48 -32 -16 0)
(mapcan
'((X)
(if X
(cons (hex X))
(need (- 9 (length Lst)) 0) ) ) # Handle '::'
(cons (or (car Lst) "0") (cdr Lst)) ) )
(format Port) ) ) |
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.
| #Raku | Raku | role BinaryTree[::T] {
has T $.value;
has BinaryTree[T] $.left;
has BinaryTree[T] $.right;
method replace-all(T $value) {
$!value = $value;
$!left.replace-all($value) if $!left.defined;
$!right.replace-all($value) if $!right.defined;
}
}
class IntTree does BinaryTree[Int] { }
my IntTree $it .= new(value => 1,
left => IntTree.new(value => 2),
right => IntTree.new(value => 3));
$it.replace-all(42);
say $it; |
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.
| #REXX | REXX | /*REXX program demonstrates (with displays) a method of parametric polymorphism. */
call newRoot 1.00, 3 /*new root, and also indicate 3 stems.*/
/* [↓] no need to label the stems. */
call addStem 1.10 /*a new stem and its initial value. */
call addStem 1.11 /*" " " " " " " */
call addStem 1.12 /*" " " " " " " */
call addStem 1.20 /*" " " " " " " */
call addStem 1.21 /*" " " " " " " */
call addStem 1.22 /*" " " " " " " */
call sayNodes /*display some nicely formatted values.*/
call modRoot 50 /*modRoot will add fifty to all stems. */
call sayNodes /*display some nicely formatted values.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
addStem: nodes= nodes + 1; do j=1 for stems; root.nodes.j= arg(1); end; return
newRoot: parse arg @,stems; nodes= -1; call addStem copies('═',9); call addStem @; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
modRoot: arg #; do j=1 for nodes /*traipse through all the defined nodes*/
do k=1 for stems /*add bias ──►───────────────────────┐ */
if datatype(root.j.k, 'N') then root.j.k= root.j.k + # /* ◄───┘ */
end /*k*/ /* [↑] add if stem value is numeric.*/
end /*j*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sayNodes: w= 9; do j=0 to nodes; _= /*ensure each of the nodes gets shown. */
do k=1 for stems; _= _ center(root.j.k, w) /*concatenate a node.*/
end /*k*/
$= word('node='j, 1 + (j<1) ) /*define a label for this line's output*/
say center($, w) substr(_, 2) /*ignore 1st (leading) blank which was */
end /*j*/ /* [↑] caused by concatenation.*/
say /*show a blank line to separate outputs*/
return |
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.
| #Haskell | Haskell | import Debug.Trace
data Expression = Const String | Exp Expression String Expression
------------- INFIX EXPRESSION FROM RPN STRING -----------
infixFromRPN :: String -> Expression
infixFromRPN = head . foldl buildExp [] . words
buildExp :: [Expression] -> String -> [Expression]
buildExp stack x
| (not . isOp) x =
let v = Const x : stack
in trace (show v) v
| otherwise =
let v = Exp l x r : rest
in trace (show v) v
where
r : l : rest = stack
isOp = (`elem` ["^", "*", "/", "+", "-"])
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
( \s ->
putStr (s <> "\n-->\n")
>> (print . infixFromRPN)
s
>> putStrLn []
)
[ "3 4 2 * 1 5 - 2 3 ^ ^ / +",
"1 2 + 3 4 + ^ 5 6 + ^",
"1 4 + 5 3 + 2 3 * * *",
"1 2 * 3 4 * *",
"1 2 + 3 4 + +"
]
---------------------- SHOW INSTANCE ---------------------
instance Show Expression where
show (Const x) = x
show exp@(Exp l op r) = left <> " " <> op <> " " <> right
where
left
| leftNeedParen = "( " <> show l <> " )"
| otherwise = show l
right
| rightNeedParen = "( " <> show r <> " )"
| otherwise = show r
leftNeedParen =
(leftPrec < opPrec)
|| ((leftPrec == opPrec) && rightAssoc exp)
rightNeedParen =
(rightPrec < opPrec)
|| ((rightPrec == opPrec) && leftAssoc exp)
leftPrec = precedence l
rightPrec = precedence r
opPrec = precedence exp
leftAssoc :: Expression -> Bool
leftAssoc (Const _) = False
leftAssoc (Exp _ op _) = op `notElem` ["^", "*", "+"]
rightAssoc :: Expression -> Bool
rightAssoc (Const _) = False
rightAssoc (Exp _ op _) = op == "^"
precedence :: Expression -> Int
precedence (Const _) = 5
precedence (Exp _ op _)
| op == "^" = 4
| op `elem` ["*", "/"] = 3
| op `elem` ["+", "-"] = 2
| otherwise = 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.
| #jq | jq | # fs(f, s) takes a function, f, of one value and a sequence of values s,
# and returns an ordered sequence of the result of applying function f to every value of s in turn.
def fs(f; s): s | f;
# f1 takes a value and returns it multiplied by 2:
def f1: 2 * .;
# f2 takes a value and returns it squared:
def f2: . * .;
# Partially apply f1 to fs to form function fsf1(s):
def fsf1(s): fs(f1;s);
# Partially apply f2 to fs to form function fsf2(s)
def fsf2(s): fs(f2; s);
# Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive ...
"fsf1",
[fsf1(range(0;4))],
"fsf2",
[fsf2(range(0;4))],
# and then the sequence of even integers from 2 to 8 inclusive:
"fsf1",
[fsf1(range(2;9;2))],
"fsf2",
[fsf2(range(2;9;2))] |
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.
| #Julia | Julia |
fs(f, s) = map(f, s)
f1(x) = 2x
f2(x) = x^2
fsf1(s) = fs(f1, s)
fsf2(s) = fs(f2, s)
s1 = [0, 1, 2 ,3]
s2 = [2, 4, 6, 8]
println("fsf1 of s1 is $(fsf1(s1))")
println("fsf2 of s1 is $(fsf2(s1))")
println("fsf1 of s2 is $(fsf1(s2))")
println("fsf2 of s2 is $(fsf2(s2))")
|
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
| #Ring | Ring |
# Project : Partition an integer X into N primes
load "stdlib.ring"
nr = 0
num = 0
list = list(100000)
items = newlist(pow(2,len(list))-1,100000)
while true
nr = nr + 1
if isprime(nr)
num = num + 1
list[num] = nr
ok
if num = 100000
exit
ok
end
powerset(list,100000)
showarray(items,100000)
see nl
func showarray(items,ind)
for p = 1 to 20
if (p > 17 and p < 21) or p = 99809 or p = 2017 or p = 22699 or p = 40355
for n = 1 to len(items)
flag = 0
for m = 1 to ind
if items[n][m] = 0
exit
ok
flag = flag + items[n][m]
next
if flag = p
str = ""
for x = 1 to len(items[n])
if items[n][x] != 0
str = str + items[n][x] + " "
ok
next
str = left(str, len(str) - 1)
str = str + "]"
if substr(str, " ") > 0
see "" + p + " = ["
see str + nl
exit
else
str = ""
ok
ok
next
ok
next
func powerset(list,ind)
num = 0
num2 = 0
items = newlist(pow(2,len(list))-1,ind)
for i = 2 to (2 << len(list)) - 1 step 2
num2 = 0
num = num + 1
for j = 1 to len(list)
if i & (1 << j)
num2 = num2 + 1
if list[j] != 0
items[num][num2] = list[j]
ok
ok
next
next
return items
|
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
| #Ruby | Ruby | require "prime"
def prime_partition(x, n)
Prime.each(x).to_a.combination(n).detect{|primes| primes.sum == x}
end
TESTCASES = [[99809, 1], [18, 2], [19, 3], [20, 4], [2017, 24],
[22699, 1], [22699, 2], [22699, 3], [22699, 4], [40355, 3]]
TESTCASES.each do |prime, num|
res = prime_partition(prime, num)
str = res.nil? ? "no solution" : res.join(" + ")
puts "Partitioned #{prime} with #{num} primes: #{str}"
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.
| #Racket | Racket |
#lang racket/base
(require racket/list)
(struct cell (v x z) #:transparent)
(define (cell-add cx cy)
(cell (+ (cell-v cx) (cell-v cy))
(+ (cell-x cx) (cell-x cy))
(+ (cell-z cx) (cell-z cy))))
(define (cell-sub cx cy)
(cell (- (cell-v cx) (cell-v cy))
(- (cell-x cx) (cell-x cy))
(- (cell-z cx) (cell-z cy))))
|
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.
| #Raku | Raku | # set up triangle
my $rows = 5;
my @tri = (1..$rows).map: { [ { x => 0, z => 0, v => 0, rhs => Nil } xx $_ ] }
@tri[0][0]<rhs> = 151;
@tri[2][0]<rhs> = 40;
@tri[4][0]<x> = 1;
@tri[4][1]<v> = 11;
@tri[4][2]<x> = 1;
@tri[4][2]<z> = 1;
@tri[4][3]<v> = 4;
@tri[4][4]<z> = 1;
# aggregate from bottom to top
for @tri - 2 ... 0 -> $row {
for 0 ..^ @tri[$row] -> $col {
@tri[$row][$col]{$_} = @tri[$row+1][$col]{$_} + @tri[$row+1][$col+1]{$_} for 'x','z','v';
}
}
# find equations
my @eqn = gather for @tri -> $row {
for @$row -> $cell {
take [ $cell<x>, $cell<z>, $cell<rhs> - $cell<v> ] if defined $cell<rhs>;
}
}
# print equations
say "Equations:";
say " x + z = y";
for @eqn -> [$x,$z,$y] { say "$x x + $z z = $y" }
# solve
my $f = @eqn[0][1] / @eqn[1][1];
@eqn[0][$_] -= $f * @eqn[1][$_] for 0..2;
$f = @eqn[1][0] / @eqn[0][0];
@eqn[1][$_] -= $f * @eqn[0][$_] for 0..2;
# print solution
say "Solution:";
my $x = @eqn[0][2] / @eqn[0][0];
my $z = @eqn[1][2] / @eqn[1][1];
my $y = $x + $z;
say "x=$x, y=$y, z=$z"; |
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
| #ooRexx | ooRexx | /*REXX program generates a random password according to the Rosetta Code task's rules.*/
parse arg L N seed xxx dbg /*obtain optional arguments from the CL*/
casl= 'abcdefghijklmnopqrstuvwxyz' /*define lowercase alphabet. */
casu= translate(casle) /*define uppercase alphabet. */
digs= '0123456789' /*define digits. */
/* avoiding the ambiguous characters Il1 o0 5S */
casl= 'abcdefghijkmnpqrtuvwxy' /*define lowercase alphabet. */
casu= translate(casl) /*define uppercase alphabet. */
digs= '0123456789' /*define digits. */
spec= '''!"#$%&()+,-./:;<=>?@[]^{|}~' /*define a bunch of special characters.*/
if L='?' then call help /*does user want documentation shown? */
if L='' | L="," then L=8 /*Not specified? Then use the default.*/
If N='' | N="," then N=1 /* " " " " " " */
If xxx=''| xxx="," then xxx='1lI0O2Z5S' /* " " " " " " */
if seed>'' &,
seed<>',' then Do
if \datatype(seed,'W')then call ser "seed is not an integer:" seed
Call random ,,seed /*the seed for repeatable RANDOM BIF #s*/
End
casl=remove(xxx,casl)
casu=remove(xxx,casu)
digs=remove(xxx,digs)
Say 'casl='casl
Say 'casu='casu
Say 'digs='digs
Say 'spec='spec
if \datatype(L, 'W') then call ser "password length, it isn't an integer: " L
if L<4 then call ser "password length, it's too small: " L
if L>80 then call ser "password length, it's too large: " L
if \datatype(N, 'W') then call ser "number of passwords, it isn't an integer: " N
if N<0 then call ser "number of passwords, it's too small: " N
do g=1 for N /*generate N passwords (default is 1)*/
pw=letterL()||letterU()||numeral()||special()/*generate 4 random PW constituents.*/
do k=5 to L; z=random(1, 4) /* [?] flush out PW with more parts. */
if z==1 then pw=pw || letterL() /*maybe append random lowercase letter.*/
if z==2 then pw=pw || letterU() /* " " " uppercase " */
if z==3 then pw=pw || numeral() /* " " " numeral */
if z==4 then pw=pw || special() /* " " " special character*/
end /*k*/ /* [?] code below randomizes PW chars.*/
t=length(pw) /*the length of the password (in bytes)*/
do L+L /*perform a random number of char swaps*/
a=random(1,t); x=substr(pw,a,1) /*A: 1st char location; X is the char.*/
b=random(1,t); y=substr(pw,b,1) /*B: 2nd " " Y " " " */
pw=overlay(x,pw,b); pw=overlay(y,pw,a) /* swap the two chars. */
end /*swaps*/ /* [?] perform extra swap to be sure. */
say right(g,length(N)) 'password is: ' pw counts() /*display the Nth password */
end /*g*/
exit /*stick a fork in it, we're all done. */
/*--------------------------------------------------------------------------------------*/
ser: say; say '***error*** invalid' arg(1); exit 13 /*display an error message*/
letterL: return substr(casl, random(1, length(casl)), 1) /*return random lowercase.*/
letterU: return substr(casu, random(1, length(casu)), 1) /* " " uppercase.*/
numeral: return substr(digs, random(1, length(digs)), 1) /* " " numeral. */
special: return substr(spec, random(1, length(spec)), 1) /* " " special char*/
remove: Procedure
Parse arg nono,s
Return space(translate(s,'',nono),0)
/*--------------------------------------------------------------------------------------*/
counts:
If dbg>'' Then Do
cnt.=0
str.=''
Do j=1 To length(pw)
c=substr(pw,j,1)
If pos(c,casL)>0 Then Do; cnt.0casL=cnt.0casL+1; str.0casL=str.0casL||c; End
If pos(c,casU)>0 Then Do; cnt.0casU=cnt.0casU+1; str.0casU=str.0casU||c; End
If pos(c,digs)>0 Then Do; cnt.0digs=cnt.0digs+1; str.0digs=str.0digs||c; End
If pos(c,spec)>0 Then Do; cnt.0spec=cnt.0spec+1; str.0spec=str.0spec||c; End
End
txt=cnt.0casL cnt.0casU cnt.0digs cnt.0spec
If pos(' 0 ',txt)>0 Then
txt=txt 'error'
Return txt str.0casL str.0casU str.0digs str.0spec
End
Else
txt=''
Return txt
help: signal .; .: do j=sigL+2 to sourceline()-1; say sourceline(j); end; exit 0
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~ documentation begins on next line.~~~~~~~~~~~~~~~~~~~~~~~~~
+-----------------------------------------------------------------------------+
¦ Documentation for the GENPW program: ¦
¦ ¦
¦ Rexx genpwd <length|,> <howmany|,> <seed|,> <xxx|,> <dbg> ¦
¦ 8 1 n '1lI0O2Z5S' none Defaults ¦
¦ ¦
¦--- where: ¦
¦ length is the length of the passwords to be generated. ¦
¦ The default is 8. ¦
¦ If a comma (,) is specified, the default is used. ¦
¦ The minimum is 4, the maximum is 80. ¦
¦ ¦
¦ howMany is the number of passwords to be generated. ¦
¦ The default is 1. ¦
¦ xxx Characters NOT to be used in generated passwords ¦
¦ dbg Schow count of characters in the 4 groups ¦
+-----------------------------------------------------------------------------+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~documentation ends on the previous line.~~~~~~~~~~~~~~~~~~~*/ |
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
| #Wren | Wren | var permute // recursive
permute = Fn.new { |input|
if (input.count == 1) return [input]
var perms = []
var toInsert = input[0]
for (perm in permute.call(input[1..-1])) {
for (i in 0..perm.count) {
var newPerm = perm.toList
newPerm.insert(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
var input = [1, 2, 3]
var perms = permute.call(input)
System.print("There are %(perms.count) permutations of %(input), namely:\n")
perms.each { |perm| System.print(perm) } |
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.
| #zkl | zkl | Series:=Walker(fcn(vs){ // just keep appending new values to a list
vs.append(111.0 - 1130.0/vs[-1] + 3000.0/(vs[-1]*vs[-2])) }.fp(List(2,-4)));
series:=Series.drop(100).value; |
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
| #F.23 | F# |
(*
Nigel Galloway February 21st., 2017
*)
let N n i g e l =
let G = function
|"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"->Some(string n+string i+string g+string e+string l)
|"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"->Some(string n+string i+string g+string e+string l)
|"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"->Some(string n+string i+string g+string e+string l)
|_->None
G ([|byte n;byte i;byte g;byte e;byte l|]|>System.Security.Cryptography.SHA256.Create().ComputeHash|>Array.map(fun (x:byte)->System.String.Format("{0:x2}",x))|>String.concat "")
open System.Threading.Tasks
let n1 = Task.Factory.StartNew(fun ()->['a'..'m']|>List.collect(fun n->['a'..'m']|>List.collect(fun i->['a'..'m']|>List.collect(fun g->['a'..'z']|>List.collect(fun e->['a'..'z']|>List.choose(fun l->N n i g e l))))))
let n2 = Task.Factory.StartNew(fun ()->['a'..'m']|>List.collect(fun n->['a'..'m']|>List.collect(fun i->['n'..'z']|>List.collect(fun g->['a'..'z']|>List.collect(fun e->['a'..'z']|>List.choose(fun l->N n i g e l))))))
let n3 = Task.Factory.StartNew(fun ()->['a'..'m']|>List.collect(fun n->['n'..'z']|>List.collect(fun i->['a'..'m']|>List.collect(fun g->['a'..'z']|>List.collect(fun e->['a'..'z']|>List.choose(fun l->N n i g e l))))))
let n4 = Task.Factory.StartNew(fun ()->['a'..'m']|>List.collect(fun n->['n'..'z']|>List.collect(fun i->['n'..'z']|>List.collect(fun g->['a'..'z']|>List.collect(fun e->['a'..'z']|>List.choose(fun l->N n i g e l))))))
let n5 = Task.Factory.StartNew(fun ()->['n'..'z']|>List.collect(fun n->['a'..'m']|>List.collect(fun i->['a'..'m']|>List.collect(fun g->['a'..'z']|>List.collect(fun e->['a'..'z']|>List.choose(fun l->N n i g e l))))))
let n6 = Task.Factory.StartNew(fun ()->['n'..'z']|>List.collect(fun n->['a'..'m']|>List.collect(fun i->['n'..'z']|>List.collect(fun g->['a'..'z']|>List.collect(fun e->['a'..'z']|>List.choose(fun l->N n i g e l))))))
let n7 = Task.Factory.StartNew(fun ()->['n'..'z']|>List.collect(fun n->['n'..'z']|>List.collect(fun i->['a'..'m']|>List.collect(fun g->['a'..'z']|>List.collect(fun e->['a'..'z']|>List.choose(fun l->N n i g e l))))))
let n8 = Task.Factory.StartNew(fun ()->['n'..'z']|>List.collect(fun n->['n'..'z']|>List.collect(fun i->['n'..'z']|>List.collect(fun g->['a'..'z']|>List.collect(fun e->['a'..'z']|>List.choose(fun l->N n i g e l))))))
for r in n1.Result@n2.Result@n3.Result@n4.Result@n5.Result@n6.Result@n7.Result@n8.Result do printfn "%s" r
|
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.
| #Go | Go | package main
import (
"fmt"
"math/big"
)
// collection of numbers. A slice is used for the collection.
// The elements are big integers, since that's what the function Primes
// uses (as was specified by the Prime decomposition task.)
var numbers = []*big.Int{
big.NewInt(12757923),
big.NewInt(12878611),
big.NewInt(12878893),
big.NewInt(12757923),
big.NewInt(15808973),
big.NewInt(15780709),
}
// main just calls the function specified by the task description and
// prints results. note it allows for multiple numbers with the largest
// minimal factor. the task didn't specify to handle this, but obviously
// it's possible.
func main() {
rs := lmf(numbers)
fmt.Println("largest minimal factor:", rs[0].decomp[0])
for _, r := range rs {
fmt.Println(r.number, "->", r.decomp)
}
}
// this type associates a number with it's prime decomposition.
// the type is neccessary so that they can be sent together over
// a Go channel, but it turns out to be convenient as well for
// the return type of lmf.
type result struct {
number *big.Int
decomp []*big.Int
}
// the function specified by the task description, "largest minimal factor."
func lmf([]*big.Int) []result {
// construct result channel and start a goroutine to decompose each number.
// goroutines run in parallel as CPU cores are available.
rCh := make(chan result)
for _, n := range numbers {
go decomp(n, rCh)
}
// collect results. <-rCh returns a single result from the result channel.
// we know how many results to expect so code here collects exactly that
// many results, and accumulates a list of those with the largest
// minimal factor.
rs := []result{<-rCh}
for i := 1; i < len(numbers); i++ {
switch r := <-rCh; r.decomp[0].Cmp(rs[0].decomp[0]) {
case 1:
rs = rs[:1]
rs[0] = r
case 0:
rs = append(rs, r)
}
}
return rs
}
// decomp is the function run as a goroutine. multiple instances of this
// function will run concurrently, one for each number being decomposed.
// it acts as a driver for Primes, calling Primes as needed, packaging
// the result, and sending the packaged result on the channel.
// "as needed" turns out to mean sending Primes a copy of n, as Primes
// as written is destructive on its argument.
func decomp(n *big.Int, rCh chan result) {
rCh <- result{n, Primes(new(big.Int).Set(n))}
}
// code below copied from Prime decomposition task
var (
ZERO = big.NewInt(0)
ONE = big.NewInt(1)
)
func Primes(n *big.Int) []*big.Int {
res := []*big.Int{}
mod, div := new(big.Int), new(big.Int)
for i := big.NewInt(2); i.Cmp(n) != 1; {
div.DivMod(n, i, mod)
for mod.Cmp(ZERO) == 0 {
res = append(res, new(big.Int).Set(i))
n.Set(div)
div.DivMod(n, i, mod)
}
i.Add(i, ONE)
}
return res
} |
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.
| #Clojure | Clojure |
(ns rosettacode.parsing-rpn-calculator-algorithm
(:require clojure.math.numeric-tower
clojure.string
clojure.pprint))
(def operators
"the only allowable operators for our calculator"
{"+" +
"-" -
"*" *
"/" /
"^" clojure.math.numeric-tower/expt})
(defn rpn
"takes a string and returns a lazy-seq of all the stacks"
[string]
(letfn [(rpn-reducer [stack item] ; this takes a stack and one item and makes a new stack
(if (contains? operators item)
(let [operand-1 (peek stack) ; if we used lists instead of vectors, we could use destructuring, but stacks would look backwards
stack-1 (pop stack)] ;we're assuming that all the operators are binary
(conj (pop stack-1)
((operators item) (peek stack-1) operand-1)))
(conj stack (Long. item))))] ; if it wasn't an operator, we'll assume it's a long. Could choose bigint, or even read-line
(reductions rpn-reducer [] (clojure.string/split string #"\s+")))) ;reductions is like reduce only shows all the intermediate steps
(let [stacks (rpn "3 4 2 * 1 5 - 2 3 ^ ^ / +")] ;bind it so we can output the answer separately.
(println "stacks: ")
(clojure.pprint/pprint stacks)
(print "answer:" (->> stacks last first)))
|
http://rosettacode.org/wiki/Pancake_numbers | Pancake numbers | Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.
The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.
Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)?
Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).
References
Bill Gates and the pancake problem
A058986
| #Raku | Raku | # 20201110 Raku programming solution
sub pancake(\n) {
my ($gap,$sum,$adj) = 2, 2, -1;
while ($sum < n) { $sum += $gap = $gap * 2 - 1 and $adj++ }
return n + $adj;
}
for (1..20).rotor(5) { say [~] @_».&{ sprintf "p(%2d) = %2d ",$_,pancake $_ } } |
http://rosettacode.org/wiki/Pancake_numbers | Pancake numbers | Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.
The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.
Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)?
Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).
References
Bill Gates and the pancake problem
A058986
| #REXX | REXX | /*REXX program calculates/displays ten pancake numbers (from 1 ──► 20, inclusive). */
pad= center('' , 10) /*indentation. */
say pad center('pancakes', 10 ) center('pancake flips', 15 ) /*show the hdr.*/
say pad center('' , 10, "─") center('', 15, "─") /* " " sep.*/
do #=1 for 20; say pad center(#, 10) center( pancake(#), 15) /*index, flips.*/
end /*#*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
pancake: procedure; parse arg n; gap= 2 /*obtain N; initialize the GAP. */
sum= 2 /* initialize the SUM. */
do adj=0 while sum <n /*perform while SUM is less than N. */
gap= gap*2 - 1 /*calculate the GAP. */
sum= sum + gap /*add the GAP to the SUM. */
end /*adj*/
return n +adj -1 /*return an adjusted adjustment sum. */ |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #C.2B.2B | C++ | #include <iostream>
#include <cstdint>
typedef uint64_t integer;
integer reverse(integer n) {
integer rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
// generates base 10 palindromes greater than 100 starting
// with the specified digit
class palindrome_generator {
public:
palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),
digit_(digit), even_(false) {}
integer next_palindrome() {
++next_;
if (next_ == power_ * (digit_ + 1)) {
if (even_)
power_ *= 10;
next_ = digit_ * power_;
even_ = !even_;
}
return next_ * (even_ ? 10 * power_ : power_)
+ reverse(even_ ? next_ : next_/10);
}
private:
integer power_;
integer next_;
int digit_;
bool even_;
};
bool gapful(integer n) {
integer m = n;
while (m >= 10)
m /= 10;
return n % (n % 10 + 10 * m) == 0;
}
template<size_t len>
void print(integer (&array)[9][len]) {
for (int digit = 1; digit < 10; ++digit) {
std::cout << digit << ":";
for (int i = 0; i < len; ++i)
std::cout << ' ' << array[digit - 1][i];
std::cout << '\n';
}
}
int main() {
const int n1 = 20, n2 = 15, n3 = 10;
const int m1 = 100, m2 = 1000;
integer pg1[9][n1];
integer pg2[9][n2];
integer pg3[9][n3];
for (int digit = 1; digit < 10; ++digit) {
palindrome_generator pgen(digit);
for (int i = 0; i < m2; ) {
integer n = pgen.next_palindrome();
if (!gapful(n))
continue;
if (i < n1)
pg1[digit - 1][i] = n;
else if (i < m1 && i >= m1 - n2)
pg2[digit - 1][i - (m1 - n2)] = n;
else if (i >= m2 - n3)
pg3[digit - 1][i - (m2 - n3)] = n;
++i;
}
}
std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n";
print(pg1);
std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n";
print(pg2);
std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n";
print(pg3);
return 0;
} |
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.
| #Haskell | Haskell | import Text.Printf
prec :: String -> Int
prec "^" = 4
prec "*" = 3
prec "/" = 3
prec "+" = 2
prec "-" = 2
leftAssoc :: String -> Bool
leftAssoc "^" = False
leftAssoc _ = True
isOp :: String -> Bool
isOp [t] = t `elem` "-+/*^"
isOp _ = False
simSYA :: [String] -> [([String], [String], String)]
simSYA xs = final <> [lastStep]
where
final = scanl f ([], [], "") xs
lastStep =
( \(x, y, _) ->
(reverse y <> x, [], "")
)
$ last final
f (out, st, _) t
| isOp t =
( reverse (takeWhile testOp st) <> out,
(t :) (dropWhile testOp st),
t
)
| t == "(" = (out, "(" : st, t)
| t == ")" =
( reverse (takeWhile (/= "(") st) <> out,
tail $ dropWhile (/= "(") st,
t
)
| otherwise = (t : out, st, t)
where
testOp x =
isOp x
&& ( leftAssoc t && prec t == prec x
|| prec t < prec x
)
main :: IO ()
main = do
a <- getLine
printf "%30s%20s%7s" "Output" "Stack" "Token"
mapM_
( \(x, y, z) ->
printf
"%30s%20s%7s\n"
(unwords $ reverse x)
(unwords y)
z
)
$ simSYA $ words a |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #J | J | part3=: ;@((<@([(],.(-+/"1))],.]+i.@(]-~1+<.@-:@-))"0 i.@>:@<.@%&3))
part4=: 3 :0
ij=.; (,.]+i.@:(]-~1+[:<.3%~y-]))&.> i.1+<.y%4
(,.y - +/"1) ; (<@(],"1 0 <.@-:@(y-[) (] + i.@>:@-) {:@] >. (>.-:y)-[)~+/)"1 ij
)
c0=: */@:{
c1=: 13 :'(*-:@(*>:))/y{~}:x'
c2=: 13 :'(*-:@(*>:))~/y{~}.x'
c3=: 13 :'3!2+y{~{.x'
radGenN=: [:;[:(],[:+/c0`c1`c2`c3@.(#.@(}.=}:)@[)"1)&.>/(<1x),~part3&.>@ i.@-
bcpGenN=: [: , 0 ,.~ -:@(*>:)@({~i.)
c11=: 13 :'*/(y{~0 1{x), -:(*>:)y{~{:x'
c12=: 13 :'*/(y{~0 3{x), -:(*>:)y{~2{x'
c13=: 13 :'*/(y{~{.x) , 3!2+ y{~{: x'
c14=: 13 :'*/(y{~_2{.x), -:(*>:)y{~{.x'
c15=: 13 :'*/ -:(*>:) y{~0 3{x'
c16=: 13 :'*/(y{~{:x) , 3!2+ y{~{. x'
c17=: 13 :'4!3+y{~{.x'
cassl=: c0`c11`c12`c13`c14`c15`c16`c17
ccpGenN=: 4 :0
if. 0=y do. i.0 return. end.
y{.2({.,0,}.) 0,+/@:(x cassl@.(#.@(}.=}:)@[)"1~[)@:part4"0 [1-.~i.y-1
)
NofParaff=: {. radGenN ((ccpGenN +:) + bcpGenN ) 2&|+<.@-: |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Arturo | Arturo | chars: map 97..122 => [to :string to :char]
pangram?: function [sentence][
every? chars 'ch ->
in? ch sentence
]
print pangram? "this is a sentence"
print pangram? "The quick brown fox jumps over the lazy dog." |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #ATS | ATS |
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
#include
"share/HATS/atspre_staload_libats_ML.hats"
//
(* ****** ****** *)
//
fun
letter_check
(
cs: string, c0: char
) : bool = cs.exists()(lam(c) => c0 = c)
//
(* ****** ****** *)
fun
Pangram_check
(text: string): bool = let
//
val
alphabet = "abcdefghijklmnopqrstuvwxyz"
val
((*void*)) = assertloc(length(alphabet) = 26)
//
in
alphabet.forall()(lam(c) => letter_check(text, c) || letter_check(text, toupper(c)))
end // end of [Pangram_check]
(* ****** ****** *)
implement
main0 () =
{
//
val
text0 = "The quick brown fox jumps over the lazy dog."
//
val-true = Pangram_check(text0)
val-false = Pangram_check("This is not a pangram sentence.")
//
} (* end of [main0] *)
(* ****** ****** *)
|
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.
| #Excel | Excel | PASCALMATRIX
=LAMBDA(n,
LAMBDA(f,
LET(
ixs, SEQUENCE(n, n, 0, 1),
f(BINCOEFF)(
QUOTIENT(ixs, n)
)(
MOD(ixs, n)
)
)
)
)
BINCOEFF
=LAMBDA(n,
LAMBDA(k,
IF(n < k,
0,
QUOTIENT(FACT(n), FACT(k) * FACT(n - k))
)
)
)
SYMMETRIC
=LAMBDA(f,
LAMBDA(a,
LAMBDA(b,
f(a + b)(b)
)
)
) |
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. | #Pascal | Pascal | program Parametrized_SQL_Statement;
uses
sqlite3, sysutils;
const
DB_FILE : PChar = ':memory:'; // Create an in-memory database.
var
DB :Psqlite3;
ResultCode :Integer;
SQL :PChar;
InsertStatements :array [1..4] of PChar;
CompiledStatement :Psqlite3_stmt;
i :integer;
{ CheckError
Checks the result code from an SQLite operation.
If it contains an error code then this procedure prints the error message,
closes the database and halts the program. }
procedure CheckError(ResultCode: integer; DB: Psqlite3);
begin
if ResultCode <> SQLITE_OK then
begin
writeln(format('Error #%d: %s', [ResultCode, sqlite3_errmsg(db)]));
sqlite3_close(DB);
halt(ResultCode);
end;
end;
{ SelectCallback
This callback function prints the results of the select statement.}
function SelectCallback(Data: pointer; ColumnCount: longint; Columns: PPChar; ColumnNames: PPChar):longint; cdecl;
var
i :longint;
col :PPChar;
begin
col := Columns;
for i:=0 to ColumnCount-1 do
begin
write(col^); // Print the current column value.
inc(col); // Advance the pointer.
if i<>ColumnCount-1 then write(' | ');
end;
writeln;
end;
begin
// Open the database.
ResultCode := sqlite3_open(DB_FILE, @DB);
CheckError(ResultCode, DB);
// Create the players table in the database.
SQL := 'create table players(' +
'id integer primary key asc, ' +
'name text, ' +
'score real, ' +
'active integer, ' + // Store the bool value as integer (see https://sqlite.org/datatype3.html chapter 2.1).
'jerseyNum integer);';
ResultCode := sqlite3_exec(DB, SQL, nil, nil, nil);
CheckError(ResultCode, DB);
// Insert some values into the players table.
InsertStatements[1] := 'insert into players (name, score, active, jerseyNum) ' +
'values (''Roethlisberger, Ben'', 94.1, 1, 7);';
InsertStatements[2] := 'insert into players (name, score, active, jerseyNum) ' +
'values (''Smith, Alex'', 85.3, 1, 11);';
InsertStatements[3] := 'insert into players (name, score, active, jerseyNum) ' +
'values (''Manning, Payton'', 96.5, 0, 18);';
InsertStatements[4] := 'insert into players (name, score, active, jerseyNum) ' +
'values (''Doe, John'', 15, 0, 99);';
for i:=1 to 4 do
begin
ResultCode := sqlite3_exec(DB, InsertStatements[i], nil, nil, nil);
CheckError(ResultCode, DB);
end;
// Display the contents of the players table.
writeln('Before update:');
SQL := 'select * from players;';
ResultCode := sqlite3_exec(DB, SQL, @SelectCallback, nil, nil);
CheckError(ResultCode, DB);
// Prepare the parametrized SQL statement to update player #99.
SQL := 'update players set name=?, score=?, active=? where jerseyNum=?;';
ResultCode := sqlite3_prepare_v2(DB, SQL, -1, @CompiledStatement, nil);
CheckError(ResultCode, DB);
// Bind the values to the parameters (see https://sqlite.org/c3ref/bind_blob.html).
ResultCode := sqlite3_bind_text(CompiledStatement, 1, PChar('Smith, Steve'), -1, nil);
CheckError(ResultCode, DB);
ResultCode := sqlite3_bind_double(CompiledStatement, 2, 42);
CheckError(ResultCode, DB);
ResultCode := sqlite3_bind_int(CompiledStatement, 3, 1);
CheckError(ResultCode, DB);
ResultCode := sqlite3_bind_int(CompiledStatement, 4, 99);
CheckError(ResultCode, DB);
// Evaluate the prepared SQL statement.
ResultCode := sqlite3_step(CompiledStatement);
if ResultCode <> SQLITE_DONE then
begin
writeln(format('Error #%d: %s', [ResultCode, sqlite3_errmsg(db)]));
sqlite3_close(DB);
halt(ResultCode);
end;
// Destroy the prepared statement object.
ResultCode := sqlite3_finalize(CompiledStatement);
CheckError(ResultCode, DB);
// Display the contents of the players table.
writeln('After update:');
SQL := 'select * from players;';
ResultCode := sqlite3_exec(DB, SQL, @SelectCallback, nil, nil);
CheckError(ResultCode, DB);
// Close the database connection.
sqlite3_close(db);
end. |
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
| #Burlesque | Burlesque |
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
|
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.
| #PL.2FI | PL/I | *process or(!) source xref attributes macro options;
/*********************************************************************
* Program to parse an IP address into --> IPv4 or IPv6 format
* 28.05.2013 Walter Pachl translated from REXX version 3
* x2d was the hard part :-)
*********************************************************************/
ip: proc options(main);
Dcl ipa char(50) Var;
Dcl ipi char(50) Var;
Dcl ipax char(50) Var Init('');
Dcl ipad char(50) Var Init('');
Dcl space char(4);
Dcl port char(5) Var;
dcl head Char(132) Var;
head=' input IP address hex IP address '!!
' decimal IP address space port';
Put Edit(head)(Skip,a);
Put Edit(copies('_',30),
copies('_',32),
copies('_',39),
copies('_', 5),
copies('_', 5))
(Skip,6(a,x(1)));
call expand('127.0.0.1');
call expand('127.0.0.1:80');
call expand('2605:2700:0:3::4713:93e3');
call expand('[2605:2700:0:3::4713:93e3]:80');
call expand('::1');
call expand('[::1]:80');
expand: procedure(s);
Dcl s Char(50) Var;
ipi=s;
ipa=s;
If index(ipa,'.')>0 Then
Call expand_ipv4;
Else
Call expand_ipv6;
ipad=x2d(ipax);
Put Edit(left(ipi,30),right(ipax,32),right(ipad,39),
right(space,5),right(port,5))
(Skip,6(a,x(1)));
End;
expand_ipv4: Proc;
Dcl a(4) Char(3) Var;
Dcl (pp,j) Bin Fixed(31);
space='IPv4';
pp=index(ipa,':');
If pp>0 Then Do;
port=substr(ipa,pp+1);
ipa=left(ipa,pp-1);
End;
Else
Port='';
Call parse((ipa),'.',a);
ipax='';
do j=1 To 4;
ipax=ipax!!a(j);
end;
End;
expand_ipv6: Proc;
Dcl a(8) Char(4) Var;
Dcl (s,o1,o2) Char(50) Var Init('');
Dcl (i,ii,pp,j,n) Bin Fixed(31) Init(0);
space='IPv6';
pp=index(ipa,']:');
If pp>0 Then Do;
port=substr(ipa,pp+2);
ipa=substr(ipa,2,pp-2);
End;
Else
Port='';
s=ipa;
j=0;
Do i=1 To 8 While(s>'');
pp=index(s,':');
dcl temp Char(6) Var;
If pp>1 Then
temp=left(s,pp-1);
Else
temp=s;
temp=right(temp,4,'0');
Select(pp);
When(0) Do;
a(i)=temp;
s='';
End;
When(1) Do;
a(i)='----';
ii=i;
s=substr(s,pp+1);
If left(s,1)=':' Then
s=substr(s,2);
End;
Otherwise Do;
a(i)=temp;
s=substr(s,pp+1);
End;
End;
End;
n=i-1;
o1='';
o2='';
Do i=1 To n;
If i=ii Then Do;
o1=o1!!'----';
Do j=1 To 9-n;
o2=o2!!'0000';
End;
End;
Else Do;
o1=o1!!right(a(i),4,'0');
o2=o2!!right(a(i),4,'0');
End;
End;
ipax=o2;
End;
parse: Proc(s,c,a);
Dcl s Char(50) Var;
Dcl c Char( 1);
Dcl a(*) Char(*) Var;
Dcl (i,p) Bin Fixed(31);
a='';
Do i=1 By 1 While(length(s)>0);
p=index(s,c);
If p>0 Then Do;
a(i)=left(s,p-1);
s=substr(s,p+1);
End;
Else Do;
a(i)=s;
s='';
End;
End;
End;
/*
underscore: Proc(s) Returns(char(132) Var);
Dcl s Char(*);
Dcl r Char(length(s)) Var Init('');
Dcl i Bin Fixed(31);
Dcl us Bit(1) Init('0'b);
Do i=1 To length(s)-1;
If substr(s,i,1)>' ' Then Do;
r=r!!'_';
us='1'b;
End;
Else Do;
If substr(s,i+1,1)>' ' & us Then
r=r!!'_';
Else Do;
r=r!!' ';
us='0'b;
End;
End;
End;
If substr(s,length(s),1)>' ' Then
r=r!!'_';
Return(r);
End;
center: Proc(s,l) Returns(char(50) Var);
Dcl s char(50) Var;
Dcl (l,b) Bin Fixed(31);
b=(l-length(s))/2;
Return(left(copies(' ',b)!!s,l));
End;
*/
copies: Proc(c,n) Returns(char(50) Var);
Dcl c char(50) Var;
Dcl n Bin Fixed(31);
Return(repeat(c,n-1));
End;
c2d: Procedure(s) Returns(Char(50) Var);
Dcl s Char(*) Var;
Dcl d Pic'99';
Dcl (v,part,result,old) Char(100) Var;
Dcl i Bin Fixed(31);
result='0';
v='1';
Do i=length(s) To 1 By -1;
d=c2d(substr(s,i,1));
part=longmult((v),(d));
result=longadd((result),(part));
v=longmult((v),'16');
End;
Do While(left(result,1)='0');
result=substr(result,2);
End;
Return(result);
/*
dbg: Proc(txt);
Dcl txt Char(*);
Put Skip list(txt);
End;
*/
x2d: Procedure(c) Returns(Char(2));
Dcl c Char(1);
Dcl res Char(2);
Select(c);
When('a','A') res='10';
When('b','B') res='11';
When('c','C') res='12';
When('d','D') res='13';
When('e','E') res='14';
When('f','F') res='15';
Otherwise res='0'!!c;
End;
Return(res);
End;
longmult: Procedure(as,bs) Returns(Char(1000) Var);
/* REXX **************************************************************
* Multiply(as,bs) -> as*bs
*********************************************************************/
Dcl (as,bs) Char(*);
Dcl (a(1000),b(1000),r(1000)) Pic'9';
Dcl (p,s) Pic'99';
Dcl (al,bl) Bin Fixed(31);
Dcl (i,ai,bi,ri,rim) Bin Fixed(31);
Dcl res Char(1000) Var Init((1000)'0');
al=length(as); Do ai=al To 1 By -1; a(ai)=substr(as,al-ai+1,1); End;
bl=length(bs); Do bi=bl To 1 By -1; b(bi)=substr(bs,bl-bi+1,1); End;
r=0;
rim=0;
Do bi=1 To bl;
Do ai=1 To al;
ri=ai+bi-1;
p=a(ai)*b(bi);
Do i=ri by 1 Until(p=0);
s=r(i)+p;
r(i)=mod(s,10);
p=s/10;
End;
rim=max(rim,i);
End;
End;
res='';
Do i=1 To rim;
res=r(i)!!res;
End;
Return(res);
End;
longadd: proc(as,bs) Returns(Char(100) Var);
Dcl (as,bs) Char(*) Var;
Dcl cs Char(100) Var Init('');
Dcl (al,bl,cl,i) Bin Fixed(31);
Dcl a(100) Pic'9' Init((100)0);
Dcl b(100) Pic'9' Init((100)0);
Dcl c(100) Pic'9' Init((100)0);
Dcl temp Pic'99';
al=length(as);
bl=length(bs);
Do i=1 To al; a(i)=substr(as,al-i+1,1); End;
Do i=1 To bl; b(i)=substr(bs,bl-i+1,1); End;
cl=max(al,bl)+1;
Do i=1 To cl;
temp=a(i)+b(i)+c(i);
c(i)=mod(temp,10);
c(i+1)=c(i+1)+temp/10;
End;
Do i=1 To cl;
cs=c(i)!!cs;
End;
Return(cs);
End;
End;
end; |
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.
| #Rust | Rust | struct TreeNode<T> {
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
impl <T> TreeNode<T> {
fn my_map<U,F>(&self, f: &F) -> TreeNode<U> where
F: Fn(&T) -> U {
TreeNode {
value: f(&self.value),
left: match self.left {
None => None,
Some(ref n) => Some(Box::new(n.my_map(f))),
},
right: match self.right {
None => None,
Some(ref n) => Some(Box::new(n.my_map(f))),
},
}
}
}
fn main() {
let root = TreeNode {
value: 3,
left: Some(Box::new(TreeNode {
value: 55,
left: None,
right: None,
})),
right: Some(Box::new(TreeNode {
value: 234,
left: Some(Box::new(TreeNode {
value: 0,
left: None,
right: None,
})),
right: None,
})),
};
root.my_map(&|x| { println!("{}" , x)});
println!("---------------");
let new_root = root.my_map(&|x| *x as f64 * 333.333f64);
new_root.my_map(&|x| { println!("{}" , x) });
} |
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.
| #Scala | Scala | case class Tree[+A](value: A, left: Option[Tree[A]], right: Option[Tree[A]]) {
def map[B](f: A => B): Tree[B] =
Tree(f(value), left map (_.map(f)), right map (_.map(f)))
} |
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func type: container (in type: elemType) is func
result
var type: container is void;
begin
container := array elemType;
global
const func container: map (in container: aContainer,
inout elemType: aVariable, ref func elemType: aFunc) is func
result
var container: mapResult is container.value;
begin
for aVariable range aContainer do
mapResult &:= aFunc;
end for;
end func;
end global;
end func;
const type: intContainer is container(integer);
var intContainer: container1 is [] (1, 2, 4, 6, 10, 12, 16, 18, 22);
var intContainer: container2 is 0 times 0;
const proc: main is func
local
var integer: num is 0;
begin
container2 := map(container1, num, num + 1);
for num range container2 do
write(num <& " ");
end for;
writeln;
end func; |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
every rpn := ![
"3 4 2 * 1 5 - 2 3 ^ ^ / +", # reqd
"1 2 + 3 4 + 5 6 + ^ ^",
"1 2 + 3 4 + 5 6 + ^ ^",
"1 2 + 3 4 + ^ 5 6 + ^" # reqd
] do {
printf("\nRPN = %i\n",rpn)
printf("infix = %i\n",RPN2Infix(rpn,show))
show := 1 # turn off inner working display
}
end
link printf
procedure RPN2Infix(expr,show) #: RPN to Infix conversion
static oi
initial {
oi := table([9,"'"]) # precedence & associativity
every oi[!"+-"] := [2,"l"] # 2L
every oi[!"*/"] := [3,"l"] # 3L
oi["^"] := [4,"r"] # 4R
}
show := if /show then printf else 1 # to show inner workings or not
stack := []
expr ? until pos(0) do { # Reformat as a tree
tab(many(' ')) # consume previous seperator
token := tab(upto(' ')|0) # get token
if token := numeric(token) then { # ... numeric
push(stack,oi[token]|||[token])
show("pushed numeric %i : %s\n",token,list2string(stack))
}
else { # ... operator
every b|a := pop(stack) # pop & reverse operands
pr := oi[token,1]
as := oi[token,2]
if a[1] < pr | (a[1] = pr & oi[token,2] == "r") then
a[3] := sprintf("( %s )",a[3])
if b[1] < pr | (b[1] == pr & oi[token,2] == "l") then
b[3] := sprintf("( %s )",b[3])
s := sprintf("%s %s %s",a[3],token,b[3])
push(stack,[pr,as,s]) # stack [prec, assoc, expr]
show("applied operator %s : %s\n",token,list2string(stack))
}
}
if *stack ~= 1 then stop("Parser failure")
return stack[1,3]
end
procedure list2string(L) #: format list as a string
s := "[ "
every x := !L do
s ||:= ( if type(x) == "list" then list2string(x)
else x) || " "
return s || "]"
end |
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.
| #Kotlin | Kotlin | // version 1.1.2
typealias Func = (Int) -> Int
typealias FuncS = (Func, List<Int>) -> List<Int>
fun fs(f: Func, seq: List<Int>) = seq.map { f(it) }
fun partial(fs: FuncS, f: Func) = { seq: List<Int> -> fs(f, seq) }
fun f1(n: Int) = 2 * n
fun f2(n: Int) = n * n
fun main(args: Array<String>) {
val fsf1 = partial(::fs, ::f1)
val fsf2 = partial(::fs, ::f2)
val seqs = listOf(
listOf(0, 1, 2, 3),
listOf(2, 4, 6, 8)
)
for (seq in seqs) {
println(fs(::f1, seq)) // normal
println(fsf1(seq)) // partial
println(fs(::f2, seq)) // normal
println(fsf2(seq)) // partial
println()
}
} |
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
| #Rust | Rust | // main.rs
mod bit_array;
mod prime_sieve;
use prime_sieve::PrimeSieve;
fn find_prime_partition(
sieve: &PrimeSieve,
number: usize,
count: usize,
min_prime: usize,
primes: &mut Vec<usize>,
index: usize,
) -> bool {
if count == 1 {
if number >= min_prime && sieve.is_prime(number) {
primes[index] = number;
return true;
}
return false;
}
for p in min_prime..number {
if sieve.is_prime(p)
&& find_prime_partition(sieve, number - p, count - 1, p + 1, primes, index + 1)
{
primes[index] = p;
return true;
}
}
false
}
fn print_prime_partition(sieve: &PrimeSieve, number: usize, count: usize) {
let mut primes = vec![0; count];
if !find_prime_partition(sieve, number, count, 2, &mut primes, 0) {
println!("{} cannot be partitioned into {} primes.", number, count);
} else {
print!("{} = {}", number, primes[0]);
for i in 1..count {
print!(" + {}", primes[i]);
}
println!();
}
}
fn main() {
let s = PrimeSieve::new(100000);
print_prime_partition(&s, 99809, 1);
print_prime_partition(&s, 18, 2);
print_prime_partition(&s, 19, 3);
print_prime_partition(&s, 20, 4);
print_prime_partition(&s, 2017, 24);
print_prime_partition(&s, 22699, 1);
print_prime_partition(&s, 22699, 2);
print_prime_partition(&s, 22699, 3);
print_prime_partition(&s, 22699, 4);
print_prime_partition(&s, 40355, 3);
} |
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
| #Scala | Scala | object PartitionInteger {
def sieve(nums: LazyList[Int]): LazyList[Int] =
LazyList.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))
// An 'infinite' stream of primes, lazy evaluation and memo-ized
private val oddPrimes = sieve(LazyList.from(3, 2))
private val primes = sieve(2 #:: oddPrimes).take(3600 /*50_000*/)
private def findCombo(k: Int, x: Int, m: Int, n: Int, combo: Array[Int]): Boolean = {
var foundCombo = combo.map(i => primes(i)).sum == x
if (k >= m) {
if (foundCombo) {
val s: String = if (m > 1) "s" else ""
printf("Partitioned %5d with %2d prime%s: ", x, m, s)
for (i <- 0 until m) {
print(primes(combo(i)))
if (i < m - 1) print('+') else println()
}
}
} else for (j <- 0 until n if k == 0 || j > combo(k - 1)) {
combo(k) = j
if (!foundCombo) foundCombo = findCombo(k + 1, x, m, n, combo)
}
foundCombo
}
private def partition(x: Int, m: Int): Unit = {
val n: Int = primes.count(it => it <= x)
if (n < m) throw new IllegalArgumentException("Not enough primes")
if (!findCombo(0, x, m, n, new Array[Int](m)))
printf("Partitioned %5d with %2d prime%s: (not possible)\n", x, m, if (m > 1) "s" else " ")
}
def main(args: Array[String]): Unit = {
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/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.
| #REXX | REXX | /*REXX program solves a (Pascal's) "Pyramid of Numbers" puzzle given four values. */
/* ╔══════════════════════════════════════════════════╗
║ answer ║
║ / ║
║ mid / ║
║ \ 151 ║
║ \ ααα ααα ║
║ 40 ααα ααα ║
║ ααα ααα ααα ααα ║
║ x 11 y 4 z ║
║ / \ ║
║ find: / \ ║
║ x y z b d ║
╚══════════════════════════════════════════════════╝ */
do #=2; _= sourceLine(#); n= pos('_', _) /* [↓] this DO loop shows (above) box.*/
if n\==0 then leave; say _ /*only display up to the above line. */
end /*#*/; say /* [↑] this is a way for in─line doc. */
parse arg b d mid answer . /*obtain optional variables from the CL*/
if b=='' | b=="," then b= 11 /*Not specified? Then use the default.*/
if d=='' | d=="," then d= 4 /* " " " " " " */
if mid='' | mid=="," then mid= 40 /* " " " " " " */
if answer='' | answer=="," then answer= 151 /* " " " " " " */
big= answer - 4*b - 4*d /*calculate BIG number less constants*/
do x=-big to big
do y=-big to big
if x+y\==mid - 2*b then iterate /*40 = x+2B+Y ──or── 40-2*11 = x+y */
do z=-big to big
if z \== y - x then iterate /*Z has to equal Y-X (Y= X+Z) */
if x+y*6+z==big then say right('x =', n) x right("y =",n) y right('z =',n) z
end /*z*/
end /*y*/
end /*x*/ /*stick a fork in it, we're all done. */ |
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
| #PARI.2FGP | PARI/GP | passwd(len=8, count=1, seed=0) =
{
if (len <= 4, print("password too short, minimum len=4"); return(), seed, setrand(seed));
my (C=["abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ","0123456789","!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"], P, j);
for (i=1, count, K = vector(#C); P = "";
for (l=1, len, K[j = random(#C)+1]++;
P = concat(P, Strchr(Vecsmall(C[j])[random(#C[j])+1]))
);
if (prod(z=1, #K, K[z]), print(P), i--) \\ if password contains all char classes print else redo
);
}
addhelp(passwd, "passwd({len},{count},{seed}): Password generator, optional: len (min=4, default=8), count (default=1), seed (default=0: no seed)"); |
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
| #XPL0 | XPL0 | code ChOut=8, CrLf=9;
def N=4; \number of objects (letters)
char S0, S1(N);
proc Permute(D); \Display all permutations of letters in S0
int D; \depth of recursion
int I, J;
[if D=N then
[for I:= 0 to N-1 do ChOut(0, S1(I));
CrLf(0);
return;
];
for I:= 0 to N-1 do
[for J:= 0 to D-1 do \check if object (letter) already used
if S1(J) = S0(I) then J:=100;
if J<100 then
[S1(D):= S0(I); \object (letter) not used so append it
Permute(D+1); \recurse next level deeper
];
];
];
[S0:= "rose "; \N different objects (letters)
Permute(0); \(space char avoids MSb termination)
] |
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
| #FreeBASIC | FreeBASIC | Function SHA_256(Byval message As String) As String
#Macro Ch (x, y, z)
(((x) And (y)) Xor ((Not (x)) And z))
#EndMacro
#Macro Maj (x, y, z)
(((x) And (y)) Xor ((x) And (z)) Xor ((y) And (z)))
#EndMacro
#Macro sigma0 (x)
(((x) Shr 2 Or (x) Shl 30) Xor ((x) Shr 13 Or (x) Shl 19) Xor ((x) Shr 22 Or (x) Shl 10))
#EndMacro
#Macro sigma1 (x)
(((x) Shr 6 Or (x) Shl 26) Xor ((x) Shr 11 Or (x) Shl 21) Xor ((x) Shr 25 Or (x) Shl 7))
#EndMacro
#Macro sigma2 (x)
(((x) Shr 7 Or (x) Shl 25) Xor ((x) Shr 18 Or (x) Shl 14) Xor ((x) Shr 3))
#EndMacro
#Macro sigma3 (x)
(((x) Shr 17 Or (x) Shl 15) Xor ((x) Shr 19 Or (x) Shl 13) Xor ((x) Shr 10))
#EndMacro
Dim As Long i, j
Dim As Ubyte Ptr ww1
Dim As Uinteger<32> Ptr ww4
Dim As Ulongint l = Len(message)
' set the first bit after the message to 1
message = message + Chr(1 Shl 7)
' add one char to the length
Dim As Ulong padding = 64 - ((l + 1) Mod (512 \ 8))
' check if we have enough room for inserting the length
If padding < 8 Then padding += 64
message += String(padding, Chr(0)) ' adjust length
Dim As Ulong l1 = Len(message) ' new length
l = l * 8 ' orignal length in bits
' create ubyte ptr to point to l ( = length in bits)
Dim As Ubyte Ptr ub_ptr = Cast(Ubyte Ptr, @l)
For i = 0 To 7 'copy length of message to the last 8 bytes
message[l1 -1 - i] = ub_ptr[i]
Next
'table of constants
Dim As Uinteger<32> K(0 To ...) = { _
&H428a2f98, &H71374491, &Hb5c0fbcf, &He9b5dba5, &H3956c25b, &H59f111f1, _
&H923f82a4, &Hab1c5ed5, &Hd807aa98, &H12835b01, &H243185be, &H550c7dc3, _
&H72be5d74, &H80deb1fe, &H9bdc06a7, &Hc19bf174, &He49b69c1, &Hefbe4786, _
&H0fc19dc6, &H240ca1cc, &H2de92c6f, &H4a7484aa, &H5cb0a9dc, &H76f988da, _
&H983e5152, &Ha831c66d, &Hb00327c8, &Hbf597fc7, &Hc6e00bf3, &Hd5a79147, _
&H06ca6351, &H14292967, &H27b70a85, &H2e1b2138, &H4d2c6dfc, &H53380d13, _
&H650a7354, &H766a0abb, &H81c2c92e, &H92722c85, &Ha2bfe8a1, &Ha81a664b, _
&Hc24b8b70, &Hc76c51a3, &Hd192e819, &Hd6990624, &Hf40e3585, &H106aa070, _
&H19a4c116, &H1e376c08, &H2748774c, &H34b0bcb5, &H391c0cb3, &H4ed8aa4a, _
&H5b9cca4f, &H682e6ff3, &H748f82ee, &H78a5636f, &H84c87814, &H8cc70208, _
&H90befffa, &Ha4506ceb, &Hbef9a3f7, &Hc67178f2 }
Dim As Uinteger<32> h0 = &H6a09e667
Dim As Uinteger<32> h1 = &Hbb67ae85
Dim As Uinteger<32> h2 = &H3c6ef372
Dim As Uinteger<32> h3 = &Ha54ff53a
Dim As Uinteger<32> h4 = &H510e527f
Dim As Uinteger<32> h5 = &H9b05688c
Dim As Uinteger<32> h6 = &H1f83d9ab
Dim As Uinteger<32> h7 = &H5be0cd19
Dim As Uinteger<32> a, b, c, d, e, f, g, h
Dim As Uinteger<32> t1, t2, w(0 To 63)
For j = 0 To (l1 -1) \ 64 ' split into block of 64 bytes
ww1 = Cast(Ubyte Ptr, @message[j * 64])
ww4 = Cast(Uinteger<32> Ptr, @message[j * 64])
For i = 0 To 60 Step 4 'little endian -> big endian
Swap ww1[i ], ww1[i +3]
Swap ww1[i +1], ww1[i +2]
Next i
For i = 0 To 15 ' copy the 16 32bit block into the array
W(i) = ww4[i]
Next i
For i = 16 To 63 ' fill the rest of the array
w(i) = sigma3(W(i -2)) + W(i -7) + sigma2(W(i -15)) + W(i -16)
Next i
a = h0 : b = h1 : c = h2 : d = h3 : e = h4 : f = h5 : g = h6 : h = h7
For i = 0 To 63
t1 = h + sigma1(e) + Ch(e, f, g) + K(i) + W(i)
t2 = sigma0(a) + Maj(a, b, c)
h = g : g = f : f = e
e = d + t1
d = c : c = b : b = a
a = t1 + t2
Next i
h0 += a : h1 += b : h2 += c : h3 += d
h4 += e : h5 += f : h6 += g : h7 += h
Next j
Dim As String answer = Hex(h0, 8) + Hex(h1, 8) + Hex(h2, 8) + Hex(h3, 8)
answer += Hex(h4, 8) + Hex(h5, 8) + Hex(h6, 8) + Hex(h7, 8)
Return Lcase(answer)
End Function
Dim t0 As Double = Timer
Dim Shared sha256fp(0 To 2) As String
sha256fp(0) = "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"
sha256fp(1) = "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"
sha256fp(2) = "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"
Sub PrintCode(n As Integer)
Dim As String fp = sha256fp(n)
Dim As Integer c1, c2, c3, c4, c5
For c1 = 97 To 122
For c2 = 97 To 122
For c3 = 97 To 122
For c4 = 97 To 122
For c5 = 97 To 122
If fp = SHA_256(Chr(c1)+Chr(c2)+Chr(c3)+Chr(c4)+Chr(c5)) Then
Print Chr(c1)+Chr(c2)+Chr(c3)+Chr(c4)+Chr(c5); " => "; fp
Exit For, For, For, For, For
End If
Next c5
Next c4
Next c3
Next c2
Next c1
End Sub
For i As Byte= 0 to 2
PrintCode(i)
Next i
Sleep |
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.
| #Haskell | Haskell | import Control.Parallel.Strategies (parMap, rdeepseq)
import Control.DeepSeq (NFData)
import Data.List (maximumBy)
import Data.Function (on)
nums :: [Integer]
nums =
[ 112272537195293
, 112582718962171
, 112272537095293
, 115280098190773
, 115797840077099
, 1099726829285419
]
lowestFactor
:: Integral a
=> a -> a -> a
lowestFactor s n
| even n = 2
| otherwise = head y
where
y =
[ x
| x <- [s .. ceiling . sqrt $ fromIntegral n] ++ [n]
, n `rem` x == 0
, odd x ]
primeFactors
:: Integral a
=> a -> a -> [a]
primeFactors l n = f n l []
where
f n l xs =
if n > 1
then f (n `div` l) (lowestFactor (max l 3) (n `div` l)) (l : xs)
else xs
minPrimes
:: (Control.DeepSeq.NFData a, Integral a)
=> [a] -> (a, [a])
minPrimes ns =
(\(x, y) -> (x, primeFactors y x)) $
maximumBy (compare `on` snd) $ zip ns (parMap rdeepseq (lowestFactor 3) ns)
main :: IO ()
main = print $ minPrimes nums |
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.
| #CLU | CLU | % Split string by whitespace
split = iter (expr: string) yields (string)
own whitespace: string := " \r\n\t"
cur: array[char] := array[char]$[]
for c: char in string$chars(expr) do
if string$indexc(c, whitespace) = 0 then
array[char]$addh(cur, c)
else
if array[char]$empty(cur) then continue end
yield(string$ac2s(cur))
cur := array[char]$[]
end
end
if ~array[char]$empty(cur) then
yield(string$ac2s(cur))
end
end split
% Tokenize a RPN expression
token = oneof[number: real, op: char]
tokens = iter (expr: string) yields (token) signals (parse_error(string))
own operators: string := "+-*/^"
for t: string in split(expr) do
if string$size(t) = 1 cand string$indexc(t[1], operators)~=0 then
yield(token$make_op(t[1]))
else
yield(token$make_number(real$parse(t)))
except when bad_format:
signal parse_error(t)
end
end
end
end tokens
% Print the stack
print_stack = proc (stack: array[real])
po: stream := stream$primary_output()
for num: real in array[real]$elements(stack) do
stream$puts(po, f_form(num, 5, 5) || " ")
end
stream$putl(po, "")
end print_stack
% Evaluate an expression, printing the stack at each point
evaluate_rpn = proc (expr: string) returns (real) signals (parse_error(string), bounds)
stack: array[real] := array[real]$[]
for t: token in tokens(expr) do
tagcase t
tag number (n: real): array[real]$addh(stack, n)
tag op (f: char):
r: real := array[real]$remh(stack)
l: real := array[real]$remh(stack)
n: real
if f='+' then n := l+r
elseif f='-' then n := l-r
elseif f='*' then n := l*r
elseif f='/' then n := l/r
elseif f='^' then n := l**r
end
array[real]$addh(stack, n)
end
print_stack(stack)
end resignal parse_error
return(array[real]$reml(stack))
end evaluate_rpn
start_up = proc ()
po: stream := stream$primary_output()
expr: string := "3 4 2 * 1 5 - 2 3 ^ ^ / +"
stream$putl(po, "Expression: " || expr)
stream$putl(po, "Result: " || f_form(evaluate_rpn(expr), 5, 5))
end start_up |
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.
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. RPN.
AUTHOR. Bill Gunshannon.
INSTALLATION.
DATE-WRITTEN. 9 Feb 2020.
************************************************************
** Program Abstract:
** 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.
************************************************************
DATA DIVISION.
WORKING-STORAGE SECTION.
01 LineIn PIC X(25).
01 IP PIC 99
VALUE 1.
01 CInNum PIC XXXX.
01 Stack PIC S999999V9999999
OCCURS 50 times.
01 SP PIC 99
VALUE 1.
01 Operator PIC X.
01 Value1 PIC S999999V9999999.
01 Value2 PIC S999999V9999999.
01 Result PIC S999999V9999999.
01 Idx PIC 99.
01 FormatNum PIC ZZZZZZ9.9999999.
01 Zip PIC X.
PROCEDURE DIVISION.
Main-Program.
DISPLAY "Enter the RPN Equation: "
WITH NO ADVANCING.
ACCEPT LineIn.
PERFORM UNTIL IP GREATER THAN
FUNCTION STORED-CHAR-LENGTH(LineIn)
UNSTRING LineIn DELIMITED BY SPACE INTO CInNum
WITH POINTER IP
MOVE CInNum TO Operator
PERFORM Do-Operation
PERFORM Show-Stack
END-PERFORM.
DISPLAY "End Result: " FormatNum
STOP RUN.
Do-Operation.
EVALUATE Operator
WHEN "+"
PERFORM Pop
Compute Result = Value2 + Value1
PERFORM Push
WHEN "-"
PERFORM Pop
Compute Result = Value2 - Value1
PERFORM Push
WHEN "*"
PERFORM Pop
Compute Result = Value2 * Value1
PERFORM Push
WHEN "/"
PERFORM Pop
Compute Result = Value2 / Value1
PERFORM Push
WHEN "^"
PERFORM Pop
Compute Result = Value2 ** Value1
PERFORM Push
WHEN NUMERIC
MOVE Operator TO Result
PERFORM Push
END-EVALUATE.
Show-Stack.
DISPLAY "STACK: " WITH NO ADVANCING.
MOVE 1 TO Idx.
PERFORM UNTIL (Idx = SP)
MOVE Stack(Idx) TO FormatNum
IF Stack(Idx) IS NEGATIVE
THEN
DISPLAY " -" FUNCTION TRIM(FormatNum)
WITH NO ADVANCING
ELSE
DISPLAY FormatNum WITH NO ADVANCING
END-IF
ADD 1 to Idx
END-PERFORM.
DISPLAY " ".
Push.
MOVE Result TO Stack(SP)
ADD 1 TO SP.
Pop.
SUBTRACT 1 FROM SP
MOVE Stack(SP) TO Value1
SUBTRACT 1 FROM SP
MOVE Stack(SP) TO Value2.
END-PROGRAM.
|
http://rosettacode.org/wiki/Pancake_numbers | Pancake numbers | Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.
The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.
Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)?
Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).
References
Bill Gates and the pancake problem
A058986
| #Ring | Ring |
for n = 1 to 9
see "p(" + n + ") = " + pancake(n) + nl
next
return 0
func pancake(n)
gap = 2
sum = 2
adj = -1;
while (sum < n)
adj = adj + 1
gap = gap * 2 - 1
sum = sum + gap
end
return n + adj
|
http://rosettacode.org/wiki/Pancake_numbers | Pancake numbers | Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.
The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.
Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)?
Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).
References
Bill Gates and the pancake problem
A058986
| #Ruby | Ruby | def pancake(n)
gap = 2
sum = 2
adj = -1
while sum < n
adj = adj + 1
gap = gap * 2 - 1
sum = sum + gap
end
return n + adj
end
for i in 0 .. 3
for j in 1 .. 5
n = i * 5 + j
print "p(%2d) = %2d " % [n, pancake(n)]
end
print "\n"
end |
http://rosettacode.org/wiki/Pancake_numbers | Pancake numbers | Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.
The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.
Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)?
Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).
References
Bill Gates and the pancake problem
A058986
| #Wren | Wren | import "/fmt" for Fmt
var pancake = Fn.new { |n|
var gap = 2
var sum = 2
var adj = -1
while (sum < n) {
adj = adj + 1
gap = gap*2 - 1
sum = sum + gap
}
return n + adj
}
for (i in 0..3) {
for (j in 1..5) {
var n = i*5 + j
Fmt.write("p($2d) = $2d ", n, pancake.call(n))
}
System.print()
} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | F is_palindrome(s)
R s == reversed(s) |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Crystal | Crystal | def palindromesgapful(digit, pow)
r1 = (10_u64**pow + 1) * digit
r2 = 10_u64**pow * (digit + 1)
nn = digit * 11
(r1...r2).select { |i| n = i.to_s; n == n.reverse && i.divisible_by?(nn) }
end
def digitscount(digit, count)
pow = 2
nums = [] of UInt64
while nums.size < count
nums += palindromesgapful(digit, pow)
pow += 1
end
nums[0...count]
end
count = 20
puts "First 20 palindromic gapful numbers ending with:"
(1..9).each { |digit| print "#{digit} : #{digitscount(digit, count)}\n" }
count = 100
puts "\nLast 15 of first 100 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "#{digit} : #{digitscount(digit, count).last(15)}\n" }
count = 1000
puts "\nLast 10 of first 1000 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "#{digit} : #{digitscount(digit, count).last(10)}\n" } |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
infix := "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
printf("Infix = %i\n",infix)
printf("RPN = %i\n",Infix2RPN(infix))
end
link printf
record op_info(pr,as) # p=precedence, a=associativity (left=null)
procedure Infix2RPN(expr) #: Infix to RPN parser - shunting yard
static oi
initial {
oi := table() # precedence & associativity
every oi[!"+-"] := op_info(2) # 2L
every oi[!"*/"] := op_info(3) # 3L
oi["^"] := op_info(4,1) # 4R
}
ostack := [] # operator stack
rpn := "" # rpn
pat := sprintf("%%5s : %%-%ds : %%s\n",*expr) # fmt
printf(pat,"Token","Output","Op Stack") # header
expr ? until pos(0) do { # while tokens
tab(many(' ')) # consume any seperator
token := tab(upto(' ')|0) # get token
printf(pat,token,rpn,list2string(ostack)) # report
if token := numeric(token) then # ... numeric
rpn ||:= token || " "
else
if member(oi,token) then { # ... operator
while member(oi,op2 := ostack[1]) &
( /oi[token].as & oi[token].pr <= oi[op2].pr ) |
( \oi[token].as & oi[token].pr < oi[op2].pr ) do
rpn ||:= pop(ostack) || " "
push(ostack,token)
}
else # ... parenthesis
if token == "(" then
push(ostack,token)
else if token == ")" then {
until ostack[1] == "(" do
rpn ||:= pop(ostack) || " " |
stop("Unbalanced parenthesis")
pop(ostack) # discard "("
}
}
while token := pop(ostack) do # ... input exhausted
if token == ("("|")") then stop("Unbalanced parenthesis")
else {
rpn ||:= token || " "
printf(pat,"",rpn,list2string(ostack))
}
return rpn
end
procedure list2string(L) #: format list as a string
every (s := "[ ") ||:= !L || " "
return s || "]"
end |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #Java | Java | import java.math.BigInteger;
import java.util.Arrays;
class Test {
final static int nMax = 250;
final static int nBranches = 4;
static BigInteger[] rooted = new BigInteger[nMax + 1];
static BigInteger[] unrooted = new BigInteger[nMax + 1];
static BigInteger[] c = new BigInteger[nBranches];
static void tree(int br, int n, int l, int inSum, BigInteger cnt) {
int sum = inSum;
for (int b = br + 1; b <= nBranches; b++) {
sum += n;
if (sum > nMax || (l * 2 >= sum && b >= nBranches))
return;
BigInteger tmp = rooted[n];
if (b == br + 1) {
c[br] = tmp.multiply(cnt);
} else {
c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1)));
c[br] = c[br].divide(BigInteger.valueOf(b - br));
}
if (l * 2 < sum)
unrooted[sum] = unrooted[sum].add(c[br]);
if (b < nBranches)
rooted[sum] = rooted[sum].add(c[br]);
for (int m = n - 1; m > 0; m--)
tree(b, m, l, sum, c[br]);
}
}
static void bicenter(int s) {
if ((s & 1) == 0) {
BigInteger tmp = rooted[s / 2];
tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]);
unrooted[s] = unrooted[s].add(tmp.shiftRight(1));
}
}
public static void main(String[] args) {
Arrays.fill(rooted, BigInteger.ZERO);
Arrays.fill(unrooted, BigInteger.ZERO);
rooted[0] = rooted[1] = BigInteger.ONE;
unrooted[0] = unrooted[1] = BigInteger.ONE;
for (int n = 1; n <= nMax; n++) {
tree(0, n, n, 1, BigInteger.ONE);
bicenter(n);
System.out.printf("%d: %s%n", n, unrooted[n]);
}
}
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #AutoHotkey | AutoHotkey | Gui, -MinimizeBox
Gui, Add, Edit, w300 r5 vText
Gui, Add, Button, x105 w100 Default, Check Pangram
Gui, Show,, Pangram Checker
Return
GuiClose:
ExitApp
Return
ButtonCheckPangram:
Gui, Submit, NoHide
Loop, 26
If Not InStr(Text, Char := Chr(64 + A_Index)) {
MsgBox,, Pangram, Character %Char% is missing!
Return
}
MsgBox,, Pangram, OK`, this is a Pangram!
Return |
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.
| #Factor | Factor | USING: arrays fry io kernel math math.combinatorics
math.matrices prettyprint sequences ;
: pascal ( n quot -- m )
[ dup 2array <coordinate-matrix> ] dip
'[ first2 @ nCk ] matrix-map ; inline
: lower ( n -- m ) [ ] pascal ;
: upper ( n -- m ) lower flip ;
: symmetric ( n -- m ) [ [ + ] keep ] pascal ;
5
[ lower "Lower:" ]
[ upper "Upper:" ]
[ symmetric "Symmetric:" ] tri
[ print simple-table. nl ] 2tri@ |
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. | #Perl | Perl | use DBI;
my $db = DBI->connect('DBI:mysql:mydatabase:host','login','password');
$statment = $db->prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?");
$rows_affected = $statment->execute("Smith, Steve",42,'true',99); |
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. | #Phix | Phix | --
-- demo\rosetta\Parameterized_SQL_statement.exw
-- ============================================
--
without js -- (pSQLite)
include pSQLite.e
--<some pretty printing, not really part of the demo>
constant {coltypes,colfmts,colrids} = columnize({
{SQLITE_INTEGER,"%4d",sqlite3_column_int},
{SQLITE_FLOAT,"%4g",sqlite3_column_double},
{SQLITE_TEXT,"%-20s",sqlite3_column_text}})
procedure show(string what, sqlite3 db)
printf(1,"%s:\n",{what})
sqlite3_stmt pStmt = sqlite3_prepare(db,"SELECT * FROM players;")
while 1 do
integer res = sqlite3_step(pStmt)
if res=SQLITE_DONE then exit end if
assert(res=SQLITE_ROW)
string text = ""
for c=1 to sqlite3_column_count(pStmt) do
integer ctype = sqlite3_column_type(pStmt,c),
cdx = find(ctype,coltypes),
rid = colrids[cdx]
string name = sqlite3_column_name(pStmt,c),
data = sprintf(colfmts[cdx],rid(pStmt,c))
text &= sprintf(" %s:%s",{name,data})
end for
printf(1,"%s\n",{text})
end while
assert(sqlite3_finalize(pStmt)=SQLITE_OK)
end procedure
--</pretty printing>
sqlite3 db = sqlite3_open(":memory:")
assert(sqlite3_exec(db,`create table players (name, score, active, jerseyNum)`)=SQLITE_OK)
assert(sqlite3_exec(db,`insert into players values ('Roethlisberger, Ben', 94.1, 1, 7 )`)=SQLITE_OK)
assert(sqlite3_exec(db,`insert into players values ('Smith, Alex', 85.3, 1, 11)`)=SQLITE_OK)
assert(sqlite3_exec(db,`insert into players values ('Doe, John', 15, 0, 99)`)=SQLITE_OK)
assert(sqlite3_exec(db,`insert into players values ('Manning, Payton', 96.5, 0, 123)`)=SQLITE_OK)
show("Before",db)
--pp({"Before",sqlite3_get_table(db, "select * from players")},{pp_Nest,2})
-- For comparison against some other entries, this is how you would do numbered parameters:
--/*
sqlite3_stmt pStmt = sqlite3_prepare(db, `update players set name=?, score=?, active=? where jerseyNum=?`)
sqlite3_bind_text(pStmt,1,"Smith, Steve")
sqlite3_bind_double(pStmt,2,42)
sqlite3_bind_int(pStmt,3,true)
sqlite3_bind_int(pStmt,4,99)
--*/
-- However, ordinarily I would prefer named parameters and sqlbind_parameter_index() calls:
sqlite3_stmt pStmt = sqlite3_prepare(db, `update players set name=:name, score=:score, active=:active where jerseyNum=:jerseyn`)
constant k_name = sqlite3_bind_parameter_index(pStmt, ":name"),
k_score = sqlite3_bind_parameter_index(pStmt, ":score"),
k_active = sqlite3_bind_parameter_index(pStmt, ":active"),
k_jerseyn = sqlite3_bind_parameter_index(pStmt, ":jerseyn")
sqlite3_bind_text(pStmt,k_name,"Smith, Steve")
sqlite3_bind_double(pStmt,k_score,42)
sqlite3_bind_int(pStmt,k_active,true)
sqlite3_bind_int(pStmt,k_jerseyn,99)
assert(sqlite3_step(pStmt)=SQLITE_DONE)
assert(sqlite3_finalize(pStmt)=SQLITE_OK)
show("After",db)
--pp({"After",sqlite3_get_table(db, "select * from players")},{pp_Nest,2})
sqlite3_close(db)
|
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
| #C | C | #include <stdio.h>
void pascaltriangle(unsigned int n)
{
unsigned int c, i, j, k;
for(i=0; i < n; i++) {
c = 1;
for(j=1; j <= 2*(n-1-i); j++) printf(" ");
for(k=0; k <= i; k++) {
printf("%3d ", c);
c = c * (i-k)/(k+1);
}
printf("\n");
}
}
int main()
{
pascaltriangle(8);
return 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.
| #PowerShell | PowerShell |
function Get-IpAddress
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$InputObject
)
Begin
{
function Get-Address ([string]$Address)
{
if ($Address.IndexOf(".") -ne -1)
{
$Address, $port = $Address.Split(":")
[PSCustomObject]@{
IPAddress = [System.Net.IPAddress]$Address
Port = $port
}
}
else
{
if ($Address.IndexOf("[") -ne -1)
{
[PSCustomObject]@{
IPAddress = [System.Net.IPAddress]$Address
Port = ($Address.Split("]")[-1]).TrimStart(":")
}
}
else
{
[PSCustomObject]@{
IPAddress = [System.Net.IPAddress]$Address
Port = $null
}
}
}
}
}
Process
{
$InputObject | ForEach-Object {
$address = Get-Address $_
$bytes = ([System.Net.IPAddress]$address.IPAddress).GetAddressBytes()
[Array]::Reverse($bytes)
$i = 0
$bytes | ForEach-Object -Begin {[bigint]$decimalIP = 0} `
-Process {$decimalIP += [bigint]$_ * [bigint]::Pow(256, $i); $i++} `
-End {[PSCustomObject]@{
Address = $address.IPAddress
Port = $address.Port
Hex = "0x$($decimalIP.ToString('x'))"}
}
}
}
}
|
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.
| #Standard_ML | Standard ML | datatype 'a tree = Empty | Node of 'a * 'a tree * 'a tree
(** val map_tree = fn : ('a -> 'b) -> 'a tree -> 'b tree *)
fun map_tree f Empty = Empty
| map_tree f (Node (x,l,r)) = Node (f x, map_tree f l, map_tree 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.
| #Swift | Swift | class Tree<T> {
var value: T?
var left: Tree<T>?
var right: Tree<T>?
func replaceAll(value: T?) {
self.value = value
left?.replaceAll(value)
right?.replaceAll(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.
| #Ursala | Ursala | binary_tree_of "node-type" = "node-type"%hhhhWZAZ |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Class BinaryTree(Of T)
ReadOnly Property Left As BinaryTree(Of T)
ReadOnly Property Right As BinaryTree(Of T)
ReadOnly Property Value As T
Sub New(value As T, Optional left As BinaryTree(Of T) = Nothing, Optional right As BinaryTree(Of T) = Nothing)
Me.Value = value
Me.Left = left
Me.Right = right
End Sub
Function Map(Of U)(f As Func(Of T, U)) As BinaryTree(Of U)
Return New BinaryTree(Of U)(f(Me.Value), Me.Left?.Map(f), Me.Right?.Map(f))
End Function
Overrides Function ToString() As String
Dim sb As New Text.StringBuilder()
Me.ToString(sb, 0)
Return sb.ToString()
End Function
Private Overloads Sub ToString(sb As Text.StringBuilder, depth As Integer)
sb.Append(New String(ChrW(AscW(vbTab)), depth))
sb.AppendLine(Me.Value?.ToString())
Me.Left?.ToString(sb, depth + 1)
Me.Right?.ToString(sb, depth + 1)
End Sub
End Class
Module Program
Sub Main()
Dim b As New BinaryTree(Of Integer)(6, New BinaryTree(Of Integer)(5), New BinaryTree(Of Integer)(7))
Dim b2 As BinaryTree(Of Double) = b.Map(Function(x) x * 0.5)
Console.WriteLine(b)
Console.WriteLine(b2)
End Sub
End Module |
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.
| #J | J | tokenize=: ' ' <;._1@, deb
ops=: ;:'+ - * / ^'
doOp=: plus`minus`times`divide`exponent`push@.(ops&i.)
parse=:3 :0
stack=: i.0 2
for_token.tokenize y do.doOp token end.
1{:: ,stack
)
parens=:4 :0
if. y do. '( ',x,' )' else. x end.
)
NB. m: precedence, n: is right associative, y: token
op=:2 :0
L=. m - n
R=. m - -.n
smoutput;'operation: ';y
'Lprec left Rprec right'=. ,_2{.stack
expr=. ;(left parens L > Lprec);' ';y,' ';right parens R > Rprec
stack=: (_2}.stack),m;expr
smoutput stack
)
plus=: 2 op 0
minus=: 2 op 0
times=: 3 op 0
divide=: 3 op 0
exponent=: 4 op 1
push=:3 :0
smoutput;'pushing: ';y
stack=: stack,_;y
smoutput stack
) |
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.
| #Lambdatalk | Lambdatalk |
1) just define function as usual:
{def add {lambda {:a :b :c} {+ :a :b :c}}} -> add
2) and use it:
{add 1 2 3} -> 6
{{add 1} 2 3} -> 6
{{add 1 2} 3} -> 6
{{{add 1} 2} 3} -> 6
3) application:
{def fs {lambda {:f} map :f}}
{def f1 {lambda {:x} {* :x 2}}}
{def f2 {lambda {:x} {pow :x 2}}}
{def fsf1 {fs f1}}
{def fsf2 {fs f2}}
{{fsf1} 0 1 2 3}
{{fsf2} 0 1 2 3}
{{fsf1} 2 4 6 8}
{{fsf2} 2 4 6 8}
Output:
0 2 4 6
0 1 4 9
4 8 12 16
4 16 36 64
|
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
| #Sidef | Sidef | func prime_partition(num, parts) {
if (parts == 1) {
return (num.is_prime ? [num] : [])
}
num.primes.combinations(parts, {|*c|
return c if (c.sum == num)
})
return []
}
var tests = [
[ 18, 2], [ 19, 3], [ 20, 4],
[99807, 1], [99809, 1], [ 2017, 24],
[22699, 1], [22699, 2], [22699, 3],
[22699, 4], [40355, 3],
]
for num,parts (tests) {
say ("Partition %5d into %2d prime piece" % (num, parts),
parts == 1 ? ': ' : 's: ', prime_partition(num, parts).join('+') || 'not possible')
} |
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.
| #Ruby | Ruby | require 'rref'
pyramid = [
[ 151],
[nil,nil],
[40,nil,nil],
[nil,nil,nil,nil],
["x", 11,"y", 4,"z"]
]
pyramid.each{|row| p row}
equations = [[1,-1,1,0]] # y = x + z
def parse_equation(str)
eqn = [0] * 4
lhs, rhs = str.split("=")
eqn[3] = rhs.to_i
for term in lhs.split("+")
case term
when "x" then eqn[0] += 1
when "y" then eqn[1] += 1
when "z" then eqn[2] += 1
else eqn[3] -= term.to_i
end
end
eqn
end
-2.downto(-5) do |row|
pyramid[row].each_index do |col|
val = pyramid[row][col]
sum = "%s+%s" % [pyramid[row+1][col], pyramid[row+1][col+1]]
if val.nil?
pyramid[row][col] = sum
else
equations << parse_equation(sum + "=#{val}")
end
end
end
reduced = convert_to(reduced_row_echelon_form(equations), :to_i)
for eqn in reduced
if eqn[0] + eqn[1] + eqn[2] != 1
fail "no unique solution! #{equations.inspect} ==> #{reduced.inspect}"
elsif eqn[0] == 1 then x = eqn[3]
elsif eqn[1] == 1 then y = eqn[3]
elsif eqn[2] == 1 then z = eqn[3]
end
end
puts
puts "x == #{x}"
puts "y == #{y}"
puts "z == #{z}"
answer = []
for row in pyramid
answer << row.collect {|cell| eval cell.to_s}
end
puts
answer.each{|row| p row} |
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
| #Pascal | Pascal |
program passwords (input,output);
{$mode objfpc}
{$H+} { We will need ansi strings instead of short strings
to hold passwords longer than 255 characters.
We need to assemble a string to check that each
password contains an upper, lower, numeral and symbol }
{ This is a random password generater in PASCAL
Copyright Englebert Finklestien on this day which is
Setting Orange day 48 of The Aftermath YOLD 3184.
It is distributed under the terms of the GNU GPL (v3)
As published by the free software foundation.
Usage :-
Without any command line arguments this program
will display 8 8-character long completely random passwords using
all 96 available character glyphs from the basic ascii set.
With a single integer numerical argument it will
produce eight passwords of the chosen length.
With a second integer numerical argument between 1 and 65536 it
will produce that number of passwords.
With two integer arguments the first is taken as the length of password
and the second as the number of passwords to produce.
The length of passwords can also be specified using -l or --length options
The number of passwords can also be specified using -n or --number options
It is also possible to exclude those glyphs which are simmilar enough to be
confused (e.g. O and 0) using the -e or --exclude option
There are also the standard -a --about and -h --help options
Other options will produce an error message and the program will halt without
producing any passwords at all.
}
uses sysutils, getopts;
var c : char;
optionindex : Longint;
theopts : array[1..5] of TOption;
numpass, lenpass, count,j : integer;
i : longint; { used to get a random number }
strength : byte; { check inclusion of different character groups }
password : string; { To hold a password as we generate it }
exc : boolean;
ex : set of char;
procedure about;
begin
writeln('Engleberts random password generator');
writeln('Writen in FreePascal on Linux');
writeln('This is free software distributed under the GNU GPL v3');
writeln;
end;
procedure help;
begin
writeln('Useage:-');
writeln('passwords produce 8 passwords each 8 characters long.');
writeln('Use one or more of the following switches to control the output.');
writeln('passwords --number=xx -nxx --length=xx -lxx --exclude -e --about -a --help -h');
writeln('passwords ll nn produce nn passwords of length ll');
writeln('The exclude option excludes easily confused characters such as `0` and `O` from');
writeln('the generated passwords.');
writeln;
end;
begin
numpass := 8;
lenpass := 8;
exc := False;
ex := ['1','!','l','|','i','I','J','0','O','S','$','5',';',':',',','.','\']; { Set of ambiguous characters }
OptErr := True;
Randomize; {initialise the random number generator}
{set up to handle the command line options}
with theopts[1] do
begin
name:='length';
has_arg:=1;
flag:=nil;
value:=#0;
end;
with theopts[2] do
begin
name:='number';
has_arg:=1;
flag:=nil;
value:=#0;
end;
with theopts[3] do
begin
name:='help';
has_arg:=0;
flag:=nil;
value:=#0;
end;
with theopts[4] do
begin
name:='about';
has_arg:=0;
flag:=nil;
value:=#0;
end;
with theopts[5] do
begin
name:='exclude';
has_arg:=0;
flag:=nil;
value:=#0;
end;
{ Get and process long and short versions of command line args. }
c:=#0;
repeat
c:=getlongopts('ahel:n:t:',@theopts[1],optionindex);
case c of
#0 : begin
if (theopts[optionindex].name = 'exclude') then exc := True;
if (theopts[optionindex].name = 'length') then lenpass := StrtoInt(optarg);
if (theopts[optionindex].name = 'number') then numpass := StrtoInt(optarg);
if (theopts[optionindex].name = 'about') then about;
if (theopts[optionindex].name = 'help') then help;
end;
'a' : about;
'h' : help;
'e' : exc := True;
'l' : lenpass := StrtoInt(optarg);
'n' : numpass := StrtoInt(optarg);
'?',':' : writeln ('Error with opt : ',optopt);
end; { case }
until c=endofoptions;
{ deal with any remaining command line parameters (two integers)}
if optind<=paramcount then
begin
count:=1;
while optind<=paramcount do
begin
if (count=1) then lenpass := StrtoInt(paramstr(optind)) else numpass := StrtoInt(paramstr(optind));
inc(optind);
inc(count);
end;
end;
if not (exc) then ex :=['\']; { if we are not going to exclude characters set the exclusion set to almost empty }
{ This generates and displays the actual passwords }
for count := 1 to numpass do begin
strength := $00;
repeat
password :='';
for j:= 1 to lenpass do begin
repeat
i:=Random(130);
until (i>32) and (i<127) and (not(chr(i) in ex)) ;
AppendStr(password,chr(i));
if (CHR(i) in ['0'..'9']) then strength := strength or $01;
if (chr(i) in ['a'..'z']) then strength := strength or $02;
if (chr(i) in ['A'..'Z']) then strength := strength or $04;
if (chr(i) in ['!'..'/']) then strength := strength or $08;
if (chr(i) in [':'..'@']) then strength := strength or $08;
if (chr(i) in ['['..'`']) then strength := strength or $08;
if (chr(i) in ['{'..'~']) then strength := strength or $08;
end;
until strength = $0f;
writeln(password);
end;
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
| #Yabasic | Yabasic | n = 4
dim a(n), c(n)
for j = 1 to n : a(j) = j : next j
repeat
for i = 1 to n: print a(i);: next: print
i = n
repeat
i = i - 1
until (i = 0) or (a(i) < a(i+1))
j = i + 1
k = n
while j < k
tmp = a(j) : a(j) = a(k) : a(k) = tmp
j = j + 1
k = k - 1
wend
if i > 0 then
j = i + 1
while a(j) < a(i)
j = j + 1
wend
tmp = a(j) : a(j) = a(i) : a(i) = tmp
endif
until i = 0
end |
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
| #Frink | Frink | hashes = new set["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"]
r = new range["a", "z"]
multifor array = [r,r,r,r,r]
{
str = join["", array]
hash = messageDigest[str, "SHA-256"]
if hashes.contains[hash]
println["$str: $hash"]
} |
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
| #Go | Go | package main
import (
"crypto/sha256"
"encoding/hex"
"log"
"sync"
)
var hh = []string{
"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f",
}
func main() {
log.SetFlags(0)
hd := make([][sha256.Size]byte, len(hh))
for i, h := range hh {
hex.Decode(hd[i][:], []byte(h))
}
var wg sync.WaitGroup
wg.Add(26)
for c := byte('a'); c <= 'z'; c++ {
go bf4(c, hd, &wg)
}
wg.Wait()
}
func bf4(c byte, hd [][sha256.Size]byte, wg *sync.WaitGroup) {
p := []byte("aaaaa")
p[0] = c
p1 := p[1:]
p:
for {
ph := sha256.Sum256(p)
for i, h := range hd {
if h == ph {
log.Println(string(p), hh[i])
}
}
for i, v := range p1 {
if v < 'z' {
p1[i]++
continue p
}
p1[i] = 'a'
}
wg.Done()
return
}
} |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
threads := []
L := list(*A)
every i := 1 to *A do put(threads, thread L[i] := primedecomp(A[i]))
every wait(!threads)
maxminF := L[maxminI := 1][1]
every i := 2 to *L do if maxminF <:= L[i][1] then maxminI := i
every writes((A[maxminI]||": ")|(!L[maxminI]||" ")|"\n")
end
procedure primedecomp(n) #: return a list of factors
every put(F := [], genfactors(n))
return F
end
link factors
|
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.
| #J | J | numbers =. 12757923 12878611 12878893 12757923 15808973 15780709 197622519
factors =. q:&.> parallelize 2 numbers NB. q: is parallelized here
ind =. (i. >./) <./@> factors
ind { numbers ;"_1 factors
┌────────┬───────────┐
│12878611│47 101 2713│
└────────┴───────────┘ |
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.
| #Common_Lisp | Common Lisp | (setf (symbol-function '^) #'expt) ; Make ^ an alias for EXPT
(defun print-stack (token stack)
(format T "~a: ~{~a ~}~%" token (reverse stack)))
(defun rpn (tokens &key stack verbose )
(cond
((and (not tokens) (not stack)) 0)
((not tokens) (car stack))
(T
(let* ((current (car tokens))
(next-stack (if (numberp current)
(cons current stack)
(let* ((arg2 (car stack))
(arg1 (cadr stack))
(fun (car tokens)))
(cons (funcall fun arg1 arg2) (cddr stack))))))
(when verbose
(print-stack current next-stack))
(rpn (cdr tokens) :stack next-stack :verbose verbose))))) |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #360_Assembly | 360 Assembly | * Reverse b string 25/06/2018
PALINDRO CSECT
USING PALINDRO,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
LA R8,BB @b[1]
LA R9,AA+L'AA-1 @a[n-1]
LA R6,1 i=1
LOOPI C R6,=A(L'AA) do i=1 to length(a)
BH ELOOPI leave i
MVC 0(1,R8),0(R9) substr(b,i,1)=substr(a,n-i+1,1)
LA R8,1(R8) @b=@b+1
BCTR R9,0 @a=@a-1
LA R6,1(R6) i=i+1
B LOOPI end do
ELOOPI XPRNT AA,L'AA print a
CLC BB,AA if b=a
BNE SKIP
XPRNT MSG,L'MSG then print msg
SKIP L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
AA DC CL32'INGIRUMIMUSNOCTEETCONSUMIMURIGNI' a
BB DS CL(L'AA) b
MSG DC CL23'IT IS A TRUE PALINDROME'
YREGS
END PALINDRO |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #F.23 | F# |
// Palindromic Gapful Numbers . Nigel Galloway: December 3rd., 2020
let rec fN g l=seq{match l with 3->yield! seq{for n in 0L..9L->g*100L+g+n*10L}
|4->yield! seq{for n in 0L..9L->g*1000L+g+n*110L}
|_->yield! seq{for n in 0L..9L do for i in fN n (l-2)->i*10L+g+g*(pown 10L (l-1))}}
let rcGf n=let rec rcGf g=seq{yield! fN n g|>Seq.filter(fun g->g%(10L*n+n)=0L); yield! rcGf(g+1)} in rcGf 3
[1L..9L]|>Seq.iter(fun n->rcGf n|>Seq.take 20|>Seq.iter(printf "%d ");printfn "");printfn "#####"
[1L..9L]|>Seq.iter(fun n->rcGf n|>Seq.skip 85|>Seq.take 15|>Seq.iter(printf "%d ");printfn "");printfn "#####"
[1L..9L]|>Seq.iter(fun n->rcGf n|>Seq.skip 990|>Seq.take 10|>Seq.iter(printf "%d ");printfn "");printfn "#####"
|
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.
| #J | J |
NB. j does not have a verb based precedence.
NB. j evaluates verb noun sequences from right to left.
NB. Seriously. 18 precedence levels in C++ .
display=: ([: : (smoutput@:(, [: ; ' '&,&.>@:{:@:|:))) :: empty
Display=: adverb define
:
m display^:(0 -.@:-: x)y
)
NB. Queue, Stack, Pop: m literal name of vector to use. verbose unless x is 0.
NB. Implementation includes display, group push and pop not available in the RC FIFO & LIFO pages
NB. As adverbs, these definitions work with any global variable.
NB. Pop needs the feature, and it helps with display as well.
Queue=: adverb define NB. enqueue y
('m'~)=: y ,~ (m~)
EMPTY
:
x (m,' queue')Display y
m Queue y
)
Stack=: adverb define NB. Stack y
('m'~)=: (|.y) , (m~)
EMPTY
:
x (m,' stack')Display y
m Stack y
)
Pop=: adverb define NB. Pop y items
0 m Pop y
:
y=. 0 {:@:, y NB. if y is empty use 0 instead
rv=. y {. (m~)
('m'~)=: y }. (m~)
x (m,' pop') Display rv
rv
)
NB. tests
TEST=: ''
'TEST'Stack'abc'
'TEST'Stack'de'
assert 'edc' -: 'TEST'Pop 3
assert 'ba' -: 'TEST'Pop 2
assert 0 (= #) TEST
'TEST'Queue'abc'
'TEST'Queue'de'
assert 'ab' -: 'TEST'Pop 2
assert 'cde' -: 'TEST'Pop 3
assert 0 (= #) TEST
any=: +./
DIGITS=: a. {~ 48+i.10 NB. ASCII 48--57
precedence_oppression=: <;._1' +- */ ^ ( ) ',DIGITS
associativity=: 'xLLRxxL'
classify=: {:@:I.@:(1 , any@e.&>)&precedence_oppression
NB. The required tokens are also tokens in j.
NB. Use the default sequential machine ;: for lexical analysis.
rclex=: (;~ classify)"0@:;:
NB. numbers can be treated as highest precedence operators
number=: Q Queue NB. put numbers onto the output queue
left=: S Stack NB. push left paren onto the stack
NB. Until the token at the top of the stack is (, pop
NB. operators off the stack onto the output queue.
NB. Pop the left parenthesis from the stack, but not onto the output queue.
right=: 4 : 0 NB. If the token is a right parenthesis:
i=. (S~) (i. rclex) '('
if. i (= #) S~ do.
smoutput'Check your parens!'
throw.
end.
x Q Queue x S Pop i
x S Pop 1
EMPTY
)
NB. If the token is an operator, o1, then:
NB.
NB. while there is an operator token, o2, at the top of the stack, and
NB. either o1 is [[left-associative and its precedence is less than or
NB. equal to that of o2]]"L*.<:", or o1 is [[right-associative and its precedence
NB. is less than that of o2]]"R*.<", pop o2 off the stack, onto the output queue;
NB. [[the tally of adjacent leading truths]]"NCT"
NB.
NB. push o1 onto the stack.
o=: 4 : 0
P=. 0 0 {:: y
L=. 'L' = P { associativity
operators=. ({.~ i.&(rclex'(')) S~
NB. NCT L*.<: or R*.<
i=. (+/@:(*./\)@:((L *. P&<:) +. ((-.L) *. P&<))@:(0&{::"1)) :: 0: operators
x Q Queue x S Pop i
x (S Stack) y
EMPTY
)
NB. terminating version of invalid
invalid=: 4 : 0
smoutput 'invalid token ',0 1 {:: y
throw.
)
NB. demonstrated invalid
invalid=: [: smoutput 'discarding invalid token ' , 0 1 {:: ]
NB. shunt_yard is a verb to implement shunt-yard parsing.
NB. verbose defaults to 0. (quiet)
NB. use: verbosity shunt_yard_parse algebraic_string
shunt_yard_parse=: 0&$: : (4 : 0)
NB. j's data structure is array. Rank 1 arrays (vectors)
NB. are just right for the stack and output queue.
'S Q'=: ;: 'OPERATOR OUTPUT'
('S'~)=:('Q'~)=: i.0 2
NB. Follow agenda for all tokens, result saved on global OUTPUT variable
x (invalid`o`o`o`left`right`number@.(0 0 {:: ])"2 ,:"1@:rclex) y
NB. x (invalid`o`o`o`left`right`o@.(0 0 {:: ])"2 ,:"1@:rclex) y NB. numbers can be treated as operators
NB. check for junk on stack
if. (rclex'(') e. S~ do.
smoutput'Check your other parens!'
throw.
end.
NB. shift remaining operators onto the output queue
x Q Queue x S Pop # S~
NB. return the output queue
Q~
)
algebra_to_rpn=: {:@:|:@:shunt_yard_parse
fulfill_requirement=: ;@:(' '&,&.>)@:algebra_to_rpn
|
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #jq | jq | def MAX_N: 500; # imprecision begins at 46
def BRANCH: 4;
# state: [unrooted, ra]
# tree(br; n; l; sum; cnt) where initially: l=n, sum=1 and cnt=1
def tree(br; n; l; sum; cnt):
# The inner function is used to implement the range(b+1; BRANCH) loop
# as there are early exits.
# On completion, _tree returns [unrooted, ra]
def _tree: # state [ (b, c, sum), (unrooted, ra)]
if length != 5 then error("_tree input has length \(length)") else . end
| .[0] as $b | .[1] as $c | .[2] as $sum | .[3] as $unrooted | .[4] as $ra
| if $b > BRANCH then [$unrooted, $ra]
else
($sum + n) as $sum
| if $sum >= MAX_N or
# prevent unneeded long math
( l * 2 >= $sum and $b >= BRANCH) then [$unrooted, $ra] # return
else (if $b == br + 1 then $ra[n] * cnt
else ($c * ($ra[n] + (($b - br - 1)))) / ($b - br) | floor
end) as $c
| (if l * 2 < $sum then ($unrooted | .[$sum] += $c)
else $unrooted end) as $unrooted
| if $b >= BRANCH then [$b+1, $c, $sum, $unrooted, $ra] | _tree # next
else [$unrooted, ($ra | .[$sum] += $c) ]
| reduce range(1; n) as $m (.; tree($b; $m; l; $sum; $c))
| ([$b + 1, $c, $sum] + .) | _tree
end
end
end
;
# start by incrementing b, and prepending values for (b,c,sum)
([br+1, cnt, sum] + .) | _tree
;
# input and output: [unrooted, ra]
def bicenter(s):
if s % 2 == 1 then .
else
.[1][s / 2] as $aux
| .[0][s] += ($aux * ($aux + 1)) / 2 # 2 divides odd*even
end
;
def array(n;init): [][n-1] = init | map(init);
def ra: array( MAX_N; 0) | .[0] = 1 | .[1] = 1;
def unrooted: ra;
# See below for a simpler implementation using "foreach"
def paraffins:
# range(1; MAX_N)
def _paraffins(n):
if n >= MAX_N then empty
else tree(0; n; n; 1; 1) | bicenter(n)
| [n, .[0][n]], # output
_paraffins(n+1)
end;
[unrooted, ra] | _paraffins(1)
;
paraffins |
http://rosettacode.org/wiki/Paraffins | Paraffins |
This organic chemistry task is essentially to implement a tree enumeration algorithm.
Task
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds.
In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with n carbon atoms share the empirical formula CnH2n+2
But for all n ≥ 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when n increases.
In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.
Example
With n = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with n = 4 there are two configurations:
a straight chain: (CH3)(CH2)(CH2)(CH3)
a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.
The input is the number n of carbon atoms of a molecule (for instance 17).
The output is how many different different paraffins there are with n carbon atoms (for instance 24,894 if n = 17).
The sequence of those results is visible in the OEIS entry:
oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
Extra credit
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
│ │ │ │ │ │ │ │ │
H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H
│ │ │ │ │ │ │ │ │
H H H H H H H │ H
│
H ─ C ─ H
│
H
Links
A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| #Julia | Julia | const branches = 4
const nmax = 500
const rooted = zeros(BigInt, nmax + 1)
const unrooted = zeros(BigInt, nmax + 1)
rooted[1] = rooted[2] = unrooted[1] = unrooted[2] = 1
const c = zeros(BigInt, branches)
function tree(br, n, l, sum, cnt)
for b in br+1:branches
sum += n
if (sum > nmax) || (l * 2 >= sum && b >= branches)
return
elseif b == br + 1
c[br + 1] = rooted[n + 1] * cnt
else
c[br + 1] *= rooted[n + 1] + b - br - 1
c[br + 1] = div(c[br + 1], b - br)
end
if l*2 < sum
unrooted[sum + 1] += c[br + 1]
end
if b < branches
rooted[sum + 1] += c[br + 1]
end
for m in n-1:-1:1
tree(b, m, l, sum, c[br + 1])
end
end
end
bicenter(n) = if iseven(n) unrooted[n + 1] += div(rooted[div(n, 2) + 1] * (rooted[div(n, 2) + 1] + 1), 2) end
function paraffins()
for n in 1:nmax
tree(0, n, n, 1, one(BigInt))
bicenter(n)
println("$n: $(unrooted[n + 1])")
end
end
paraffins()
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #AutoIt | AutoIt |
Pangram("The quick brown fox jumps over the lazy dog")
Func Pangram($s_String)
For $i = 1 To 26
IF Not StringInStr($s_String, Chr(64 + $i)) Then
Return MsgBox(0,"No Pangram", "Character " & Chr(64 + $i) &" is missing")
EndIf
Next
Return MsgBox(0,"Pangram", "Sentence is a Pangram")
EndFunc
|
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.
| #Fermat | Fermat | &a; {set mode to 0-indexed matrices}
Func Pasmat( n, t ) =
;{create a Pascal matrix of size n by n}
;{t=0 -> upper triangular, 1 -> lower triangular,2->symmetric}
Array m[n, n]; {result is stored in array m}
if t = 0 then
[m]:=[<i=0,n-1><j=0,n-1> Bin(j,i) ];
fi;
if t = 1 then
[m]:=[<i=0,n-1><j=0,n-1> Bin(i,j) ];
fi;
if t = 2 then
[m]:=[<i=0,n-1><j=0,n-1> Bin(i+j,i) ];
fi;
.;
Pasmat(5, 0);
!!([m);
!;
Pasmat(5, 1);
!!([m);
!;
Pasmat(5, 2);
!!([m); |
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. | #PHP | PHP | $updatePlayers = "UPDATE `players` SET `name` = ?, `score` = ?, `active` = ?\n".
"WHERE `jerseyNum` = ?";
$dbh = new PDO( "mysql:dbname=db;host=localhost", "username", "password" );
$updateStatement = $dbh->prepare( $updatePlayers );
$updateStatement->bindValue( 1, "Smith, Steve", PDO::PARAM_STR );
$updateStatement->bindValue( 2, 42, PDO::PARAM_INT );
$updateStatement->bindValue( 3, 1, PDO::PARAM_INT );
$updateStatement->bindValue( 4, 99, PDO::PARAM_INT );
$updateStatement->execute();
// alternatively pass parameters as an array to the execute method
$updateStatement = $dbh->prepare( $updatePlayers );
$updateStatement->execute( array( "Smith, Steve", 42, 1, 99 ) ); |
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. | #PicoLisp | PicoLisp | (for P (collect 'jerseyNum '+Players 99)
(put!> P 'name "Smith, Steve")
(put!> P 'score 42)
(put!> P 'active T) ) |
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
| #C.23 | C# | using System;
namespace RosettaCode {
class PascalsTriangle {
public static void CreateTriangle(int n) {
if (n > 0) {
for (int i = 0; i < n; i++) {
int c = 1;
Console.Write(" ".PadLeft(2 * (n - 1 - i)));
for (int k = 0; k <= i; k++) {
Console.Write("{0}", c.ToString().PadLeft(3));
c = c * (i - k) / (k + 1);
}
Console.WriteLine();
}
}
}
public static void Main() {
CreateTriangle(8);
}
}
} |
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.
| #Python | Python | from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = None
except ValueError:
parsed = urlparse('//{}'.format(netloc))
ip = ip_address(parsed.hostname)
port = parsed.port
return ip, port
for address in tests:
ip, port = parse_ip_port(address)
hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
print("{:39s} {:>32s} IPv{} port={}".format(
str(ip), hex_ip, ip.version, port )) |
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.
| #Visual_Prolog | Visual Prolog |
domains
tree{Type} = branch(tree{Type} Left, tree{Type} Right); leaf(Type Value).
class predicates
treewalk : (tree{X},function{X,Y}) -> tree{Y} procedure (i,i).
clauses
treewalk(branch(Left,Right),Func) = branch(NewLeft,NewRight) :-
NewLeft = treewalk(Left,Func), NewRight = treewalk(Right,Func).
treewalk(leaf(Value),Func) = leaf(X) :-
X = Func(Value).
run():-
init(),
X = branch(leaf(2), branch(leaf(3),leaf(4))),
Y = treewalk(X,addone),
write(Y),
succeed().
|
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.
| #Java | Java | import java.util.Stack;
public class PostfixToInfix {
public static void main(String[] args) {
for (String e : new String[]{"3 4 2 * 1 5 - 2 3 ^ ^ / +",
"1 2 + 3 4 + ^ 5 6 + ^"}) {
System.out.printf("Postfix : %s%n", e);
System.out.printf("Infix : %s%n", postfixToInfix(e));
System.out.println();
}
}
static String postfixToInfix(final String postfix) {
class Expression {
final static String ops = "-+/*^";
String op, ex;
int prec = 3;
Expression(String e) {
ex = e;
}
Expression(String e1, String e2, String o) {
ex = String.format("%s %s %s", e1, o, e2);
op = o;
prec = ops.indexOf(o) / 2;
}
@Override
public String toString() {
return ex;
}
}
Stack<Expression> expr = new Stack<>();
for (String token : postfix.split("\\s+")) {
char c = token.charAt(0);
int idx = Expression.ops.indexOf(c);
if (idx != -1 && token.length() == 1) {
Expression r = expr.pop();
Expression l = expr.pop();
int opPrec = idx / 2;
if (l.prec < opPrec || (l.prec == opPrec && c == '^'))
l.ex = '(' + l.ex + ')';
if (r.prec < opPrec || (r.prec == opPrec && c != '^'))
r.ex = '(' + r.ex + ')';
expr.push(new Expression(l.ex, r.ex, token));
} else {
expr.push(new Expression(token));
}
System.out.printf("%s -> %s%n", token, expr);
}
return expr.peek().ex;
}
} |
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.
| #LFE | LFE |
(defun partial
"The partial function is arity 2 where the first parameter must be a
function and the second parameter may either be a single item or a list of
items.
When funcall is called against the result of the partial call, a second
parameter is applied to the partial function. This parameter too may be
either a single item or a list of items."
((func args-1) (when (is_list args-1))
(match-lambda
((args-2) (when (is_list args-2))
(apply func (++ args-1 args-2)))
((arg-2)
(apply func (++ args-1 `(,arg-2))))))
((func arg-1)
(match-lambda
((args-2) (when (is_list args-2))
(apply func (++ `(,arg-1) args-2)))
((arg-2)
(funcall func arg-1 arg-2)))))
|
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.
| #Logtalk | Logtalk |
:- object(partial_functions).
:- public(show/0).
show :-
% create the partial functions
create_partial_function(f1, PF1),
create_partial_function(f2, PF2),
% apply the partial functions
Sequence1 = [0,1,2,3],
call(PF1, Sequence1, PF1Sequence1), output_results(PF1, Sequence1, PF1Sequence1),
call(PF2, Sequence1, PF2Sequence1), output_results(PF2, Sequence1, PF2Sequence1),
Sequence2 = [2,4,6,8],
call(PF1, Sequence2, PF1Sequence2), output_results(PF1, Sequence2, PF1Sequence2),
call(PF2, Sequence2, PF2Sequence2), output_results(PF2, Sequence2, PF2Sequence2).
create_partial_function(Closure, fs(Closure)).
output_results(Function, Input, Output) :-
write(Input), write(' -> '), write(Function), write(' -> '), write(Output), nl.
fs(Closure, Arg1, Arg2) :-
meta::map(Closure, Arg1, Arg2).
f1(Value, Double) :-
Double is 2*Value.
f2(Value, Square) :-
Square is Value*Value.
:- end_object.
|
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
| #Swift | Swift | import Foundation
class BitArray {
var array: [UInt32]
init(size: Int) {
array = Array(repeating: 0, count: (size + 31)/32)
}
func get(index: Int) -> Bool {
let bit = UInt32(1) << (index & 31)
return (array[index >> 5] & bit) != 0
}
func set(index: Int, value: Bool) {
let bit = UInt32(1) << (index & 31)
if value {
array[index >> 5] |= bit
} else {
array[index >> 5] &= ~bit
}
}
}
class PrimeSieve {
let composite: BitArray
init(size: Int) {
composite = BitArray(size: size/2)
var p = 3
while p * p <= size {
if !composite.get(index: p/2 - 1) {
let inc = p * 2
var q = p * p
while q <= size {
composite.set(index: q/2 - 1, value: true)
q += inc
}
}
p += 2
}
}
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
if (number & 1) == 0 {
return number == 2
}
return !composite.get(index: number/2 - 1)
}
}
func findPrimePartition(sieve: PrimeSieve, number: Int,
count: Int, minPrime: Int,
primes: inout [Int], index: Int) -> Bool {
if count == 1 {
if number >= minPrime && sieve.isPrime(number: number) {
primes[index] = number
return true
}
return false
}
if minPrime >= number {
return false
}
for p in minPrime..<number {
if sieve.isPrime(number: p)
&& findPrimePartition(sieve: sieve, number: number - p,
count: count - 1, minPrime: p + 1,
primes: &primes, index: index + 1) {
primes[index] = p
return true
}
}
return false
}
func printPrimePartition(sieve: PrimeSieve, number: Int, count: Int) {
var primes = Array(repeating: 0, count: count)
if !findPrimePartition(sieve: sieve, number: number, count: count,
minPrime: 2, primes: &primes, index: 0) {
print("\(number) cannot be partitioned into \(count) primes.")
} else {
print("\(number) = \(primes[0])", terminator: "")
for i in 1..<count {
print(" + \(primes[i])", terminator: "")
}
print()
}
}
let sieve = PrimeSieve(size: 100000)
printPrimePartition(sieve: sieve, number: 99809, count: 1)
printPrimePartition(sieve: sieve, number: 18, count: 2)
printPrimePartition(sieve: sieve, number: 19, count: 3)
printPrimePartition(sieve: sieve, number: 20, count: 4)
printPrimePartition(sieve: sieve, number: 2017, count: 24)
printPrimePartition(sieve: sieve, number: 22699, count: 1)
printPrimePartition(sieve: sieve, number: 22699, count: 2)
printPrimePartition(sieve: sieve, number: 22699, count: 3)
printPrimePartition(sieve: sieve, number: 22699, count: 4)
printPrimePartition(sieve: sieve, number: 40355, count: 3) |
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
| #VBScript | VBScript | ' Partition an integer X into N primes
dim p(),a(32),b(32),v,g: redim p(64)
what="99809 1 18 2 19 3 20 4 2017 24 22699 1-4 40355 3"
t1=split(what," ")
for j=0 to ubound(t1)
t2=split(t1(j)): x=t2(0): n=t2(1)
t3=split(x,"-"): x=clng(t3(0))
if ubound(t3)=1 then y=clng(t3(1)) else y=x
t3=split(n,"-"): n=clng(t3(0))
if ubound(t3)=1 then m=clng(t3(1)) else m=n
genp y 'generate primes in p
for g=x to y
for q=n to m: part: next 'q
next 'g
next 'j
sub genp(high)
p(1)=2: p(2)=3: c=2: i=p(c)+2
do 'i
k=2: bk=false
do while k*k<=i and not bk 'k
if i mod p(k)=0 then bk=true
k=k+1
loop 'k
if not bk then
c=c+1: if c>ubound(p) then redim preserve p(ubound(p)+8)
p(c)=i
end if
i=i+2
loop until p(c)>high 'i
end sub 'genp
sub getp(z)
if a(z)=0 then w=z-1: a(z)=a(w)
a(z)=a(z)+1: w=a(z): b(z)=p(w)
end sub 'getp
function list()
w=b(1)
if v=g then for i=2 to q: w=w&"+"&b(i): next else w="(not possible)"
list="primes: "&w
end function 'list
sub part()
for i=lbound(a) to ubound(a): a(i)=0: next 'i
for i=1 to q: call getp(i): next 'i
do while true: v=0: bu=false
for s=1 to q
v=v+b(s)
if v>g then
if s=1 then exit do
for k=s to q: a(k)=0: next 'k
for r=s-1 to q: call getp(r): next 'r
bu=true: exit for
end if
next 's
if not bu then
if v=g then exit do
if v<g then call getp(q)
end if
loop
wscript.echo "partition "&g&" into "&q&" "&list
end sub 'part
|
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.
| #Scala | Scala | object PascalTriangle extends App {
val (x, y, z) = pascal(11, 4, 40, 151)
def pascal(a: Int, b: Int, mid: Int, top: Int): (Int, Int, Int) = {
val y = (top - 4 * (a + b)) / 7
val x = mid - 2 * a - y
(x, y, y - x)
}
println(if (x != 0) s"Solution is: x = $x, y = $y, z = $z" else "There is 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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use English;
use Const::Fast;
use Getopt::Long;
use Math::Random;
const my @lcs => 'a' .. 'z';
const my @ucs => 'A' .. 'Z';
const my @digits => 0 .. 9;
const my $others => q{!"#$%&'()*+,-./:;<=>?@[]^_{|}~}; # "
my $pwd_length = 8;
my $num_pwds = 6;
my $seed_phrase = 'TOO MANY SECRETS';
my %opts = (
'password_length=i' => \$pwd_length,
'num_passwords=i' => \$num_pwds,
'seed_phrase=s' => \$seed_phrase,
'help!' => sub {command_line_help(); exit 0}
);
command_line_help() and exit 1 unless $num_pwds >= 1 and $pwd_length >= 4 and GetOptions(%opts);
random_set_seed_from_phrase($seed_phrase);
say gen_password() for 1 .. $num_pwds;
sub gen_password {
my @generators = (\&random_lc, \&random_uc, \&random_digit, \&random_other);
my @chars = map {$ARG->()} @generators; # At least one char of each type.
push @chars, $generators[random_uniform_integer(1, 0, 3)]->() for 1 .. $pwd_length - 4;
join '', random_permutation(@chars);
}
sub random_lc { $lcs[ random_uniform_integer(1, 0, $#lcs) ] }
sub random_uc { $ucs[ random_uniform_integer(1, 0, $#ucs) ] }
sub random_digit { $digits[ random_uniform_integer(1, 0, $#digits) ] }
sub random_other { substr($others, random_uniform_integer(1, 0, length($others)-1), 1) }
sub command_line_help {
say <<~END
Usage: $PROGRAM_NAME
[--password_length=<l> default: 8, minimum: 4]
[--num_passwords=<n> default: 6, minimum: 1]
[--seed_phrase=<s> default: TOO MANY SECRETS (optional)]
[--help]
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
| #zkl | zkl | zkl: Utils.Helpers.permute("rose").apply("concat")
L("rose","roes","reos","eros","erso","reso","rseo","rsoe","sroe","sreo",...)
zkl: Utils.Helpers.permute("rose").len()
24
zkl: Utils.Helpers.permute(T(1,2,3,4))
L(L(1,2,3,4),L(1,2,4,3),L(1,4,2,3),L(4,1,2,3),L(4,1,3,2),L(1,4,3,2),L(1,3,4,2),L(1,3,2,4),...) |
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
| #Haskell | Haskell | import Control.Concurrent (setNumCapabilities)
import Crypto.Hash (hashWith, SHA256 (..), Digest)
import Control.Monad (replicateM, join, (>=>))
import Control.Monad.Par (runPar, get, spawnP)
import Data.ByteString (pack)
import Data.List.Split (chunksOf)
import GHC.Conc (getNumProcessors)
import Text.Printf (printf)
hashedValues :: [Digest SHA256]
hashedValues = read <$>
[ "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"
, "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"
, "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad" ]
bruteForce :: Int -> [(String, String)]
bruteForce n = runPar $ join <$>
(mapM (spawnP . foldr findMatch []) >=> mapM get) chunks
where
chunks = chunksOf (26^5 `div` n) $ replicateM 5 [97..122]
findMatch s accum
| hashed `elem` hashedValues = (show hashed, show bStr) : accum
| otherwise = accum
where
bStr = pack s
hashed = hashWith SHA256 bStr
main :: IO ()
main = do
cpus <- getNumProcessors
setNumCapabilities cpus
printf "Using %d cores\n" cpus
mapM_ (uncurry (printf "%s -> %s\n")) (bruteForce cpus) |
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.
| #Java | Java | import static java.lang.System.out;
import static java.util.Arrays.stream;
import static java.util.Comparator.comparing;
public interface ParallelCalculations {
public static final long[] NUMBERS = {
12757923,
12878611,
12878893,
12757923,
15808973,
15780709,
197622519
};
public static void main(String... arguments) {
stream(NUMBERS)
.unordered()
.parallel()
.mapToObj(ParallelCalculations::minimalPrimeFactor)
.max(comparing(a -> a[0]))
.ifPresent(res -> out.printf(
"%d has the largest minimum prime factor: %d%n",
res[1],
res[0]
));
}
public static long[] minimalPrimeFactor(long n) {
for (long i = 2; n >= i * i; i++) {
if (n % i == 0) {
return new long[]{i, n};
}
}
return new long[]{n, n};
}
} |
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.
| #D | D | import std.stdio, std.string, std.conv, std.typetuple;
void main() {
auto input = "3 4 2 * 1 5 - 2 3 ^ ^ / +";
writeln("For postfix expression: ", input);
writeln("\nToken Action Stack");
real[] stack;
foreach (tok; input.split()) {
auto action = "Apply op to top of stack";
switch (tok) {
foreach (o; TypeTuple!("+", "-", "*", "/", "^")) {
case o:
mixin("stack[$ - 2]" ~
(o == "^" ? "^^" : o) ~ "=stack[$ - 1];");
stack.length--;
break;
}
break;
default:
action = "Push num onto top of stack";
stack ~= to!real(tok);
}
writefln("%3s %-26s %s", tok, action, stack);
}
writeln("\nThe final value is ", stack[0]);
} |
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.