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/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
| #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Is the $-terminated string at DE a palindrome?
;;; Returns: zero flag set if palindrome
palin: mov h,d ; Find end of string
mov l,e
mvi a,'$'
cmp m ; The empty string is a palindrome
rz
pend: inx h ; Scan until terminator found
cmp m
jnz pend
dcx h ; Move to last byte of text
ptest: ldax d ; Load char at left pointer
cmp m ; Compare to char at right pointer
rnz ; If not equal, not a palindrome
inx d ; Move pointers
dcx h
mov a,d ; Check if left pointer is before right pointer
cmp h ; High byte
jc ptest
mov a,e ; Low byte
cmp l
jc ptest
xra a ; Made it to the end - set zero flag
ret ; Return
;;; Test the routine on a few examples
demo: lxi h,words ; Word list pointer
loop: mov e,m ; Load word pointer
inx h
mov d,m
inx h
mov a,e ; Stop when zero reached
ora d
rz
push h ; Keep word list pointer
call pstr ; Print word
call palin ; Check if palindrome
lxi d,no
jnz print ; Print "no" if not a palindrome
lxi d,yes ; Print "yes" otherwise
print: call pstr
pop h
jmp loop
;;; Print strint using CP/M keeping DEHL registers
pstr: push d
push h
mvi c,9
call 5
pop h
pop d
ret
yes: db ': yes',13,10,'$'
no: db ': no',13,10,'$'
words: dw w1,w2,w3,w4,0
w1: db 'rotor$'
w2: db 'racecar$'
w3: db 'level$'
w4: db 'rosetta$' |
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.
| #Factor | Factor | USING: formatting fry io kernel lists lists.lazy locals math
math.functions math.ranges math.text.utils prettyprint sequences ;
IN: rosetta-code.palindromic-gapful-numbers
! Palindromic numbers are relatively rare compared to gapful
! numbers, so our strategy for finding palindromic gapful
! numbers is to filter gapful numbers from palindromic numbers.
! Palindromic numbers can be generated directly rather than
! filtered or identified from the natural numbers. This is a
! significant speedup since palindromic numbers are relatively
! rare in the natural numbers.
! Here I have used a generation method similar to
! https://www.geeksforgeeks.org/generate-palindromic-numbers-less-n/
! Create a palindrome from its base natural number.
! e.g. 321 t -> 32123
! 321 f -> 321123
: create-palindrome ( n odd? -- m )
dupd [ 10 /i ] when swap [ over 0 > ]
[ 10 * [ 10 /mod ] [ + ] bi* ] while nip ;
! Create an infinite lazy list of palindromic numbers starting
! at 100.
: palindromes ( -- l )
1 lfrom [
10 swap ^ dup 10 * [a,b)
[ [ t create-palindrome ] map ]
[ [ f create-palindrome ] map ] bi
[ sequence>list ] bi@ lappend
] lmap-lazy lconcat ;
! Is an integer gapful?
: gapful? ( n -- ? )
dup 1 digit-groups [ first ] [ last 10 * + ] bi divisor? ;
! Create an infinite lazy list of gapful palindromes.
: gapful-palindromes ( -- l ) palindromes [ gapful? ] lfilter ;
:: show-palindromic-gapfuls ( last of -- )
gapful-palindromes :> nums
last of
"~~==[ Last %d of %d palindromic gapful numbers starting at 100 ]==~~\n"
printf 9 [1,b] [| d |
of nums [ 10 mod d = ] lfilter ltake list>array
last tail* d pprint ": " write [ pprint bl ] each nl
] each nl ;
20 20 ! part 1
15 100 ! part 2
10 1000 ! part 3 (Optional)
[ show-palindromic-gapfuls ] 2tri@ |
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.
| #Java | Java | import java.util.Stack;
public class ShuntingYard {
public static void main(String[] args) {
String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
System.out.printf("infix: %s%n", infix);
System.out.printf("postfix: %s%n", infixToPostfix(infix));
}
static String infixToPostfix(String infix) {
/* To find out the precedence, we take the index of the
token in the ops string and divide by 2 (rounding down).
This will give us: 0, 0, 1, 1, 2 */
final String ops = "-+/*^";
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
for (String token : infix.split("\\s")) {
if (token.isEmpty())
continue;
char c = token.charAt(0);
int idx = ops.indexOf(c);
// check for operator
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 > prec1 || (prec2 == prec1 && c != '^'))
sb.append(ops.charAt(s.pop())).append(' ');
else break;
}
s.push(idx);
}
}
else if (c == '(') {
s.push(-2); // -2 stands for '('
}
else if (c == ')') {
// until '(' on stack, pop operators.
while (s.peek() != -2)
sb.append(ops.charAt(s.pop())).append(' ');
s.pop();
}
else {
sb.append(token).append(' ');
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop())).append(' ');
return sb.toString();
}
} |
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
| #Kotlin | Kotlin | // version 1.1.4-3
import java.math.BigInteger
const val MAX_N = 250
const val BRANCHES = 4
val rooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }
val unrooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }
val c = Array(BRANCHES) { BigInteger.ZERO }
fun tree(br: Int, n: Int, l: Int, s: Int, cnt: BigInteger) {
var sum = s
for (b in (br + 1)..BRANCHES) {
sum += n
if (sum > MAX_N || (l * 2 >= sum && b >= BRANCHES)) return
var tmp = rooted[n]
if (b == br + 1) {
c[br] = tmp * cnt
}
else {
val diff = (b - br).toLong()
c[br] *= tmp + BigInteger.valueOf(diff - 1L)
c[br] /= BigInteger.valueOf(diff)
}
if (l * 2 < sum) unrooted[sum] += c[br]
if (b < BRANCHES) rooted[sum] += c[br]
for (m in n - 1 downTo 1) tree(b, m, l, sum, c[br])
}
}
fun bicenter(s: Int) {
if ((s and 1) == 0) {
var tmp = rooted[s / 2]
tmp *= tmp + BigInteger.ONE
unrooted[s] += tmp.shiftRight(1)
}
}
fun main(args: Array<String>) {
for (n in 1..MAX_N) {
tree(0, n, n, 1, BigInteger.ONE)
bicenter(n)
println("$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
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
allChars="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
print isPangram("The quick brown fox jumps over the lazy dog.");
print isPangram("The quick brown fo.");
}
function isPangram(string) {
delete X;
for (k=1; k<length(string); k++) {
X[toupper(substr(string,k,1))]++; # histogram
}
for (k=1; k<=length(allChars); k++) {
if (!X[substr(allChars,k,1)]) return 0;
}
return 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
| #BASIC | BASIC | DECLARE FUNCTION IsPangram! (sentence AS STRING)
DIM x AS STRING
x = "My dog has fleas."
GOSUB doIt
x = "The lazy dog jumps over the quick brown fox."
GOSUB doIt
x = "Jackdaws love my big sphinx of quartz."
GOSUB doIt
x = "What's a jackdaw?"
GOSUB doIt
END
doIt:
PRINT IsPangram!(x), x
RETURN
FUNCTION IsPangram! (sentence AS STRING)
'returns -1 (true) if sentence is a pangram, 0 (false) otherwise
DIM l AS INTEGER, s AS STRING, t AS INTEGER
DIM letters(25) AS INTEGER
FOR l = 1 TO LEN(sentence)
s = UCASE$(MID$(sentence, l, 1))
SELECT CASE s
CASE "A" TO "Z"
t = ASC(s) - 65
letters(t) = 1
END SELECT
NEXT
FOR l = 0 TO 25
IF letters(l) < 1 THEN
IsPangram! = 0
EXIT FUNCTION
END IF
NEXT
IsPangram! = -1
END FUNCTION |
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.
| #Fortran | Fortran | module pascal
implicit none
contains
function pascal_lower(n) result(a)
integer :: n, i, j
integer, allocatable :: a(:, :)
allocate(a(n, n))
a = 0
do i = 1, n
a(i, 1) = 1
end do
do i = 2, n
do j = 2, i
a(i, j) = a(i - 1, j) + a(i - 1, j - 1)
end do
end do
end function
function pascal_upper(n) result(a)
integer :: n, i, j
integer, allocatable :: a(:, :)
allocate(a(n, n))
a = 0
do i = 1, n
a(1, i) = 1
end do
do i = 2, n
do j = 2, i
a(j, i) = a(j, i - 1) + a(j - 1, i - 1)
end do
end do
end function
function pascal_symmetric(n) result(a)
integer :: n, i, j
integer, allocatable :: a(:, :)
allocate(a(n, n))
a = 0
do i = 1, n
a(i, 1) = 1
a(1, i) = 1
end do
do i = 2, n
do j = 2, n
a(i, j) = a(i - 1, j) + a(i, j - 1)
end do
end do
end function
subroutine print_matrix(a)
integer :: a(:, :)
integer :: n, i
n = ubound(a, 1)
do i = 1, n
print *, a(i, :)
end do
end subroutine
end module
program ex_pascal
use pascal
implicit none
integer :: n
integer, allocatable :: a(:, :)
print *, "Size?"
read *, n
print *, "Lower Pascal Matrix"
a = pascal_lower(n)
call print_matrix(a)
print *, "Upper Pascal Matrix"
a = pascal_upper(n)
call print_matrix(a)
print *, "Symmetric Pascal Matrix"
a = pascal_symmetric(n)
call print_matrix(a)
end program |
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. | #PureBasic | PureBasic | UseSQLiteDatabase()
Procedure CheckDatabaseUpdate(database, query$)
result = DatabaseUpdate(database, query$)
If result = 0
PrintN(DatabaseError())
EndIf
ProcedureReturn result
EndProcedure
If OpenConsole()
If OpenDatabase(0, ":memory:", "", "")
;create players table with sample data
CheckDatabaseUpdate(0, "CREATE table players (name, score, active, jerseyNum)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jones, Bob',0,'N',99)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)")
CheckDatabaseUpdate(0, "INSERT INTO players VALUES ('Jello, Frank',0,'N',101)")
Define name$, score, active$, jerseynum
name$ = "Smith, Steve"
score = 42
active$ ="TRUE"
jerseynum = 99
SetDatabaseString(0, 0, name$)
SetDatabaseLong(0, 1, score)
SetDatabaseString(0, 2, active$)
SetDatabaseLong(0, 3, jerseynum)
CheckDatabaseUpdate(0, "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?")
;display database contents
If DatabaseQuery(0, "Select * from players")
While NextDatabaseRow(0)
name$ = GetDatabaseString(0, 0)
score = GetDatabaseLong(0, 1)
active$ = GetDatabaseString(0, 2)
jerseynum = GetDatabaseLong(0, 3)
row$ = "['" + name$ + "', " + score + ", '" + active$ + "', " + jerseynum + "]"
PrintN(row$)
Wend
FinishDatabaseQuery(0)
EndIf
CloseDatabase(0)
Else
PrintN("Can't open database !")
EndIf
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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.2B.2B | C++ | #include <iostream>
#include <algorithm>
#include<cstdio>
using namespace std;
void Pascal_Triangle(int size) {
int a[100][100];
int i, j;
//first row and first coloumn has the same value=1
for (i = 1; i <= size; i++) {
a[i][1] = a[1][i] = 1;
}
//Generate the full Triangle
for (i = 2; i <= size; i++) {
for (j = 2; j <= size - i; j++) {
if (a[i - 1][j] == 0 || a[i][j - 1] == 0) {
break;
}
a[i][j] = a[i - 1][j] + a[i][j - 1];
}
}
/*
1 1 1 1
1 2 3
1 3
1
first print as above format-->
for (i = 1; i < size; i++) {
for (j = 1; j < size; j++) {
if (a[i][j] == 0) {
break;
}
printf("%8d",a[i][j]);
}
cout<<"\n\n";
}*/
// standard Pascal Triangle Format
int row,space;
for (i = 1; i < size; i++) {
space=row=i;
j=1;
while(space<=size+(size-i)+1){
cout<<" ";
space++;
}
while(j<=i){
if (a[row][j] == 0){
break;
}
if(j==1){
printf("%d",a[row--][j++]);
}
else
printf("%6d",a[row--][j++]);
}
cout<<"\n\n";
}
}
int main()
{
//freopen("out.txt","w",stdout);
int size;
cin>>size;
Pascal_Triangle(size);
}
} |
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.
| #Racket | Racket |
#lang racket
(require net/private/ip)
(define (bytes->hex bs)
(string-append* (map (λ(n) (~r n #:base 16 #:min-width 2 #:pad-string "0"))
(bytes->list bs))))
(define (parse-ip str)
(define-values [ipstr portstr]
(match str
[(regexp #rx"^([0-9.]+):([0-9]+)$" (list _ i p)) (values i p)]
[(regexp #rx"^\\[([0-9a-fA-F:]+)\\]:([0-9]+)$" (list _ i p)) (values i p)]
[_ (values str "")]))
(define ip (make-ip-address ipstr))
(define 4? (ipv4? ip))
(define hex (bytes->hex ((if 4? ipv4-bytes ipv6-bytes) ip)))
(displayln (~a (~a str #:min-width 30)
" "
(~a hex #:min-width 32 #:align 'right)
" ipv" (if 4? "4" "6") " " portstr)))
(for-each parse-ip
'("127.0.0.1"
"127.0.0.1:80"
"::1"
"[::1]:80"
"2605:2700:0:3::4713:93e3"
"[2605:2700:0:3::4713:93e3]:80"))
|
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.
| #Wren | Wren | class BinaryTree {
construct new(T, value) {
if (!(T is Class)) Fiber.abort ("T must be a class.")
if (value.type != T) Fiber.abort("Value must be of type T.")
_kind = T
_value = value
_left = null
_right = null
}
// constructor overload to enable kind to be inferred from type of value
static new (value) { new(value.type, value) }
kind { _kind }
value { _value}
value=(v) {
if (v.type != _kind) Fiber.abort("Value must be of type %(_kind)")
_value = v
}
left { _left }
right { _right }
left=(b) {
if (b.type != BinaryTree || b.kind != _kind) {
Fiber.abort("Argument must be a BinaryTree of type %(_kind)")
}
_left = b
}
right=(b) {
if (b.type != BinaryTree || b.kind != _kind) {
Fiber.abort("Argument must be a BinaryTree of type %(_kind)")
}
_right = b
}
map(f) {
var tree = BinaryTree.new(f.call(_value))
if (_left) tree.left = left.map(f)
if (_right) tree.right = right.map(f)
return tree
}
showTopThree() { "(%(left.value), %(value), %(right.value))" }
}
var b = BinaryTree.new(6)
b.left = BinaryTree.new(5)
b.right = BinaryTree.new(7)
System.print(b.showTopThree())
var b2 = b.map{ |i| i * 10 }
System.print(b2.showTopThree())
b2.value = "six" // generates an error because "six" is not a Num |
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.
| #JavaScript | JavaScript | const Associativity = {
/** a / b / c = (a / b) / c */
left: 0,
/** a ^ b ^ c = a ^ (b ^ c) */
right: 1,
/** a + b + c = (a + b) + c = a + (b + c) */
both: 2,
};
const operators = {
'+': { precedence: 2, associativity: Associativity.both },
'-': { precedence: 2, associativity: Associativity.left },
'*': { precedence: 3, associativity: Associativity.both },
'/': { precedence: 3, associativity: Associativity.left },
'^': { precedence: 4, associativity: Associativity.right },
};
class NumberNode {
constructor(text) { this.text = text; }
toString() { return this.text; }
}
class InfixNode {
constructor(fnname, operands) {
this.fnname = fnname;
this.operands = operands;
}
toString(parentPrecedence = 0) {
const op = operators[this.fnname];
const leftAdd = op.associativity === Associativity.right ? 0.01 : 0;
const rightAdd = op.associativity === Associativity.left ? 0.01 : 0;
if (this.operands.length !== 2) throw Error("invalid operand count");
const result = this.operands[0].toString(op.precedence + leftAdd)
+` ${this.fnname} ${this.operands[1].toString(op.precedence + rightAdd)}`;
if (parentPrecedence > op.precedence) return `( ${result} )`;
else return result;
}
}
function rpnToTree(tokens) {
const stack = [];
console.log(`input = ${tokens}`);
for (const token of tokens.split(" ")) {
if (token in operators) {
const op = operators[token], arity = 2; // all of these operators take 2 arguments
if (stack.length < arity) throw Error("stack error");
stack.push(new InfixNode(token, stack.splice(stack.length - arity)));
}
else stack.push(new NumberNode(token));
console.log(`read ${token}, stack = [${stack.join(", ")}]`);
}
if (stack.length !== 1) throw Error("stack error " + stack);
return stack[0];
}
const tests = [
["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 )"],
["1 2 3 + +", "1 + 2 + 3"] // test associativity (1+(2+3)) == (1+2+3)
];
for (const [inp, oup] of tests) {
const realOup = rpnToTree(inp).toString();
console.log(realOup === oup ? "Correct!" : "Incorrect!");
} |
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.
| #Lua | Lua | function map(f, ...)
local t = {}
for k, v in ipairs(...) do
t[#t+1] = f(v)
end
return t
end
function timestwo(n)
return n * 2
end
function squared(n)
return n ^ 2
end
function partial(f, arg)
return function(...)
return f(arg, ...)
end
end
timestwo_s = partial(map, timestwo)
squared_s = partial(map, squared)
print(table.concat(timestwo_s{0, 1, 2, 3}, ', '))
print(table.concat(squared_s{0, 1, 2, 3}, ', '))
print(table.concat(timestwo_s{2, 4, 6, 8}, ', '))
print(table.concat(squared_s{2, 4, 6, 8}, ', ')) |
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes | Partition an integer x into n primes | Task
Partition a positive integer X into N distinct primes.
Or, to put it in another way:
Find N unique primes such that they add up to X.
Show in the output section the sum X and the N primes in ascending order separated by plus (+) signs:
• partition 99809 with 1 prime.
• 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
| #Visual_Basic_.NET | Visual Basic .NET | ' Partition an integer X into N primes - 29/03/2017
Option Explicit On
Module PartitionIntoPrimes
Dim p(8), a(32), b(32), v, g, q As Long
Sub Main()
Dim what, t1(), t2(), t3(), xx, nn As String
Dim x, y, n, m As Long
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)) : xx = t2(0) : nn = t2(1)
t3 = Split(xx, "-") : x = CLng(t3(0))
If UBound(t3) = 1 Then y = CLng(t3(1)) Else y = x
t3 = Split(nn, "-") : 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
End Sub 'Main
Sub genp(high As Long)
Dim c, i, k As Long
Dim bk As Boolean
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 As Long)
Dim w As Long
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()
Dim w As String
w = b(1)
If v = g Then
For i = 2 To q : w = w & "+" & b(i) : Next
Else
w = "(not possible)"
End If
Return "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
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
Continue Do
End If
Next 's
If v = g Then Exit Do
If v < g Then Call getp(q)
Loop
Console.WriteLine("partition " & g & " into " & q & " " & list())
End Sub 'part
End Module 'PartitionIntoPrimes
|
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.
| #Sidef | Sidef | # set up triangle
var rows = 5
var tri = rows.of {|i| (i+1).of { Hash(x => 0, z => 0, v => 0, rhs => nil) } }
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 row in (tri.len ^.. 1) {
for col in (^tri[row-1]) {
[:x, :z, :v].each { |key|
tri[row-1][col]{key} = (tri[row][col]{key} + tri[row][col+1]{key})
}
}
}
# find equations
var eqn = gather {
for r in tri {
for c in r {
take([c{:x}, c{:z}, c{:rhs} - c{:v}]) if defined(c{:rhs})
}
}
}
# print equations
say "Equations:"
say " x + z = y"
for x,z,y in eqn { say "#{x}x + #{z}z = #{y}" }
# solve
var f = (eqn[0][1] / eqn[1][1])
{|i| eqn[0][i] -= (f * eqn[1][i]) } << ^3
f = (eqn[1][0] / eqn[0][0])
{|i| eqn[1][i] -= (f * eqn[0][i]) } << ^3
# print solution
say "Solution:"
var x = (eqn[0][2] / eqn[0][0])
var z = (eqn[1][2] / eqn[1][1])
var 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
| #Phix | Phix | --with javascript_semantics -- not quite yet:
without js -- (VALUECHANGED_CB not yet triggering)
constant az = "abcdefghijklmnopqrstuvwxyz",
AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
O9 = "1234567890",
OT = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"
function password(integer len, integer n, sequence exclude="Il1O05S2Z")
sequence res = {},
S4 = apply(true,filter,{{az,AZ,O9,OT},{"out"},{exclude}})
string pw = repeat(' ',len)
for i=1 to n do
sequence sel = shuffle({1,2,3,4}&sq_rand(repeat(4,len-4)))
for c=1 to len do
string S4c = S4[sel[c]]
pw[c] = S4c[rand(length(S4c))]
end for
res = append(res,pw)
end for
return res
end function
include pGUI.e
Ihandle lenl, leng, numl, numb, res, dlg
function valuechanged_cb(Ihandle /*leng|numb*/)
integer l = IupGetInt(leng,"VALUE"),
n = IupGetInt(numb,"VALUE")
string s = join(password(l,n),"\n")
s = substitute(s,"&","&&") -- (on p2js??)
IupSetStrAttribute(res,"TITLE",s)
IupSetAttribute(dlg,"SIZE",NULL)
IupRefresh(dlg)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
lenl = IupLabel("length(4..99)")
leng = IupText("SPIN=YES,SPINMIN=4,SPINMAX=99")
numl = IupLabel("number(1..99)")
numb = IupText("SPIN=YES,SPINMIN=1,SPINMAX=99")
res = IupLabel("","FONTFACE=Courier")
IupSetCallback({leng,numb},"VALUECHANGED_CB", Icallback("valuechanged_cb"))
dlg = IupDialog(IupVbox({IupHbox({lenl,leng,numl,numb},"GAP=10,NORMALIZESIZE=VERTICAL"),
IupHbox({res})},"MARGIN=5x5"),
`TITLE="Password Generator"`)
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
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
| #Java | Java | import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* "Main Program" that does the parallel processing
*/
public class ParallelBruteForce {
public static void main(String[] args) throws NoSuchAlgorithmException {
//the hashes to be cracked
String[] hashes = {"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"};
//An ExecutorService is a high-level parallel programming facility, that can execute a number of tasks
//the FixedThreadPool is an ExecutorService that uses a configurable number of parallel threads
ExecutorService executorService = Executors.newFixedThreadPool(3);
//Submit one Task per hash to the thread po
for (String hash : hashes) {
executorService.submit(new Forcer(hash));
}
//An ExecutorSerice must be shut down properly (this also causes the program to await termination of
// all pending tasks in the thread pool)
executorService.shutdown();
}
}
/**
* The Class that contains the actual brute-forcing task.
* <p>
* It implements the build-in Interface "Runnable", so it can be run on a Thread or a Thread-Execution-Facility
* (such as an ExecutorService).
*/
class Forcer implements Runnable {
private static final int LENGTH = 5;
//These will sore the hash to be cracked in both bytes (required for comparison) and String representation
// (required for output)
private final byte[] crackMe;
private final String crackMeString;
//The MessageDigest does the SHA-256 caclulation. Note that this may throw a NoSuchAlgorithmException when there
// is no SHA-256 implementation in the local standard libraries (but that algorithm is mandatory, so this code
// probably will never throw that Excpetion
private final MessageDigest digest = MessageDigest.getInstance("SHA-256");
public Forcer(String crackMe) throws NoSuchAlgorithmException {
this.crackMeString = crackMe;
this.crackMe = DatatypeConverter.parseHexBinary(crackMe);
}
@Override
public void run() {
String match = "";
//all loops use this array for their counters. This is very dirty and should never be done in production!
char[] chars = new char[LENGTH];
//used for short-stopping when a match is found - one could abuse the match-variable for this, but this is
// much clearer
boolean done = false;
for (chars[0] = 'a'; chars[0] <= 'z' && !done; chars[0]++) {
for (chars[1] = 'a'; chars[1] <= 'z' && !done; chars[1]++) {
for (chars[2] = 'a'; chars[2] <= 'z' && !done; chars[2]++) {
for (chars[3] = 'a'; chars[3] <= 'z' && !done; chars[3]++) {
for (chars[4] = 'a'; chars[4] <= 'z' && !done; chars[4]++) {
//the String creation is necessary to get the encoding right
String canidate = new String(chars);
//genenrate SHA-256 hash using Java's standard facilities
byte[] hash = digest.digest(canidate.getBytes());
if (Arrays.equals(hash, crackMe)) {
match = canidate;
done = true;
}
}
}
}
}
}
System.out.println(String.format("Hash %s has the following match : %s", crackMeString, match));
}
}
|
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.
| #JavaScript | JavaScript |
var onmessage = function(event) {
postMessage({"n" : event.data.n,
"factors" : factor(event.data.n),
"id" : event.data.id});
};
function factor(n) {
var factors = [];
for(p = 2; p <= n; p++) {
if((n % p) == 0) {
factors[factors.length] = p;
n /= p;
}
}
return 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.
| #Julia | Julia |
using Primes
factortodict(d, n) = (d[minimum(collect(keys(factor(n))))] = n)
# Numbers are from from the Raku example.
numbers = [64921987050997300559, 70251412046988563035, 71774104902986066597,
83448083465633593921, 84209429893632345702, 87001033462961102237,
87762379890959854011, 89538854889623608177, 98421229882942378967,
259826672618677756753, 262872058330672763871, 267440136898665274575,
278352769033314050117, 281398154745309057242, 292057004737291582187]
mins = Dict()
Base.@sync(
Threads.@threads for n in numbers
factortodict(mins, n)
end
)
answer = maximum(keys(mins))
println("The number that has the largest minimum prime factor is $(mins[answer]), with a smallest factor of $answer")
|
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.
| #EchoLisp | EchoLisp |
;; RPN (postfix) evaluator
(lib 'hash)
(define OPS (make-hash))
(hash-set OPS "^" expt)
(hash-set OPS "*" *)
(hash-set OPS "/" //) ;; float divide
(hash-set OPS "+" +)
(hash-set OPS "-" -)
(define (op? op) (hash-ref OPS op))
;; algorithm : https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm
(define (calculator rpn S)
(for ((token rpn))
(if (op? token)
(let [(op2 (pop S)) (op1 (pop S))]
(unless (and op1 op2) (error "cannot calculate expression at:" token))
(push S ((op? token) op1 op2))
(writeln op1 token op2 "→" (stack-top S)))
(push S (string->number token))))
(pop S))
(define (task rpn)
(define S (stack 'S))
(calculator (text-parse rpn) S ))
|
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
| #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
jmp demo
;;; Check if the $-terminated string in [DS:SI] is a palindrome.
;;; Returns with zero flag set if so.
;;; Destroyed: AL, CX, SI, DI, ES.
palin: push es ; Set ES=DS.
pop ds
mov al,'$' ; Find end of string
mov cx,-1
mov di,si
repne scasb
dec di ; Move back to last actual character
.loop: cmp si,di
ja .ok ; If SI > DI, it is a palindrome
lodsb
dec di ; Compare left character to right character
cmp al,[di]
jne .no ; If not equal, not a palindrome
jmp .loop ; Otherwise, try next pair of characters
.ok: cmp al,al ; Set zero flag
.no: ret ; Return
;;; Try the routine on a couple of strings
demo: mov si,words
.loop: lodsw ; Grab word pointer
test ax,ax ; Zero?
jz .done ; Then we are done
mov dx,ax ; Otherwise, print word
mov ah,9
int 21h
xchg bp,si ; Keep array pointer in BP
xchg si,dx ; Put word pointer in SI
call palin ; Check if it is a palindrome
mov dx,yes ; Print 'yes'...
jz .print ; ...if it is a palindrome
mov dx,no ; Otherwise, print 'no'
.print: int 21h
xchg si,bp ; Restore array pointer
jmp .loop ; Get next word.
.done: ret
yes: db ': yes',13,10,'$' ; Yes and no
no: db ': no',13,10,'$'
words: dw .w1,.w2,.w3,.w4,.w5,0
.w1: db 'rotor$' ; Words to check
.w2: db 'racecar$'
.w3: db 'level$'
.w4: db 'redder$'
.w5: db 'rosetta$' |
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.
| #FreeBASIC | FreeBASIC | function is_gapful( n as uinteger ) as boolean
if n<100 then return false
dim as string ns = str(n)
dim as uinteger gap = 10*val(mid(ns,1,1)) + val(mid(ns,len(ns),1))
if n mod gap = 0 then return true else return false
end function
function is_palindrome( n as uinteger ) as boolean
dim as string ns = str(n)
for i as uinteger = 1 to len(ns)\2
if mid(ns,i,1) <> mid(ns,len(ns)+1-i,1) then return false
next i
return true
end function
function padto( n as uinteger, s as integer ) as string
dim as string outstr=""
dim as integer k = len(str(n))
for i as integer = 1 to s-k
outstr = " " + outstr
next i
return outstr + str(n)
end function
sub print_range( yays() as uinteger, first as uinteger, last as uinteger)
dim as string outstr
for i as uinteger = first to last
outstr = padto(i,4)+" : "
for d as uinteger = 1 to 9
outstr += padto(yays(d,i), 11)
next d
print outstr
next i
end sub
#define is_yay(n) (is_gapful(n) and is_palindrome(n))
#define log10(n) log(n)*0.43429448190325182765112891891660508229
dim as uinteger yays(1 to 9, 1 to 1000), nyays(1 to 9), num = 99, fd
do
num += 1 : fd = val(left(str(num),1))
if fd = 0 then continue do 'no paligap will have 0 as leading digit
if nyays(fd) = 1000 then
num = (fd+1)*10^int(log10(num))
end if
if is_yay(num) then
nyays(fd) += 1
yays(fd, nyays(fd)) = num
end if
for y as uinteger = 1 to 9
if nyays(y) < 1000 then continue do
next y
exit do
loop
'excessive output requirements for such a simple task
print_range(yays(), 1, 20)
print_range(yays(), 86, 100)
print_range(yays(), 991, 1000) |
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.
| #JavaScript | JavaScript | function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
}
function push(element) {
this.dataStore[this.top++] = element;
}
function pop() {
return this.dataStore[--this.top];
}
function peek() {
return this.dataStore[this.top-1];
}
function length() {
return this.top;
}
var infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
infix = infix.replace(/\s+/g, ''); // remove spaces, so infix[i]!=" "
var s = new Stack();
var ops = "-+/*^";
var precedence = {"^":4, "*":3, "/":3, "+":2, "-":2};
var associativity = {"^":"Right", "*":"Left", "/":"Left", "+":"Left", "-":"Left"};
var token;
var postfix = "";
var o1, o2;
for (var i = 0; i < infix.length; i++) {
token = infix[i];
if (token >= "0" && token <= "9") { // if token is operand (here limited to 0 <= x <= 9)
postfix += token + " ";
}
else if (ops.indexOf(token) != -1) { // if token is an operator
o1 = token;
o2 = s.peek();
while (ops.indexOf(o2)!=-1 && ( // while operator token, o2, on top of the stack
// and o1 is left-associative and its precedence is less than or equal to that of o2
(associativity[o1] == "Left" && (precedence[o1] <= precedence[o2]) ) ||
// the algorithm on wikipedia says: or o1 precedence < o2 precedence, but I think it should be
// or o1 is right-associative and its precedence is less than that of o2
(associativity[o1] == "Right" && (precedence[o1] < precedence[o2]))
)){
postfix += o2 + " "; // add o2 to output queue
s.pop(); // pop o2 of the stack
o2 = s.peek(); // next round
}
s.push(o1); // push o1 onto the stack
}
else if (token == "(") { // if token is left parenthesis
s.push(token); // then push it onto the stack
}
else if (token == ")") { // if token is right parenthesis
while (s.peek() != "("){ // until token at top is (
postfix += s.pop() + " ";
}
s.pop(); // pop (, but not onto the output queue
}
}
postfix += s.dataStore.reverse().join(" ");
print(postfix); |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | s[m_, p_, n_] :=
CycleIndexPolynomial[SymmetricGroup[m],
Table[ComposeSeries[p, x^i + O[x]^(n + 1)], {i, m}]];
G000598[n_] := Nest[1 + x s[3, #, n] &, 1 + O[x], n];
G000602[n_] :=
x s[4, #, n] - s[2, # - 1, n] +
ComposeSeries[#, x^2 + O[x]^(n + 1)] &[G000598[n]];
A000602[n_] := SeriesCoefficient[G000602[n], n];
A000602List[n_] := CoefficientList[G000602[n], x];
Grid@Transpose@{Range[0, 200], A000602List@200} |
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
| #Nim | Nim | import bigints
const
nMax: int32 = 250
nBranches = 4
var rooted, unrooted: array[nMax + 1, BigInt]
rooted[0..1] = [1.initBigInt, 1.initBigInt]
unrooted[0..1] = [1.initBigInt, 1.initBigInt]
for i in 2 .. nMax:
rooted[i] = 0.initBigInt
unrooted[i] = 0.initBigInt
proc choose(m: BigInt; k: int32): BigInt =
result = m
if k == 1: return
for i in 1 ..< k:
result = result * (m + i) div (i + 1)
proc tree(br, n, l, sum: int32; cnt: BigInt) =
var s: int32 = 0
for b in br + 1 .. nBranches:
s = sum + (b - br) * n
if s > nMax: return
let c = choose(rooted[n], b - br) * cnt
if l * 2 < s: unrooted[s] += c
if b == nBranches: return
rooted[s] += c
for m in countdown(n-1, 1):
tree b, m, l, s, c
proc bicenter(s: int32) =
if (s and 1) == 0:
unrooted[s] += rooted[s div 2] * (rooted[s div 2] + 1) div 2
for n in 1 .. nMax:
tree 0, n, n, 1, 1.initBigInt
n.bicenter
echo 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
| #BASIC256 | BASIC256 | function isPangram$(texto$)
longitud = Length(texto$)
if longitud < 26 then return "is not a pangram"
t$ = lower(texto$)
print "'"; texto$; "' ";
for i = 97 to 122
if instr(t$, chr(i)) = 0 then return "is not a pangram"
next i
return "is a pangram"
end function
print isPangram$("The quick brown fox jumps over the lazy dog.") # --> true
print isPangram$("The quick brown fox jumped over the lazy dog.") # --> false
print isPangram$("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ") # --> true |
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
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
%===The Main Thing===%
call :pangram "The quick brown fox jumps over the lazy dog."
call :pangram "The quick brown fox jumped over the lazy dog."
echo.
pause
exit /b 0
%===The Function===%
:pangram
set letters=abcdefgihjklmnopqrstuvwxyz
set cnt=0
set inp=%~1
set str=!inp: =!
:loop
set chr=!str:~%cnt%,1!
if "!letters!"=="" (
echo %1 is a pangram^^!
goto :EOF
)
if "!chr!"=="" (
echo %1 is not a pangram.
goto :EOF
)
set letters=!letters:%chr%=!
set /a cnt+=1
goto loop |
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.
| #FreeBASIC | FreeBASIC |
sub print_matrix( M() as integer )
'displays a matrix
for row as integer = 0 to ubound(M, 1)
for col as integer = 0 to ubound(M, 2)
print using "#### ";M(row, col);
next col
print
next row
return
end sub
function fact( n as uinteger ) as uinteger
'quick and dirty factorial
if n<2 then return 1 else return n*fact(n-1)
end function
function nCp( n as uinteger, p as uinteger ) as uinteger
'quick and dirty binomial
if p>n then return 0 else return fact(n)/(fact(p)*fact(n-p))
end function
sub make_pascal( M() as integer, typ as const ubyte )
'allocate the matrix first
'typ 0 = jCi, 1=iCj, 2=(j+i)Ci
for i as uinteger = 0 to ubound(M,1)
for j as uinteger = 0 to ubound(M,2)
select case typ
case 0
M(i,j) = nCp(j, i)
case 1
M(i,j) = nCp(i, j)
case 2
M(i,j) = nCp(i + j, j)
case else
M(i, j) = 0
end select
next j
next i
return
end sub
dim as integer M(0 to 4, 0 to 4)
print "Upper triangular"
make_pascal( M(), 0 )
print_matrix( M() )
print "Lower triangular"
make_pascal( M(), 1 )
print_matrix( M() )
print "Symmetric"
make_pascal( M(), 2 )
print_matrix( M() )
print "Technically the matrix needn't be square :)"
dim as integer Q(0 to 4, 0 to 9)
make_pascal( Q(), 2 )
print_matrix( Q() ) |
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. | #Python | Python | import sqlite3
db = sqlite3.connect(':memory:')
# setup
db.execute('create temp table players (name, score, active, jerseyNum)')
db.execute('insert into players values ("name",0,"false",99)')
db.execute('insert into players values ("name",0,"false",100)')
# demonstrate parameterized SQL
# example 1 -- simple placeholders
db.execute('update players set name=?, score=?, active=? where jerseyNum=?', ('Smith, Steve', 42, True, 99))
# example 2 -- named placeholders
db.execute('update players set name=:name, score=:score, active=:active where jerseyNum=:num',
{'num': 100,
'name': 'John Doe',
'active': False,
'score': -1}
)
# and show the results
for row in db.execute('select * from players'):
print(row) |
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. | #Racket | Racket |
#lang racket/base
(require sql db)
(define pgc
; Don't actually inline sensitive data ;)
(postgresql-connect #:user "resu"
#:database "esabatad"
#:server "example.com"
#:port 5432
#:password "s3>r37P455"))
(define update-player
(parameterize ((current-sql-dialect 'postgresql))
(update players
#:set [name ?] [score ?] [active ?]
#:where [jerseyNum ?])))
(apply query
pgc
update-player
'("Smith, Steve" 42 #t 99))
|
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
| #Clojure | Clojure | (defn pascal [n]
(let [newrow (fn newrow [lst ret]
(if lst
(recur (rest lst)
(conj ret (+ (first lst) (or (second lst) 0))))
ret))
genrow (fn genrow [n lst]
(when (< 0 n)
(do (println lst)
(recur (dec n) (conj (newrow lst []) 1)))))]
(genrow n [1])))
(pascal 4) |
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.
| #Raku | Raku | grammar IP_Addr {
token TOP { ^ [ <IPv4> | <IPv6> ] $ }
token IPv4 {
[ <d8> +% '.' ] <?{ $<d8> == 4 }> <port>?
{ @*by8 = @$<d8> }
}
token IPv6 {
| <ipv6>
| '[' <ipv6> ']' <port>
}
token ipv6 {
| <h16> +% ':' <?{ $<h16> == 8 }>
{ @*by16 = @$<h16> }
| [ (<h16>) +% ':']? '::' [ (<h16>) +% ':' ]? <?{ @$0 + @$1 ≤ 8 }>
{ @*by16 = |@$0, |('0' xx 8 - (@$0 + @$1)), |@$1 }
| '::ffff:' <IPv4>
{ @*by16 = |('0' xx 5), 'ffff', |(by8to16 @*by8) }
}
token d8 { (\d+) <?{ $0 < 256 }> }
token d16 { (\d+) <?{ $0 < 65536 }> }
token h16 { (<:hexdigit>+) <?{ $0.chars ≤ 4 }> }
token port {
':' <d16> { $*port = +$<d16> }
}
}
sub by8to16 (@m) { gather for @m -> $a,$b { take ($a * 256 + $b).fmt("%04x") } }
my @cases = <
127.0.0.1
127.0.0.1:80
::1
[::1]:80
2605:2700:0:3::4713:93e3
[2605:2700:0:3::4713:93e3]:80
2001:db8:85a3:0:0:8a2e:370:7334
2001:db8:85a3::8a2e:370:7334
[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443
192.168.0.1
::ffff:192.168.0.1
::ffff:71.19.147.227
[::ffff:71.19.147.227]:80
::
256.0.0.0
g::1
0000
0000:0000
0000:0000:0000:0000:0000:0000:0000:0000
0000:0000:0000::0000:0000
0000::0000::0000:0000
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
ffff:ffff:ffff:fffg:ffff:ffff:ffff:ffff
fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
fff:ffff:0:ffff:ffff:ffff:ffff:ffff
>;
for @cases -> $addr {
my @*by8;
my @*by16;
my $*port;
IP_Addr.parse($addr);
say $addr;
if @*by16 {
say " IPv6: ", @*by16.map({:16(~$_)})».fmt("%04x").join;
say " Port: ", $*port if $*port;
}
elsif @*by8 {
say " IPv4: ", @*by8».fmt("%02x").join;
say " Port: ", $*port if $*port;
}
else {
say " BOGUS!";
}
say '';
} |
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.
| #Julia | Julia |
function parseRPNstring(rpns)
infix = []
rpn = split(rpns)
for tok in rpn
if all(isnumber, tok)
push!(infix, parse(Int, tok))
else
last = pop!(infix)
prev = pop!(infix)
push!(infix, Expr(:call, Symbol(tok), prev, last))
println("Current step: $infix")
end
end
infix
end
unany(s) = replace(string(s), r"Any\[:\((.+)\)\]", s"\1")
println("The final infix result: ", parseRPNstring("3 4 2 * 1 5 - 2 3 ^ ^ / +") |> unany, "\n")
println("The final infix result: ", parseRPNstring("1 2 + 3 4 + ^ 5 6 + ^") |> unany)
|
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.
| #Kotlin | Kotlin | // version 1.2.0
import java.util.Stack
class Expression(var ex: String, val op: String = "", val prec: Int = 3) {
constructor(e1: String, e2: String, o: String) :
this("$e1 $o $e2", o, OPS.indexOf(o) / 2)
override fun toString() = ex
companion object {
const val OPS = "-+/*^"
}
}
fun postfixToInfix(postfix: String): String {
val expr = Stack<Expression>()
val rx = Regex("""\s+""")
for (token in postfix.split(rx)) {
val c = token[0]
val idx = Expression.OPS.indexOf(c)
if (idx != -1 && token.length == 1) {
val r = expr.pop()
val l = expr.pop()
val 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(Expression(l.ex, r.ex, token))
}
else {
expr.push(Expression(token))
}
println("$token -> $expr")
}
return expr.peek().ex
}
fun main(args: Array<String>) {
val es = listOf(
"3 4 2 * 1 5 - 2 3 ^ ^ / +",
"1 2 + 3 4 + ^ 5 6 + ^"
)
for (e in es) {
println("Postfix : $e")
println("Infix : ${postfixToInfix(e)}\n")
}
} |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | fs[f_, s_] := Map[f, s]
f1 [n_] := n*2
f2 [n_] := n^2
fsf1[s_] := fs[f1, s]
fsf2[s_] := fs[f2, s] |
http://rosettacode.org/wiki/Partial_function_application | Partial function application | Partial function application is the ability to take a function of many
parameters and apply arguments to some of the parameters to create a new
function that needs only the application of the remaining arguments to
produce the equivalent of applying all arguments to the original function.
E.g:
Given values v1, v2
Given f(param1, param2)
Then partial(f, param1=v1) returns f'(param2)
And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2)
Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application.
Task
Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s.
Function fs should return an ordered sequence of the result of applying function f to every value of s in turn.
Create function f1 that takes a value and returns it multiplied by 2.
Create function f2 that takes a value and returns it squared.
Partially apply f1 to fs to form function fsf1( s )
Partially apply f2 to fs to form function fsf2( s )
Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive.
Notes
In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed.
This task is more about how results are generated rather than just getting results.
| #Mercury | Mercury | :- module partial_function_application.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list.
main(!IO) :-
io.write((fsf1)([0, 1, 2, 3]), !IO), io.nl(!IO),
io.write((fsf2)([0, 1, 2, 3]), !IO), io.nl(!IO),
io.write((fsf1)([2, 4, 6, 8]), !IO), io.nl(!IO),
io.write((fsf2)([2, 4, 6, 8]), !IO), io.nl(!IO).
:- func fs(func(V) = V, list(V)) = list(V).
fs(_, []) = [].
fs(F, [V | Vs]) = [F(V) | fs(F, Vs)].
:- func f1(int) = int.
f1(V) = V * 2.
:- func f2(int) = int.
f2(V) = V * V.
:- func fsf1 = (func(list(int)) = list(int)).
fsf1 = fs(f1).
:- func fsf2 = (func(list(int)) = list(int)).
fsf2 = fs(f2). |
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
| #Wren | Wren | import "/math" for Int, Nums
import "/fmt" for Fmt
var primes = Int.primeSieve(1e5)
var foundCombo = false
var findCombo // recursive
findCombo = Fn.new { |k, x, m, n, combo|
if (k >= m) {
if (Nums.sum(combo.map { |i| primes[i] }.toList) == x) {
var s = (m > 1) ? "s" : ""
Fmt.write("Partitioned $5d with $2d prime$s: ", x, m, s)
for (i in 0...m) {
System.write(primes[combo[i]])
System.write((i < m - 1) ? "+" : "\n")
}
foundCombo = true
}
} else {
for (j in 0...n) {
if (k == 0 || j > combo[k - 1]) {
combo[k] = j
if (!foundCombo) findCombo.call(k + 1, x, m, n, combo)
}
}
}
}
var partition = Fn.new { |x, m|
if (x < 2 || m < 1 || m >= x) Fiber.abort("Invalid argument(s)")
var n = primes.where { |p| p <= x }.count
if (n < m) Fiber.abort("Not enough primes")
var combo = List.filled(m, 0)
foundCombo = false
findCombo.call(0, x, m, n, combo)
if (!foundCombo) {
var s = (m > 1) ? "s" : ""
Fmt.print("Partitioned $5d with $2d prime$s: (not possible)", x, m, s)
}
}
var a = [
[99809, 1],
[18, 2],
[19, 3],
[20, 4],
[2017, 24],
[22699, 1],
[22699, 2],
[22699, 3],
[22699, 4],
[40355, 3]
]
for (p in a) partition.call(p[0], p[1]) |
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle | Pascal's triangle/Puzzle | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).
Task
Write a program to find a solution to this puzzle.
| #SystemVerilog | SystemVerilog | program main;
class Triangle;
rand bit [7:0] a,b,c,d,e,f,g,h,X,Y,Z;
function new();
randomize;
$display(" [%0d]", 151);
$display(" [%0d][%0d]", a, b);
$display(" [%0d][%0d][%0d]", 40,c,d);
$display(" [%0d][%0d][%0d][%0d]", e,f,g,h);
$display(" [%0d][%0d][%0d][%0d][%0d]",X,11,Y,4,Z);
endfunction
constraint structure {
151 == a + b;
a == 40 + c;
b == c + d;
40 == e + f;
c == f + g;
d == g + h;
e == X + 11;
f == 11 + Y;
g == Y + 4;
h == 4 + Z;
};
constraint extra {
Y == X + Z;
};
endclass
Triangle answer = new;
endprogram |
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
| #PicoLisp | PicoLisp | #!/usr/bin/pil
# Default seed
(seed (in "/dev/urandom" (rd 8)))
# Global defaults
(setq
*PwCount 1
*PwLength 12
*UppChars (mapcar char (range (char "A") (char "Z")))
*LowChars (mapcar lowc *UppChars)
*Digits (mapcar format (range 0 9))
*Others (chop "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~") )
# Command line options
(de -count ()
(setq *PwCount (format (opt))) )
(de -length ()
(setq *PwLength (format (opt))) )
(de -seed ()
(seed (opt)) )
(de -exclude ()
(for C (chop (opt))
(del C '*UppChars)
(del C '*LowChars)
(del C '*Digits)
(del C '*Others) ) )
(de -help ()
(prinl "Generate password(s)")
(prinl "Options:")
(prinl " --help")
(prinl " --count <num>")
(prinl " --length <num>")
(prinl " --seed <chars>")
(prinl " --exclude <chars>")
(bye) )
(load T)
# Return random character from list
(de randChar (Lst)
(get Lst (rand 1 (length Lst))) )
# Generate password(s)
(do *PwCount
(prinl
(by '(NIL (rand)) sort
(make
(link
(randChar *UppChars) # At least one from each group
(randChar *LowChars)
(randChar *Digits)
(randChar *Others) )
(do (- *PwLength 4)
(link
(randChar
(caar
(rot '(*UppChars *Others *Digits *LowChars))) ) ) ) ) ) ) )
(bye) |
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
| #Julia | Julia | @everywhere using SHA
@everywhere function bruteForceRange(startSerial, numberToDo)
targets = ["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"]
targets = map(hex2bytes, targets)
for count = 1 : numberToDo
password = [UInt8(97 + x) for x in digits(UInt8, startSerial + count, 26, 5)]
hashbytes = sha256(password)
if (hashbytes[1] == 0x11 || hashbytes[1] == 0x3a || hashbytes[1] == 0x74) && findfirst(targets, hashbytes) > 0
hexstring = join(hex(x,2) for x in hashbytes)
passwordstring = join(map(Char, password))
println("$passwordstring --> $hexstring")
end
end
return 0
end
@everywhere perThread = div(26^5, Sys.CPU_CORES)
pmap(x -> bruteForceRange(x * perThread, perThread), 0:Sys.CPU_CORES-1)
|
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
| #Kotlin | Kotlin | // version 1.1.51
import java.security.MessageDigest
fun stringHashToByteHash(hash: String): ByteArray {
val ba = ByteArray(32)
for (i in 0 until 64 step 2) ba[i / 2] = hash.substring(i, i + 2).toInt(16).toByte()
return ba
}
fun ByteArray.matches(other: ByteArray): Boolean {
for (i in 0 until 32) {
if (this[i] != other[i]) return false
}
return true
}
fun main(args: Array<String>) {
val stringHashes = listOf(
"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"
)
val byteHashes = List(3) { stringHashToByteHash(stringHashes[it]) }
val letters = List(26) { (97 + it).toByte() }
letters.stream().parallel().forEach {
val md = MessageDigest.getInstance("SHA-256")
val range = 97..122
val pwd = ByteArray(5)
pwd[0] = it
for (i1 in range) {
pwd[1] = i1.toByte()
for (i2 in range) {
pwd[2] = i2.toByte()
for (i3 in range) {
pwd[3] = i3.toByte()
for (i4 in range) {
pwd[4] = i4.toByte()
val ba = md.digest(pwd)
for (j in 0..2) {
if (ba.matches(byteHashes[j])) {
val password = pwd.toString(Charsets.US_ASCII)
println("$password => ${stringHashes[j]}")
break
}
}
}
}
}
}
}
} |
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.
| #Kotlin | Kotlin | // version 1.1.51
import java.util.stream.Collectors
/* returns the number itself, its smallest prime factor and all its prime factors */
fun primeFactorInfo(n: Int): Triple<Int, Int, List<Int>> {
if (n <= 1) throw IllegalArgumentException("Number must be more than one")
if (isPrime(n)) return Triple(n, n, listOf(n))
val factors = mutableListOf<Int>()
var factor = 2
var nn = n
while (true) {
if (nn % factor == 0) {
factors.add(factor)
nn /= factor
if (nn == 1) return Triple(n, factors.min()!!, factors)
if (isPrime(nn)) factor = nn
}
else if (factor >= 3) factor += 2
else factor = 3
}
}
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun main(args: Array<String>) {
val numbers = listOf(
12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519
)
val info = numbers.stream()
.parallel()
.map { primeFactorInfo(it) }
.collect(Collectors.toList())
val maxFactor = info.maxBy { it.second }!!.second
val results = info.filter { it.second == maxFactor }
println("The following number(s) have the largest minimal prime factor of $maxFactor:")
for (result in results) {
println(" ${result.first} whose prime factors are ${result.third}")
}
} |
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.
| #Ela | Ela | open string generic monad io
type OpType = Push | Operate
deriving Show
type Op = Op (OpType typ) input stack
deriving Show
parse str = split " " str
eval stack [] = []
eval stack (x::xs) = op :: eval nst xs
where (op, nst) = conv x stack
conv "+"@x = operate x (+)
conv "-"@x = operate x (-)
conv "*"@x = operate x (*)
conv "/"@x = operate x (/)
conv "^"@x = operate x (**)
conv x = \stack ->
let n = gread x::stack in
(Op Push x n, n)
operate input fn (x::y::ys) =
let n = (y `fn` x) :: ys in
(Op Operate input n, n)
print_line (Op typ input stack) = do
putStr input
putStr "\t"
put typ
putStr "\t\t"
putLn stack
print ((Op typ input stack)@x::xs) lv = print_line x `seq` print xs (head stack)
print [] lv = lv
print_result xs = do
putStrLn "Input\tOperation\tStack after"
res <- return $ print xs 0
putStrLn ("Result: " ++ show res)
res = parse "3 4 2 * 1 5 - 2 3 ^ ^ / +" |> eval []
print_result res ::: IO |
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.
| #Erlang | Erlang | -module(rpn).
-export([eval/1]).
parse(Expression) ->
parse(string:tokens(Expression," "),[]).
parse([],Expression) ->
lists:reverse(Expression);
parse(["+"|Xs],Expression) ->
parse(Xs,[fun erlang:'+'/2|Expression]);
parse(["-"|Xs],Expression) ->
parse(Xs,[fun erlang:'-'/2|Expression]);
parse(["*"|Xs],Expression) ->
parse(Xs,[fun erlang:'*'/2|Expression]);
parse(["/"|Xs],Expression) ->
parse(Xs,[fun erlang:'/'/2|Expression]);
parse(["^"|Xs],Expression) ->
parse(Xs,[fun math:pow/2|Expression]);
parse([X|Xs],Expression) ->
{N,_} = string:to_integer(X),
parse(Xs,[N|Expression]).
%% The expression should be entered as a string of numbers and
%% operators separated by spaces. No error handling is included if
%% another string format is used.
eval(Expression) ->
eval(parse(Expression),[]).
eval([],[N]) ->
N;
eval([N|Exp],Stack) when is_number(N) ->
NewStack = [N|Stack],
print(NewStack),
eval(Exp,NewStack);
eval([F|Exp],[X,Y|Stack]) ->
NewStack = [F(Y,X)|Stack],
print(NewStack),
eval(Exp,NewStack).
print(Stack) ->
lists:map(fun (X) when is_integer(X) -> io:format("~12.12b ",[X]);
(X) when is_float(X) -> io:format("~12f ",[X]) end, Stack),
io:format("~n"). |
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
| #ACL2 | ACL2 | (defun reverse-split-at-r (xs i ys)
(if (zp i)
(mv xs ys)
(reverse-split-at-r (rest xs) (1- i)
(cons (first xs) ys))))
(defun reverse-split-at (xs i)
(reverse-split-at-r xs i nil))
(defun is-palindrome (str)
(let* ((lngth (length str))
(idx (floor lngth 2)))
(mv-let (xs ys)
(reverse-split-at (coerce str 'list) idx)
(if (= (mod lngth 2) 1)
(equal (rest xs) ys)
(equal xs ys))))) |
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.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func ord(n uint) string {
var suffix string
if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {
suffix = "th"
} else {
switch n % 10 {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
default:
suffix = "th"
}
}
return fmt.Sprintf("%s%s", commatize(n), suffix)
}
func main() {
const max = 10_000_000
data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},
{1e6, 1e6, 16}, {1e7, 1e7, 18}}
results := make(map[uint][]uint64)
for _, d := range data {
for i := d[0]; i <= d[1]; i++ {
results[i] = make([]uint64, 9)
}
}
var p uint64
outer:
for d := uint64(1); d < 10; d++ {
count := uint(0)
pow := uint64(1)
fl := d * 11
for nd := 3; nd < 20; nd++ {
slim := (d + 1) * pow
for s := d * pow; s < slim; s++ {
e := reverse(s)
mlim := uint64(1)
if nd%2 == 1 {
mlim = 10
}
for m := uint64(0); m < mlim; m++ {
if nd%2 == 0 {
p = s*pow*10 + e
} else {
p = s*pow*100 + m*pow*10 + e
}
if p%fl == 0 {
count++
if _, ok := results[count]; ok {
results[count][d-1] = p
}
if count == max {
continue outer
}
}
}
}
if nd%2 == 1 {
pow *= 10
}
}
}
for _, d := range data {
if d[0] != d[1] {
fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1]))
} else {
fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0]))
}
for i := 1; i <= 9; i++ {
fmt.Printf("%d: ", i)
for j := d[0]; j <= d[1]; j++ {
fmt.Printf("%*d ", d[2], results[j][i-1])
}
fmt.Println()
}
fmt.Println()
}
} |
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.
| #Julia | Julia |
function parseinfix2rpn(s)
outputq = []
opstack = []
infix = split(s)
for tok in infix
if all(isnumber, tok)
push!(outputq, tok)
elseif tok == "("
push!(opstack, tok)
elseif tok == ")"
while !isempty(opstack) && (op = pop!(opstack)) != "("
push!(outputq, op)
end
else # operator
while !isempty(opstack)
op = pop!(opstack)
if Base.operator_precedence(Symbol(op)) > Base.operator_precedence(Symbol(tok)) ||
(Base.operator_precedence(Symbol(op)) ==
Base.operator_precedence(Symbol(tok)) && op != "^")
push!(outputq, op)
else
push!(opstack, op) # undo peek
break
end
end
push!(opstack, tok)
end
println("The working output stack is $outputq")
end
while !isempty(opstack)
if (op = pop!(opstack)) == "("
throw("mismatched parentheses")
else
push!(outputq, op)
end
end
outputq
end
teststring = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
println("\nResult: $teststring becomes $(join(parseinfix2rpn(teststring), ' '))")
|
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
| #PARI.2FGP | PARI/GP | paraffin(p) =
{
local (P = p+1, R, U = R = Vec([1,1], P));
for (n = 1, p,
((B,n,C,S,l=n) -> my(b,c,i,s);
for (b = 1, 4-B,
if ((s = S + b * n) < P,
c = R[n+1] * C * prod(i = 1, b-1, (R[n+1]+i)/(i+1));
if (l+l < s, U[s+1] += c);
if (B+b < 4, R[s+1] += c; i = n; while (i--, self()(B+b, i, c, s, l)))))
)(0,n,1,1);
if (n % 2,, U[n+1] += R[n/2+1] * (R[n/2+1]+1)/2);
print([n, U[n+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
| #BBC_BASIC | BBC BASIC | FOR test% = 1 TO 2
READ test$
PRINT """" test$ """ " ;
IF FNpangram(test$) THEN
PRINT "is a pangram"
ELSE
PRINT "is not a pangram"
ENDIF
NEXT test%
END
DATA "The quick brown fox jumped over the lazy dog"
DATA "The five boxing wizards jump quickly"
DEF FNpangram(A$)
LOCAL C%
A$ = FNlower(A$)
FOR C% = ASC("a") TO ASC("z")
IF INSTR(A$, CHR$(C%)) = 0 THEN = FALSE
NEXT
= TRUE
DEF FNlower(A$)
LOCAL A%, C%
FOR A% = 1 TO LEN(A$)
C% = ASCMID$(A$,A%)
IF C% >= 65 IF C% <= 90 MID$(A$,A%,1) = CHR$(C%+32)
NEXT
= A$ |
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
| #BCPL | BCPL | get "libhdr"
// Test if s is a pangram. The ASCII character set is assumed.
let pangram(s) = valof
$( let letters = vec 25
for i=0 to 25 do letters!i := false
for i=1 to s%0 do
$( let c = (s%i | 32) - 'a'
if c >= 0 & c < 26 then
letters!c := true
$)
for i=0 to 25 unless letters!i resultis false
resultis true
$)
// Display s and whether or not it is a pangram.
let check(s) be
$( writes(s)
writes(" -> ")
test pangram(s)
then writes("yes*N")
else writes("no*N")
$)
let start() be
$( check("The quick brown fox jumps over the lazy dog.")
check("The five boxing wizards dump quickly.")
$) |
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.
| #Go | Go | package main
import (
"fmt"
"strings"
)
func binomial(n, k int) int {
if n < k {
return 0
}
if n == 0 || k == 0 {
return 1
}
num := 1
for i := k + 1; i <= n; i++ {
num *= i
}
den := 1
for i := 2; i <= n-k; i++ {
den *= i
}
return num / den
}
func pascalUpperTriangular(n int) [][]int {
m := make([][]int, n)
for i := 0; i < n; i++ {
m[i] = make([]int, n)
for j := 0; j < n; j++ {
m[i][j] = binomial(j, i)
}
}
return m
}
func pascalLowerTriangular(n int) [][]int {
m := make([][]int, n)
for i := 0; i < n; i++ {
m[i] = make([]int, n)
for j := 0; j < n; j++ {
m[i][j] = binomial(i, j)
}
}
return m
}
func pascalSymmetric(n int) [][]int {
m := make([][]int, n)
for i := 0; i < n; i++ {
m[i] = make([]int, n)
for j := 0; j < n; j++ {
m[i][j] = binomial(i+j, i)
}
}
return m
}
func printMatrix(title string, m [][]int) {
n := len(m)
fmt.Println(title)
fmt.Print("[")
for i := 0; i < n; i++ {
if i > 0 {
fmt.Print(" ")
}
mi := strings.Replace(fmt.Sprint(m[i]), " ", ", ", -1)
fmt.Print(mi)
if i < n-1 {
fmt.Println(",")
} else {
fmt.Println("]\n")
}
}
}
func main() {
printMatrix("Pascal upper-triangular matrix", pascalUpperTriangular(5))
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(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. | #Raku | Raku | use DBIish;
my $db = DBIish.connect('DBI:mysql:mydatabase:host','login','password');
my $update = $db.prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?");
my $rows-affected = $update.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. | #Ruby | Ruby | require 'sqlite3'
db = SQLite3::Database.new(":memory:")
# setup
db.execute('create temp table players (name, score, active, jerseyNum)')
db.execute('insert into players values ("name",0,"false",99)')
db.execute('insert into players values ("name",0,"false",100)')
db.execute('insert into players values ("name",0,"false",101)')
# demonstrate parameterized SQL
# example 1 -- simple placeholders
db.execute('update players set name=?, score=?, active=? where jerseyNum=?', 'Smith, Steve', 42, true, 99)
# example 2 -- named placeholders
db.execute('update players set name=:name, score=:score, active=:active where jerseyNum=:num',
:num => 100,
:name => 'John Doe',
:active => false,
:score => -1
)
# example 3 -- numbered placeholders
stmt = db.prepare('update players set name=?4, score=?3, active=?2 where jerseyNum=?1')
stmt.bind_param(1, 101)
stmt.bind_param(2, true)
stmt.bind_param(3, 3)
stmt.bind_param(4, "Robert'; DROP TABLE players--")
stmt.execute
# and show the results
db.execute2('select * from players') {|row| p row} |
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
| #CoffeeScript | CoffeeScript |
pascal = (n) ->
width = 6
for r in [1..n]
s = ws (width/2) * (n-r) # center row
output = (n) -> s += pad width, n
cell = 1
output cell
# Compute binomial coefficients as you go
# across the row.
for c in [1...r]
cell *= (r-c) / c
output cell
console.log s
ws = (n) ->
s = ''
s += ' ' for i in [0...n]
s
pad = (cnt, n) ->
s = n.toString()
# There is probably a better way to do this.
cnt -= s.length
right = Math.floor(cnt / 2)
left = cnt - right
ws(left) + s + ws(right)
pascal(7)
|
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.
| #REXX | REXX | /*REXX program parses an IP address into ──► IPv4 or IPv6 format, optional pport.*/
_= "_"; say center('input IP address' , 30),
center('hex IP address' , 32),
center('decimal IP address' , 39) "space port"
say copies(_, 30) copies(_, 32) copies(_, 39) copies(_, 5) copies(_, 5)
call IP_parse 127.0.0.1 /*this simple IP doesn't need quotes.*/
call IP_parse '127.0.0.1:80'
call IP_parse '::1'
call IP_parse '[::1]:80'
call IP_parse '2605:2700:0:3::4713:93e3'
call IP_parse '[2605:2700:0:3::4713:93e3]:80'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
IP_parse: procedure; parse arg a .; hx=; @.=; numeric digits 50
dot= pos(., a)\==0 /*see if there is a dot present in IP. */
if dot then do; parse var a @.1 '.' @.2 "." @.3 '.' @.4 ":" port
do j=1 for 4; hx= hx || d2x(@.j, 2)
end /*j*/
end
else do; parse var a pureA ']:' port
_= space( translate( pureA, , '[]'), 0) /*remove brackets.*/
parse var _ x '::' y
do L=1 until x=='' /*get left side. */
parse var x @.L ':' x
end /*L*/
y= reverse(y)
do r=8 by -1 /*get right side. */
parse var y z ':' y; if z=='' then leave
@.r= reverse(z)
end /*r*/
do k=1 for 8; hx=hx || right( word(@.k 0, 1), 4, 0)
end /*k*/
end
say left(a,30) right(hx,32) right(x2d(hx),39) ' IPv' || (6-2*dot) right(port,5)
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.
| #Lua | Lua | function tokenize(rpn)
local out = {}
local cnt = 0
for word in rpn:gmatch("%S+") do
table.insert(out, word)
cnt = cnt + 1
end
return {tokens = out, pos = 1, size = cnt}
end
function advance(lex)
if lex.pos <= lex.size then
lex.pos = lex.pos + 1
return true
else
return false
end
end
function current(lex)
return lex.tokens[lex.pos]
end
function isOperator(sym)
return sym == '+' or sym == '-'
or sym == '*' or sym == '/'
or sym == '^'
end
function buildTree(lex)
local stack = {}
while lex.pos <= lex.size do
local sym = current(lex)
advance(lex)
if isOperator(sym) then
local b = table.remove(stack)
local a = table.remove(stack)
local t = {op=sym, left=a, right=b}
table.insert(stack, t)
else
table.insert(stack, sym)
end
end
return table.remove(stack)
end
function infix(tree)
if type(tree) == "table" then
local a = {}
local b = {}
if type(tree.left) == "table" then
a = '(' .. infix(tree.left) .. ')'
else
a = tree.left
end
if type(tree.right) == "table" then
b = '(' .. infix(tree.right) .. ')'
else
b = tree.right
end
return a .. ' ' .. tree.op .. ' ' .. b
else
return tree
end
end
function convert(str)
local lex = tokenize(str)
local tree = buildTree(lex)
print(infix(tree))
end
function main()
convert("3 4 2 * 1 5 - 2 3 ^ ^ / +")
convert("1 2 + 3 4 + ^ 5 6 + ^")
end
main() |
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.
| #min | min | 'map :fs
(dup +) :f1
(dup *) :f2
('f1 fs) :fsf1
('f2 fs) :fsf2
(0 1 2 3) fsf1 puts!
(0 1 2 3) fsf2 puts!
(2 4 6 8) fsf1 puts!
(2 4 6 8) fsf2 puts! |
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.
| #Nemerle | Nemerle | using System;
using System.Console;
module Partial
{
fs[T] (f : T -> T, s : list[T]) : list[T]
{
$[f(x)| x in s]
}
f1 (x : int) : int
{
x * 2
}
f2 (x : int) : int
{
x * x
}
curry[T, U, V] (f : T * U -> V, x : T) : U -> V
{
f(x, _)
}
// curryr() isn't actually used in this task, I just include it for symmetry
curryr[T, U, V] (f : T * U -> V, x : U) : T -> V
{
f(_, x)
}
Main() : void
{
def fsf1 = curry(fs, f1);
def fsf2 = curry(fs, f2);
def test1 = $[0 .. 3];
def test2 = $[x | x in [2 .. 8], x % 2 == 0];
WriteLine (fsf1(test1));
WriteLine (fsf1(test2));
WriteLine (fsf2(test1));
WriteLine (fsf2(test2));
}
} |
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
| #zkl | zkl | // Partition integer N into M unique primes
fcn partition(N,M,idx=0,ps=List()){
var [const] sieve=Utils.Generator(Import("sieve").postponed_sieve);
var [const] primes=List();
while(sieve.peek()<=N){ primes.append(sieve.next()) }
if(M<2){
z:=primes.find(N);
return(if(Void!=z and z>=idx) ps.append(N) else Void);
}
foreach z in ([idx..primes.len()-1]){
p:=primes[z];
if(p<=N and self.fcn(N-p,M-1,z+1,ps)) return(ps.insert(0,p));
if(p>N) break;
}
Void // no solution
} |
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.
| #Tcl | Tcl | package require Tcl 8.5
namespace path ::tcl::mathop
set pyramid {
{151.0 "" "" "" ""}
{"" "" "" "" ""}
{40.0 "" "" "" ""}
{"" "" "" "" ""}
{x 11.0 y 4.0 z}
}
set equations {{1 -1 1 0}}
proc simplify {terms val} {
set vars {0 0 0}
set x 0
set y 1
set z 2
foreach term $terms {
switch -exact -- $term {
x - y - z {
lset vars [set $term] [+ 1 [lindex $vars [set $term]]]
}
default {
set val [- $val $term]
}
}
}
return [concat $vars $val]
}
for {set row [+ [llength $pyramid] -2]} {$row >= 0} {incr row -1} {
for {set cell 0} {$cell <= $row} {incr cell } {
set sum [concat [lindex $pyramid [+ 1 $row] $cell] [lindex $pyramid [+ 1 $row] [+ 1 $cell]]]
if {[set val [lindex $pyramid $row $cell]] ne ""} {
lappend equations [simplify $sum $val]
} else {
lset pyramid $row $cell $sum
}
}
}
set solution [toRREF $equations]
foreach row $solution {
lassign $row a b c d
if {$a + $b + $c > 1} {
error "problem does not have a unique solution"
}
if {$a} {set x $d}
if {$b} {set y $d}
if {$c} {set z $d}
}
puts "x=$x"
puts "y=$y"
puts "z=$z"
foreach row $pyramid {
set newrow {}
foreach cell $row {
if {$cell eq ""} {
lappend newrow ""
} else {
lappend newrow [expr [join [string map [list x $x y $y z $z] $cell] +]]
}
}
lappend solved $newrow
}
print_matrix $solved |
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
| #PowerShell | PowerShell |
function New-RandomPassword
{
<#
.SYNOPSIS
Generates one or more passwords.
.DESCRIPTION
Generates one or more passwords.
.PARAMETER Length
The password length (default = 8).
.PARAMETER Count
The number of passwords to generate.
.PARAMETER Source
An array of strings containing characters from which the password will be generated. The default is good for most uses.
.PARAMETER ExcludeSimilar
A switch which indicates that visually similar characters should be ignored.
.EXAMPLE
New-RandomPassword
Generates one password of the default length (8 characters).
.EXAMPLE
New-RandomPassword -Count 4
Generates four passwords each of the default length (8 characters).
.EXAMPLE
New-RandomPassword -Length 12 -Source abcdefghijklmnopqrstuvwxyz, ABCDEFGHIJKLMNOPQRSTUVWXYZ, 0123456789
Generates a password with a length of 12 containing at least one char from each string in Source
.EXAMPLE
New-RandomPassword -Count 4 -ExcludeSimilar
Generates four passwords each of the default length (8 characters) while excluding similar characters "Il1O05S2Z".
#>
[CmdletBinding()]
[OutputType([string])]
Param
(
[Parameter(Mandatory=$false)]
[ValidateRange(1,[Int]::MaxValue)]
[Alias("l")]
[int]
$Length = 8,
[Parameter(Mandatory=$false)]
[ValidateRange(1,[Int]::MaxValue)]
[Alias("n","c")]
[int]
$Count = 1,
[Parameter(Mandatory=$false)]
[Alias("s")]
[string[]]
$Source = @("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "0123456789", "!\`"#$%&'()*+,-./:;<=>?@[]^_{|}~"),
[Parameter(Mandatory=$false)]
[Alias("x")]
[switch]
$ExcludeSimilar
)
Begin
{
[char[][]] $charArrays = $Source
[char[]] $allChars = $charArrays | ForEach-Object {$_}
[char[]] $similar = "Il1O05S2Z".ToCharArray()
$random = New-Object -TypeName System.Security.Cryptography.RNGCryptoServiceProvider
function Get-Seed
{
$bytes = New-Object -TypeName System.Byte[] -Argument 4
$random.GetBytes($bytes)
[BitConverter]::ToUInt32($bytes, 0)
}
function Add-PasswordCharacter ([char[]]$From)
{
$key = Get-Seed
while ($password.ContainsKey($key))
{
$key = Get-Seed
}
$index = (Get-Seed) % $From.Count
if ($ExcludeSimilar)
{
while ($From[$index] -in $similar)
{
$index = (Get-Seed) % $From.Count
}
}
$password.Add($key, $From[$index])
}
}
Process
{
for ($i = 1;$i -le $Count; $i++)
{
[hashtable] $password = @{}
foreach ($array in $charArrays)
{
if($password.Count -lt $Length)
{
Add-PasswordCharacter -From $array # Append to $password
}
}
for ($j = $password.Count; $j -lt $Length; $j++)
{
Add-PasswordCharacter -From $allChars # Append to $password
}
($password.GetEnumerator() | Select-Object -ExpandProperty Value) -join ""
}
}
}
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | testPassword[pass_String] :=
If[MemberQ[{16^^1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad,
16^^3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b,
16^^74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f},
Hash[pass, "SHA256"]], Print[pass]];
chars=CharacterRange["a","z"];
ParallelDo[
testPassword[StringJoin[a, b, c, d, e]],
{a, chars}, {b, chars}, {c, chars}, {d, chars}, {e, chars}] |
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
| #Modula-2 | Modula-2 | MODULE PBF;
FROM FormatString IMPORT FormatString;
FROM SHA256 IMPORT SHA256,Create,Destroy,HashBytes,Finalize,GetHash;
FROM SYSTEM IMPORT ADR,ADDRESS,BYTE;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
FROM Threads IMPORT Thread,CreateThread,WaitForThreadTermination;
PROCEDURE PrintHexBytes(str : ARRAY OF BYTE; limit : INTEGER);
VAR
buf : ARRAY[0..7] OF CHAR;
i,v : INTEGER;
BEGIN
i := 0;
WHILE i<limit DO
v := ORD(str[i]);
IF v < 16 THEN
WriteString("0")
END;
FormatString("%h", buf, v);
WriteString(buf);
INC(i);
END
END PrintHexBytes;
PROCEDURE Check(str : ARRAY OF CHAR);
TYPE
HA = ARRAY[0..31] OF BYTE;
CONST
h1 = HA{3aH, 7bH, 0d3H, 0e2H, 36H, 0aH, 3dH, 29H, 0eeH, 0a4H, 36H, 0fcH, 0fbH, 7eH, 44H, 0c7H, 35H, 0d1H, 17H, 0c4H, 2dH, 1cH, 18H, 35H, 42H, 0bH, 6bH, 99H, 42H, 0ddH, 4fH, 1bH};
h2 = HA{74H, 0e1H, 0bbH, 62H, 0f8H, 0daH, 0bbH, 81H, 25H, 0a5H, 88H, 52H, 0b6H, 3bH, 0dfH, 6eH, 0aeH, 0f6H, 67H, 0cbH, 56H, 0acH, 7fH, 7cH, 0dbH, 0a6H, 0d7H, 30H, 5cH, 50H, 0a2H, 2fH};
h3 = HA{11H, 15H, 0ddH, 80H, 0fH, 0eaH, 0acH, 0efH, 0dfH, 48H, 1fH, 1fH, 90H, 70H, 37H, 4aH, 2aH, 81H, 0e2H, 78H, 80H, 0f1H, 87H, 39H, 6dH, 0b6H, 79H, 58H, 0b2H, 07H, 0cbH, 0adH};
VAR
hash : SHA256;
out : ARRAY[0..31] OF BYTE;
i : CARDINAL;
match : BOOLEAN;
BEGIN
hash := Create();
HashBytes(hash, ADR(str), HIGH(str)+1);
Finalize(hash);
GetHash(hash, out);
Destroy(hash);
match := TRUE;
FOR i:=0 TO HIGH(out) DO
IF out[i] # h1[i] THEN
match := FALSE;
BREAK
END
END;
IF match THEN
WriteString(str);
WriteString(" ");
PrintHexBytes(out, 32);
WriteLn;
RETURN
END;
match := TRUE;
FOR i:=0 TO HIGH(out) DO
IF out[i] # h2[i] THEN
match := FALSE;
BREAK
END
END;
IF match THEN
WriteString(str);
WriteString(" ");
PrintHexBytes(out, 32);
WriteLn;
RETURN
END;
match := TRUE;
FOR i:=0 TO HIGH(out) DO
IF out[i] # h3[i] THEN
match := FALSE;
BREAK
END
END;
IF match THEN
WriteString(str);
WriteString(" ");
PrintHexBytes(out, 32);
WriteLn
END
END Check;
PROCEDURE CheckWords(a : CHAR);
VAR
word : ARRAY[0..4] OF CHAR;
b,c,d,e : CHAR;
BEGIN
word[0] := a;
FOR b:='a' TO 'z' DO
word[1] := b;
FOR c:='a' TO 'z' DO
word[2] := c;
FOR d:='a' TO 'z' DO
word[3] := d;
FOR e:='a' TO 'z' DO
word[4] := e;
Check(word)
END
END
END
END
END CheckWords;
PROCEDURE CheckAF(ptr : ADDRESS) : CARDINAL;
VAR a : CHAR;
BEGIN
FOR a:='a' TO 'f' DO
CheckWords(a)
END;
RETURN 0
END CheckAF;
PROCEDURE CheckGM(ptr : ADDRESS) : CARDINAL;
VAR a : CHAR;
BEGIN
FOR a:='g' TO 'm' DO
CheckWords(a)
END;
RETURN 0
END CheckGM;
PROCEDURE CheckNS(ptr : ADDRESS) : CARDINAL;
VAR a : CHAR;
BEGIN
FOR a:='n' TO 's' DO
CheckWords(a)
END;
RETURN 0
END CheckNS;
PROCEDURE CheckTZ(ptr : ADDRESS) : CARDINAL;
VAR a : CHAR;
BEGIN
FOR a:='t' TO 'z' DO
CheckWords(a)
END;
RETURN 0
END CheckTZ;
VAR
t1,t2,t3,t4 : Thread;
s1,s2,s3,s4 : CARDINAL;
BEGIN
CreateThread(t1,CheckAF,NIL,0,TRUE);
CreateThread(t2,CheckGM,NIL,0,TRUE);
CreateThread(t3,CheckNS,NIL,0,TRUE);
CreateThread(t4,CheckTZ,NIL,0,TRUE);
WaitForThreadTermination(t1,-1,s1);
WaitForThreadTermination(t2,-1,s2);
WaitForThreadTermination(t3,-1,s3);
WaitForThreadTermination(t4,-1,s4);
WriteString("Done");
WriteLn;
ReadChar
END PBF. |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | hasSmallestFactor[data_List]:=Sort[Transpose[{ParallelTable[FactorInteger[x][[1, 1]], {x, data}],data}]][[1, 2]] |
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.
| #Nim | Nim | import strformat, strutils, threadpool
const Numbers = [576460752303423487,
576460752303423487,
576460752303423487,
112272537195293,
115284584522153,
115280098190773,
115797840077099,
112582718962171,
299866111963290359]
proc lowestFactor(n: int64): int64 =
if n mod 2 == 0: return 2
if n mod 3 == 0: return 3
var p = 5
var delta = 2
while p * p < n:
if n mod p == 0: return p
inc p, delta
delta = 6 - delta
result = n
proc factors(n, lowest: int64): seq[int64] =
var n = n
var lowest = lowest
while true:
result.add lowest
n = n div lowest
if n == 1: break
lowest = lowestFactor(n)
# Launch a thread for each number to process.
var responses: array[Numbers.len, FlowVar[int64]]
for i, n in Numbers:
responses[i] = spawn lowestFactor(n)
# Read the results and find the largest minimum prime factor.
var maxMinfact = 0i64
var maxIdx: int
for i in 0..responses.high:
let minfact = ^responses[i] # Blocking read.
echo &"For n = {Numbers[i]}, the lowest factor is {minfact}."
if minfact > maxMinfact:
maxMinfact = minfact
maxIdx = i
let result = Numbers[maxIdx]
echo ""
echo "The first number with the largest minimum prime factor is: ", result
echo "Its factors are: ", result.factors(maxMinfact).join(", ") |
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.
| #F.23 | F# | let reduce op = function
| b::a::r -> (op a b)::r
| _ -> failwith "invalid expression"
let interprete s = function
| "+" -> "add", reduce ( + ) s
| "-" -> "subtr", reduce ( - ) s
| "*" -> "mult", reduce ( * ) s
| "/" -> "divide", reduce ( / ) s
| "^" -> "exp", reduce ( ** ) s
| str -> "push", (System.Double.Parse str) :: s
let interp_and_show s inp =
let op,s'' = interprete s inp
printf "%5s%8s " inp op
List.iter (printf " %-6.3F") (List.rev s'')
printf "\n";
s''
let eval str =
printfn "Token Action Stack";
let ss = str.ToString().Split() |> Array.toList
List.fold interp_and_show [] ss |
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
| #Action.21 | Action! | BYTE FUNC Palindrome(CHAR ARRAY s)
BYTE l,r
l=1 r=s(0)
WHILE l<r
DO
IF s(l)#s(r) THEN RETURN (0) FI
l==+1 r==-1
OD
RETURN (1)
BYTE FUNC IsIgnored(BYTE c)
IF (c>=' AND c<='/) OR
(c>=': AND c<='@) OR
(c>='[ AND c<='_) THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC ToUpper(BYTE c)
IF c>='a AND c<='z THEN
RETURN (c-'a+'A)
FI
RETURN (c)
BYTE FUNC InexactPalindrome(CHAR ARRAY s)
BYTE l,r,lc,rc
l=1 r=s(0)
WHILE l<r
DO
WHILE IsIgnored(s(l))
DO
l==+1
IF l>=r THEN RETURN (1) FI
OD
WHILE IsIgnored(s(r))
DO
r==-1
IF l>=r THEN RETURN (1) FI
OD
lc=ToUpper(s(l))
rc=ToUpper(s(r))
IF lc#rc THEN RETURN (0) FI
l==+1 r==-1
OD
RETURN (1)
PROC Test(CHAR ARRAY s)
IF Palindrome(s) THEN
PrintF("'%S' is a palindrome%E%E",s)
ELSEIF InexactPalindrome(s) THEN
PrintF("'%S' is an inexact palindrome%E%E",s)
ELSE
PrintF("'%S' is not a palindrome%E%E",s)
FI
RETURN
PROC Main()
Test("rotavator")
Test("13231+464+989=989+464+13231")
Test("Was it a car or a cat I saw?")
Test("Did Hannah see bees? Hannah did.")
Test("This sentence is not a palindrome.")
Test("123 456 789 897 654 321")
RETURN |
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.
| #Go | Go | package main
import "fmt"
func reverse(s uint64) uint64 {
e := uint64(0)
for s > 0 {
e = e*10 + (s % 10)
s /= 10
}
return e
}
func commatize(n uint) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func ord(n uint) string {
var suffix string
if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {
suffix = "th"
} else {
switch n % 10 {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
default:
suffix = "th"
}
}
return fmt.Sprintf("%s%s", commatize(n), suffix)
}
func main() {
const max = 10_000_000
data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},
{1e6, 1e6, 16}, {1e7, 1e7, 18}}
results := make(map[uint][]uint64)
for _, d := range data {
for i := d[0]; i <= d[1]; i++ {
results[i] = make([]uint64, 9)
}
}
var p uint64
outer:
for d := uint64(1); d < 10; d++ {
count := uint(0)
pow := uint64(1)
fl := d * 11
for nd := 3; nd < 20; nd++ {
slim := (d + 1) * pow
for s := d * pow; s < slim; s++ {
e := reverse(s)
mlim := uint64(1)
if nd%2 == 1 {
mlim = 10
}
for m := uint64(0); m < mlim; m++ {
if nd%2 == 0 {
p = s*pow*10 + e
} else {
p = s*pow*100 + m*pow*10 + e
}
if p%fl == 0 {
count++
if _, ok := results[count]; ok {
results[count][d-1] = p
}
if count == max {
continue outer
}
}
}
}
if nd%2 == 1 {
pow *= 10
}
}
}
for _, d := range data {
if d[0] != d[1] {
fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1]))
} else {
fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0]))
}
for i := 1; i <= 9; i++ {
fmt.Printf("%d: ", i)
for j := d[0]; j <= d[1]; j++ {
fmt.Printf("%*d ", d[2], results[j][i-1])
}
fmt.Println()
}
fmt.Println()
}
} |
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.
| #Kotlin | Kotlin | // version 1.2.0
import java.util.Stack
/* To find out the precedence, we take the index of the
token in the OPS string and divide by 2 (rounding down).
This will give us: 0, 0, 1, 1, 2 */
const val OPS = "-+/*^"
fun infixToPostfix(infix: String): String {
val sb = StringBuilder()
val s = Stack<Int>()
val rx = Regex("""\s""")
for (token in infix.split(rx)) {
if (token.isEmpty()) continue
val c = token[0]
val idx = OPS.indexOf(c)
// check for operator
if (idx != - 1) {
if (s.isEmpty()) {
s.push(idx)
}
else {
while (!s.isEmpty()) {
val prec2 = s.peek() / 2
val prec1 = idx / 2
if (prec2 > prec1 || (prec2 == prec1 && c != '^')) {
sb.append(OPS[s.pop()]).append(' ')
}
else break
}
s.push(idx)
}
}
else if (c == '(') {
s.push(-2) // -2 stands for '('
}
else if (c == ')') {
// until '(' on stack, pop operators.
while (s.peek() != -2) sb.append(OPS[s.pop()]).append(' ')
s.pop()
}
else {
sb.append(token).append(' ')
}
}
while (!s.isEmpty()) sb.append(OPS[s.pop()]).append(' ')
return sb.toString()
}
fun main(args: Array<String>) {
val es = listOf(
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )"
)
for (e in es) {
println("Infix : $e")
println("Postfix : ${infixToPostfix(e)}\n")
}
} |
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
| #Pascal | Pascal | Program Paraffins;
uses
gmp;
const
max_n = 500;
branch = 4;
var
rooted, unrooted: array [0 .. max_n-1] of mpz_t;
c: array [0 .. branch-1] of mpz_t;
cnt, tmp: mpz_t;
n: integer;
fmt: pchar;
sum: integer;
procedure tree(br, n, l: integer; sum: integer; cnt: mpz_t);
var
b, m: integer;
begin
for b := br + 1 to branch do
begin
sum := sum + n;
if sum >= max_n then
exit;
(* prevent unneeded long math *)
if (l * 2 >= sum) and (b >= branch) then
exit;
if b = (br + 1) then
mpz_mul(c[br], rooted[n], cnt)
else
begin
mpz_add_ui(tmp, rooted[n], b - br - 1);
mpz_mul(c[br], c[br], tmp);
mpz_divexact_ui(c[br], c[br], b - br);
end;
if l * 2 < sum then
mpz_add(unrooted[sum], unrooted[sum], c[br]);
if b < branch then
begin
mpz_add(rooted[sum], rooted[sum], c[br]);
for m := n-1 downto 1 do
tree(b, m, l, sum, c[br]);
end;
end;
end;
procedure bicenter(s: integer);
begin
if odd(s) then
exit;
mpz_add_ui(tmp, rooted[s div 2], 1);
mpz_mul(tmp, rooted[s div 2], tmp);
mpz_tdiv_q_2exp(tmp, tmp, 1);
mpz_add(unrooted[s], unrooted[s], tmp);
end;
begin
for n := 0 to 1 do
begin
mpz_init_set_ui(rooted[n], 1);
mpz_init_set_ui(unrooted[n], 1);
end;
for n := 2 to max_n-1 do
begin
mpz_init_set_ui(rooted[n], 0);
mpz_init_set_ui(unrooted[n], 0);
end;
for n := 0 to BRANCH-1 do
mpz_init(c[n]);
mpz_init(tmp);
mpz_init_set_ui(cnt, 1);
sum := 1;
for n := 1 to MAX_N do
begin
tree(0, n, n, sum, cnt);
bicenter(n);
mp_printf('%d: %Zd'+chr(13)+chr(10), n, @unrooted[n]);
end;
end. |
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
| #Befunge | Befunge | >~>:65*`!#v_:"`"`48*v>g+04p1\4p
^#*`\*93\`0<::-"@"-*<^40!%2g4:_
"pangram."<v*84<_v#-":"g40\" a"
>>:#,_55+,@>"ton">48*>"si tahT" |
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
| #Bracmat | Bracmat | (isPangram=
k
. low$!arg:?arg
& a:?k
& whl
' ( @(!arg:? !k ?)
& chr$(1+asc$!k):?k:~>z
)
& !k:>z
&
); |
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.
| #Haskell | Haskell | import Data.List (transpose)
import System.Environment (getArgs)
import Text.Printf (printf)
-- Pascal's triangle.
pascal :: [[Int]]
pascal = iterate (\row -> 1 : zipWith (+) row (tail row) ++ [1]) [1]
-- The n by n Pascal lower triangular matrix.
pascLow :: Int -> [[Int]]
pascLow n = zipWith (\row i -> row ++ replicate (n-i) 0) (take n pascal) [1..]
-- The n by n Pascal upper triangular matrix.
pascUp :: Int -> [[Int]]
pascUp = transpose . pascLow
-- The n by n Pascal symmetric matrix.
pascSym :: Int -> [[Int]]
pascSym n = take n . map (take n) . transpose $ pascal
-- Format and print a matrix.
printMat :: String -> [[Int]] -> IO ()
printMat title mat = do
putStrLn $ title ++ "\n"
mapM_ (putStrLn . concatMap (printf " %2d")) mat
putStrLn "\n"
main :: IO ()
main = do
ns <- fmap (map read) getArgs
case ns of
[n] -> do printMat "Lower triangular" $ pascLow n
printMat "Upper triangular" $ pascUp n
printMat "Symmetric" $ pascSym n
_ -> error "Usage: pascmat <number>" |
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. | #Run_BASIC | Run BASIC | sqliteconnect #mem, ":memory:"
#mem execute("CREATE table players (name, score, active, jerseyNum)")
#mem execute("INSERT INTO players VALUES ('Jones, Bob',0,'N',99)")
#mem execute("INSERT INTO players VALUES ('Jesten, Jim',0,'N',100)")
#mem execute("INSERT INTO players VALUES ('Jello, Frank',0,'N',101)")
sql$ = "
UPDATE players
SET name = 'Smith, Steve',
score = 42,
active = 'TRUE'
WHERE jerseyNum = 99"
#mem execute(sql$)
#mem execute("SELECT * FROM players ORDER BY jerseyNum")
WHILE #mem hasanswer()
#row = #mem #nextrow()
name$ = #row name$()
score = #row score()
active$ = #row active$()
jerseyNum = #row jerseyNum()
print name$;chr$(9);score;chr$(9);active$;chr$(9);jerseyNum
WEND
end |
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. | #Scala | Scala | import slick.jdbc.H2Profile.api._
import slick.sql.SqlProfile.ColumnOption.SqlType
import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
object PlayersApp extends App {
lazy val playerRecords = TableQuery[PlayerRecords]
val db = Database.forURL("jdbc:h2:mem:test1;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver")
// Pre-compiled parameterized statement
val compiledUpdate = Compiled { jerseyN: Rep[Int] =>
for {c <- playerRecords if c.jerseyNum === jerseyN} yield (c.name, c.score, c.active)
}
def setup = DBIO.seq(
playerRecords.schema.create,
playerRecords ++= Seq( // JDBC batch update
(7, "Roethlisberger, Ben", 94.1f, true),
(11, "Smith, Alex", 85.3f, true),
(18, "Manning, Payton", 96.5f, false),
(99, "Doe, John", 15f, false))
)
def queryPlayers(prelude: String) = {
println("\n " +prelude)
println(
"│ Name │Scor│ Active │Jerseynum│\n" +
"├───────────────────────────────┼────┼────────┼─────────┤"
)
DBIO.seq(playerRecords.result.map(_.map {
case (jerseyN, name, score, active) =>
f"$name%32s $score ${(if (active) "" else "in") + "active"}%8s $jerseyN%8d"
}.foreach(println)))
}
// Definition of the PLAYERS table
class PlayerRecords(tag: Tag) extends Table[(Int, String, Float, Boolean)](tag, "PLAYER_RECORDS") {
def active = column[Boolean]("ACTIVE")
def jerseyNum = column[Int]("JERSEY_NUM", O.PrimaryKey)
def name = column[String]("NAME", SqlType("VARCHAR2(32)"))
def score = column[Float]("SCORE")
def * = (jerseyNum, name, score, active)
}
println(s"The pre-compiled parameterized update DML:\n${compiledUpdate(0).updateStatement}")
Await.result(db.run(
for { // Using the for comprehension
_ <- setup
_ <- queryPlayers("Before update:")
n <- compiledUpdate(99).update("Smith, Steve", 42f, true)
_ <- queryPlayers("After update:")
} yield n), Duration.Inf)
} |
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
| #Commodore_BASIC | Commodore BASIC | 10 INPUT "HOW MANY";N
20 IF N<1 THEN END
30 DIM C(N)
40 DIM D(N)
50 LET C(1)=1
60 LET D(1)=1
70 FOR J=1 TO N
80 FOR I=1 TO N-J+1
90 PRINT " ";
100 NEXT I
110 FOR I=1 TO J
120 PRINT C(I)" ";
130 NEXT I
140 PRINT
150 IF J=N THEN END
160 C(J+1)=1
170 D(J+1)=1
180 FOR I=1 TO J-1
190 D(I+1)=C(I)+C(I+1)
200 NEXT I
210 FOR I=1 TO J
220 C(I)=D(I)
230 NEXT I
240 NEXT J |
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.
| #Ruby | Ruby | require 'ipaddr'
TESTCASES = ["127.0.0.1", "127.0.0.1:80",
"::1", "[::1]:80",
"2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80"]
output = [%w(String Address Port Family Hex),
%w(------ ------- ---- ------ ---)]
def output_table(rows)
widths = []
rows.each {|row| row.each_with_index {|col, i| widths[i] = [widths[i].to_i, col.to_s.length].max }}
format = widths.map {|size| "%#{size}s"}.join("\t")
rows.each {|row| puts format % row}
end
TESTCASES.each do |str|
case str # handle port; IPAddr does not.
when /\A\[(?<address> .* )\]:(?<port> \d+ )\z/x # string like "[::1]:80"
address, port = $~[:address], $~[:port]
when /\A(?<address> [^:]+ ):(?<port> \d+ )\z/x # string like "127.0.0.1:80"
address, port = $~[:address], $~[:port]
else # string with no port number
address, port = str, nil
end
ip_addr = IPAddr.new(address)
family = "IPv4" if ip_addr.ipv4?
family = "IPv6" if ip_addr.ipv6?
output << [str, ip_addr.to_s, port.to_s, family, ip_addr.to_i.to_s(16)]
end
output_table(output) |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Rpn_2_Infix {
Rem Form 80,60
function rpn_to_infix$(a$) {
def m=0
inventory precendence="-":=2,"+":=2,"*":=3,"/":=3,"^":=4
dim token$()
token$()=piece$(a$," ")
l=len(token$())
dim type(l)=0, right(l)=0, infix$(l)
infix=-1
for i=0 to l-1
if exist(precendence, token$(i)) then
type(i)=precendence(token$(i))
if type(i)=4 then right(i)=-1
end if
if type(i)=0 then
infix++
infix$(infix)=token$(i)
type(infix)=100
else
if right(i) then
if type(infix)<type(i) then infix$(infix)="("+infix$(infix)+")"
if type(infix-1)<100 then infix$(infix-1)="("+infix$(infix-1)+")"
infix$(infix-1)=infix$(infix-1)+token$(i)+infix$(infix)
else
if type(infix)<type(i) then infix$(infix)="("+infix$(infix)+")"
if type(infix-1)<type(i) then
infix$(infix-1)="("+infix$(infix-1)+")"+token$(i)+infix$(infix)
else
infix$(infix-1)=infix$(infix-1)+token$(i)+infix$(infix)
end if
end if
type(infix-1)=type(i)
infix--
end if
inf=each(infix$(),1, infix+1)
while inf
export$<=token$(i)+" ["+str$(inf^,"")+"] "+ array$(inf)+{
}
token$(i)=" "
end while
next i
=infix$(0)
}
Global export$
document export$
example1=rpn_to_infix$("3 4 2 * 1 5 - 2 3 ^ ^ / +")="3+4*2/(1-5)^2^3"
example2=rpn_to_infix$("1 2 + 3 4 + ^ 5 6 + ^")="((1+2)^(3+4))^(5+6)"
\\ a test from Phix example
example3=rpn_to_infix$("moon stars mud + * fire soup * ^")="(moon*(stars+mud))^(fire*soup)"
Print example1, example2, example3
Rem Print #-2, Export$
ClipBoard Export$
}
Rpn_2_Infix
|
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.
| #Nim | Nim | import tables, strutils
const nPrec = 9
let ops: Table[string, tuple[prec: int, rAssoc: bool]] =
{ "^": (4, true)
, "*": (3, false)
, "/": (3, false)
, "+": (2, false)
, "-": (2, false)
}.toTable
proc parseRPN(e: string) =
echo "postfix: ", e
var stack = newSeq[tuple[prec: int, expr: string]]()
for tok in e.split:
echo "Token: ", tok
if ops.hasKey tok:
let op = ops[tok]
let rhs = stack.pop
var lhs = stack.pop
if lhs.prec < op.prec or (lhs.prec == op.prec and op.rAssoc):
lhs.expr = "(" & lhs.expr & ")"
lhs.expr.add " " & tok & " "
if rhs.prec < op.prec or (rhs.prec == op.prec and not op.rAssoc):
lhs.expr.add "(" & rhs.expr & ")"
else:
lhs.expr.add rhs.expr
lhs.prec = op.prec
stack.add lhs
else:
stack.add((nPrec, tok))
for f in stack:
echo " ", f.prec, " ", f.expr
echo "infix: ", stack[0].expr
for test in ["3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^"]:
test.parseRPN |
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.
| #Nim | Nim | import sequtils
type
Func = proc(n: int): int
FuncS = proc(f: Func; s: seq[int]): seq[int]
proc fs(f: Func; s: seq[int]): seq[int] = s.map(f)
proc partial(fs: FuncS; f: Func): auto =
result = proc(s: seq[int]): seq[int] = fs(f, s)
proc f1(n: int): int = 2 * n
proc f2(n: int): int = n * n
when isMainModule:
const Seqs = @[@[0, 1, 2, 3], @[2, 4, 6, 8]]
let fsf1 = partial(fs, f1)
let fsf2 = partial(fs, f2)
for s in Seqs:
echo fs(f1, s) # Normal.
echo fsf1(s) # Partial.
echo fs(f2, s) # Normal.
echo fsf2(s) # Partial.
echo "" |
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.
| #OCaml | OCaml | #
let fs f s = List.map f s
let f1 value = value * 2
let f2 value = value * value
let fsf1 = fs f1
let fsf2 = fs f2
;;
val fs : ('a -> 'b) -> 'a list -> 'b list = <fun>
val f1 : int -> int = <fun>
val f2 : int -> int = <fun>
val fsf1 : int list -> int list = <fun>
val fsf2 : int list -> int list = <fun>
# fsf1 [0; 1; 2; 3];;
- : int list = [0; 2; 4; 6]
# fsf2 [0; 1; 2; 3];;
- : int list = [0; 1; 4; 9]
# fsf1 [2; 4; 6; 8];;
- : int list = [4; 8; 12; 16]
# fsf2 [2; 4; 6; 8];;
- : int list = [4; 16; 36; 64] |
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.
| #Wren | Wren | import "/fmt" for Fmt
var isIntegral = Fn.new { |x, tol| x.fraction.abs <= tol }
var pascal = Fn.new { |a, b, mid, top|
var yd = (top - 4 * (a + b)) / 7
if (!isIntegral.call(yd, 0.0001)) return [0, 0, 0]
var y = yd.truncate
var x = mid - 2*a - y
return [x, y, y - x]
}
var sol = pascal.call(11, 4, 40, 151)
if (sol[0] != 0) {
Fmt.print("Solution is: x = $d, y = $d, z = $d", sol[0], sol[1], sol[2])
} else {
System.print("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
| #Prolog | Prolog | :- set_prolog_flag(double_quotes, chars).
:- initialization(main, main).
main( Argv ) :-
opt_spec( Spec ),
opt_parse( Spec, Argv, Opts, _ ),
(
member( help(true), Opts ) -> show_help
;
member( length( Len ), Opts ),
member( number( Num ), Opts ),
print_set_of_passwords( Len, Num )
).
show_help :-
opt_spec( Spec ),
opt_help( Spec, HelpText ),
write( 'Usage: swipl pgen.pl <options>\n\n' ),
write( HelpText ),
nl.
opt_spec([
[opt(help), type(boolean), default(false), shortflags([h]), longflags([help]),
help('Show Help')],
[opt(length), type(integer), default(10), shortflags([l]), longflags([length]),
help('Specify the length of each password.')],
[opt(number), type(integer), default(1), shortflags([n]), longflags([number]),
help('Specify the number of passwords to create.')]
]).
print_set_of_passwords( Length, Number ) :-
forall(
between( 1, Number, _ ),
(
random_pword( Length, P ),
maplist( format('~w'), P ),
nl
)
).
random_pword( Length, Pword ) :-
length( GenPword, Length ),
findall( C, pword_char( _, C), PwordChars ),
repeat,
maplist(populate_pword( PwordChars ), GenPword ),
maplist( pword_char_rule( GenPword ), [lower, upper, digits, special] ),
random_permutation( GenPword, Pword ).
populate_pword( PwordChars, C ) :- random_member( C, PwordChars ).
pword_char_rule( Pword, Type ) :-
pword_char( Type, C ),
member( C, Pword).
pword_char( lower, C ) :- member( C, "abcdefghijklmnopqrstuvwxyz" ).
pword_char( upper, C ) :- member( C, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ).
pword_char( digits, C ) :- member( C, "0123456789" ).
pword_char( special, C ) :- member( C, "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" ). |
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
| #Nim | Nim | import strutils, threadpool
import nimcrypto
const
# List of hexadecimal representation of target hashes.
HexHashes = ["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"]
# List of target hashes.
Hashes = [MDigest[256].fromHex(HexHashes[0]),
MDigest[256].fromHex(HexHashes[1]),
MDigest[256].fromHex(HexHashes[2])]
Letters = 'a'..'z'
proc findHashes(a: char) =
## Build the arrays of five characters starting with the value
## of "a" and check if their hash matches one of the targets.
## Print the string and the hash value if a match is found.
for b in Letters:
for c in Letters:
for d in Letters:
for e in Letters:
let s = [a, b, c, d, e]
let h = sha256.digest(s)
for i, target in Hashes:
if h == target: # Match.
echo s.join(), " → ", HexHashes[i]
# Launch a thread for each starting character.
for a in Letters:
spawn findHashes(a)
sync() |
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
| #Perl | Perl | use Digest::SHA qw/sha256_hex/;
use threads;
use threads::shared;
my @results :shared;
print "$_ : ",join(" ",search($_)), "\n" for (qw/
1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
/);
sub search {
my $hash = shift;
@results = ();
$_->join() for map { threads->create('tsearch', $_, $hash) } 0..25;
return @results;
}
sub tsearch {
my($tnum, $hash) = @_;
my $s = chr(ord("a")+$tnum) . "aaaa";
for (1..456976) { # 26^4
push @results, $s if sha256_hex($s) eq $hash;
$s++;
}
} |
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.
| #Oforth | Oforth | import: parallel
: largeMinFactor dup mapParallel(#factors) zip maxFor(#[ second first ]) ; |
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.
| #ooRexx | ooRexx | /* Concurrency in ooRexx. Example of early reply */
object1 = .example~new
object2 = .example~new
say object1~primes(1,11111111111,11111111114)
say object2~primes(2,11111111111,11111111114)
say "Main ended at" time()
exit
::class example
::method primes
use arg which,bot,top
reply "Start primes"which':' time()
Select
When which=1 Then Call pd1 bot top
When which=2 Then Call pd2 bot top
End |
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.
| #Factor | Factor | IN: scratchpad 3 4 2 * 1 5 - 2 3 ^ ^ / +
--- Data stack:
3+1/8192 |
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.
| #Forth | Forth | : ^ over swap 1 ?do over * loop nip ;
s" 3 4 2 * 1 5 - 2 3 ^ ^ / +" evaluate . |
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
| #ActionScript | ActionScript | function isPalindrome(str:String):Boolean
{
for(var first:uint = 0, second:uint = str.length - 1; first < second; first++, second--)
if(str.charAt(first) != str.charAt(second)) return false;
return true;
} |
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.
| #Haskell | Haskell | import Control.Monad (guard)
palindromic :: Int -> Bool
palindromic n = d == reverse d
where
d = show n
gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
where
firstLastDigit = read [head asDigits, last asDigits]
asDigits = show n
result :: Int -> [Int]
result d = do
x <- [(d+100),(d+110)..]
guard $ palindromic x && gapful x
pure x
showSets :: (Int -> String) -> IO ()
showSets r = go 1
where
go n = if n <= 9 then do
putStrLn (show n ++ ": " ++ r n)
go (succ n)
else pure ()
main :: IO ()
main = do
putStrLn "\nFirst 20 palindromic gapful numbers ending in:"
showSets (show . take 20 . result)
putStrLn "\nLast 15 of first 100 palindromic gapful numbers ending in:"
showSets (show . drop 85 . take 100 . result)
putStrLn "\nLast 10 of first 1000 palindromic gapful numbers ending in:"
showSets (show . drop 990 . take 1000 . result)
putStrLn "\ndone." |
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.
| #Liberty_BASIC | Liberty BASIC |
global stack$,queue$
stack$=""
queue$=""
in$ = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
print "Input:"
print in$
token$ = "#"
print "No", "token", "stack", "queue"
while 1
i=i+1
token$ = word$(in$, i)
if token$ = "" then i=i-1: exit while
print i, token$, reverse$(stack$), queue$
select case
case token$ = "("
call stack.push token$
case token$ = ")"
while stack.peek$() <> "("
'if stack is empty
if stack$="" then print "Error: no matching '(' for token ";i: end
call queue.push stack.pop$()
wend
discard$=stack.pop$() 'discard "("
case isOperator(token$)
op1$=token$
while(isOperator(stack.peek$()))
op2$=stack.peek$()
select case
case op2$<>"^" and precedence(op1$) = precedence(op2$)
'"^" is the only right-associative operator
call queue.push stack.pop$()
case precedence(op1$) < precedence(op2$)
call queue.push stack.pop$()
case else
exit while
end select
wend
call stack.push op1$
case else 'number
'actually, wrong operator could end up here, like say %
'If the token is a number, then add it to the output queue.
call queue.push token$
end select
wend
while stack$<>""
if stack.peek$() = "(" then print "no matching ')'": end
call queue.push stack.pop$()
wend
print "Output:"
while queue$<>""
print queue.pop$();" ";
wend
print
end
'------------------------------------------
function isOperator(op$)
isOperator = instr("+-*/^", op$)<>0 AND len(op$)=1
end function
function precedence(op$)
if isOperator(op$) then
precedence = 1 _
+ (instr("+-*/^", op$)<>0) _
+ (instr("*/^", op$)<>0) _
+ (instr("^", op$)<>0)
end if
end function
'------------------------------------------
sub stack.push s$
stack$=s$+"|"+stack$
end sub
sub queue.push s$
queue$=queue$+s$+"|"
end sub
function queue.pop$()
'it does return empty on empty stack or queue
queue.pop$=word$(queue$,1,"|")
queue$=mid$(queue$,instr(queue$,"|")+1)
end function
function stack.pop$()
'it does return empty on empty stack or queue
stack.pop$=word$(stack$,1,"|")
stack$=mid$(stack$,instr(stack$,"|")+1)
end function
function stack.peek$()
'it does return empty on empty stack or queue
stack.peek$=word$(stack$,1,"|")
end function
function reverse$(s$)
reverse$ = ""
token$="#"
while token$<>""
i=i+1
token$=word$(s$,i,"|")
reverse$ = token$;" ";reverse$
wend
end function
|
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
| #Perl | Perl | use Math::GMPz;
my $nmax = 250;
my $nbranches = 4;
my @rooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax;
my @unrooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax;
my @c = map { Math::GMPz->new(0) } 0 .. $nbranches-1;
sub tree {
my($br, $n, $l, $sum, $cnt) = @_;
for my $b ($br+1 .. $nbranches) {
$sum += $n;
return if $sum > $nmax || ($l*2 >= $sum && $b >= $nbranches);
if ($b == $br+1) {
$c[$br] = $rooted[$n] * $cnt;
} else {
$c[$br] *= $rooted[$n] + $b - $br - 1;
$c[$br] /= $b - $br;
}
$unrooted[$sum] += $c[$br] if $l*2 < $sum;
return if $b >= $nbranches;
$rooted[$sum] += $c[$br];
for my $m (reverse 1 .. $n-1) {
next if $sum+$m > $nmax;
tree($b, $m, $l, $sum, $c[$br]);
}
}
}
sub bicenter {
my $s = shift;
$unrooted[$s] += $rooted[$s/2] * ($rooted[$s/2]+1) / 2 unless $s & 1;
}
for my $n (1 .. $nmax) {
tree(0, $n, $n, 1, Math::GMPz->new(1));
bicenter($n);
print "$n: $unrooted[$n]\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
| #Brat | Brat | pangram? = { sentence |
letters = [:a :b :c :d :e :f :g :h :i :j :k :l :m
:n :o :p :q :r :s :t :u :v :w :x :y :z]
sentence.downcase!
letters.reject! { l |
sentence.include? l
}
letters.empty?
}
p pangram? 'The quick brown fox jumps over the lazy dog.' #Prints true
p pangram? 'Probably not a pangram.' #Prints false |
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
| #C | C | #include <stdio.h>
int is_pangram(const char *s)
{
const char *alpha = ""
"abcdefghjiklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char ch, wasused[26] = {0};
int total = 0;
while ((ch = *s++) != '\0') {
const char *p;
int idx;
if ((p = strchr(alpha, ch)) == NULL)
continue;
idx = (p - alpha) % 26;
total += !wasused[idx];
wasused[idx] = 1;
if (total == 26)
return 1;
}
return 0;
}
int main(void)
{
int i;
const char *tests[] = {
"The quick brown fox jumps over the lazy dog.",
"The qu1ck brown fox jumps over the lazy d0g."
};
for (i = 0; i < 2; i++)
printf("\"%s\" is %sa pangram\n",
tests[i], is_pangram(tests[i])?"":"not ");
return 0;
} |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #J | J | !/~ i. 5
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
!~/~ i. 5
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
(["0/ ! +/)~ i. 5
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 |
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. | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "sql_base.s7i";
const proc: main is func
local
var database: testDb is database.value;
var sqlStatement: statement is sqlStatement.value;
var string: name is "Smith, Steve";
begin
testDb := openDatabase(DB_SQLITE, "test", "test", "test");
execute(testDb, "create table players (name CHAR(32), score INTEGER, active CHAR, jerseyNum INTEGER)");
execute(testDb, "insert into players values ('Jones, Bob',0,0,99)");
execute(testDb, "insert into players values ('Jesten, Jim',0,0,100)");
execute(testDb, "insert into players values ('Jello, Frank',0,0,101)");
statement := prepare(testDb, "update players set name = ?, score = ?, active = ? \
\where jerseyNum = ?");
bind(statement, 1, name);
bind(statement, 2, 42);
bind(statement, 3, TRUE);
bind(statement, 4, 99);
execute(statement);
statement := prepare(testDb, "select * from players");
execute(statement);
while fetch(statement) do
writeln(column(statement, 1, string) <& " " <&
column(statement, 2, integer) <& " " <&
column(statement, 3, boolean) <& " " <&
column(statement, 4, integer));
end while;
execute(testDb, "drop table players");
close(testDb);
end func; |
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. | #SQL | SQL | -- This works in Oracle's SQL*Plus command line utility
VARIABLE P_NAME VARCHAR2(20);
VARIABLE P_SCORE NUMBER;
VARIABLE P_ACTIVE VARCHAR2(5);
VARIABLE P_JERSEYNUM NUMBER;
BEGIN
:P_NAME := 'Smith, Steve';
:P_SCORE := 42;
:P_ACTIVE := 'TRUE';
:P_JERSEYNUM := 99;
END;
/
DROP TABLE players;
CREATE TABLE players
(
NAME VARCHAR2(20),
SCORE NUMBER,
ACTIVE VARCHAR2(5),
JERSEYNUM NUMBER
);
INSERT INTO players VALUES ('No name',0,'FALSE',99);
commit;
SELECT * FROM players;
UPDATE players
SET name = :P_NAME, score = :P_SCORE, active = :P_ACTIVE
WHERE jerseyNum = :P_JERSEYNUM;
commit;
SELECT * FROM players; |
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. | #SQL_PL | SQL PL |
--#SET TERMINATOR @
CREATE TABLE PLAYERS (
NAME VARCHAR(32),
SCORE INT,
ACTIVE SMALLINT,
JERSEYNUM INT
) @
CREATE PROCEDURE UPDATE_PLAYER (
IN PLAYER_NAME VARCHAR(32),
IN PLAYER_SCORE INT,
IN PLAYER_ACTIVE SMALLINT,
IN JERSEY_NUMBER INT
)
BEGIN
UPDATE PLAYERS
SET NAME = PLAYER_NAME, SCORE = PLAYER_SCORE, ACTIVE = PLAYER_ACTIVE
WHERE JERSEYNUM = JERSEY_NUMBER;
END @
INSERT INTO PLAYERS VALUES ('Pele', '1280', 0, 10) @
CALL UPDATE_PLAYER ('Maradona', '600', 1, 10) @
SELECT * FROM PLAYERS @
|
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
| #Common_Lisp | Common Lisp | (defun pascal (n)
(genrow n '(1)))
(defun genrow (n l)
(when (< 0 n)
(print l)
(genrow (1- n) (cons 1 (newrow l)))))
(defun newrow (l)
(if (> 2 (length l))
'(1)
(cons (+ (car l) (cadr l)) (newrow (cdr l))))) |
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.