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
| #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
every writes(s := !arglist) do write( if palindrome(s) then " is " else " is not", " a palindrome.")
end |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #BASIC | BASIC |
dateTest$ = ""
total = 0
PRINT "Siguientes 15 fechas palindr¢micas al 2020-02-02:"
FOR anno = 2021 TO 9999
dateTest$ = LTRIM$(STR$(anno))
FOR mes = 1 TO 12
IF mes < 10 THEN dateTest$ = dateTest$ + "0"
dateTest$ = dateTest$ + LTRIM$(STR$(mes))
FOR dia = 1 TO 31
IF mes = 2 AND dia > 28 THEN EXIT FOR
IF (mes = 4 OR mes = 6 OR mes = 9 OR mes = 11) AND dia > 30 THEN EXIT FOR
IF dia < 10 THEN dateTest$ = dateTest$ + "0"
dateTest$ = dateTest$ + LTRIM$(STR$(dia))
FOR Pal = 1 TO 4
IF MID$(dateTest$, Pal, 1) <> MID$(dateTest$, 9 - Pal, 1) THEN EXIT FOR
NEXT Pal
IF Pal = 5 THEN
total = total + 1
IF total <= 15 THEN PRINT LEFT$(dateTest$, 4); "-"; MID$(dateTest$, 5, 2); "-"; RIGHT$(dateTest$, 2)
END IF
IF total > 15 THEN
EXIT FOR: EXIT FOR: EXIT FOR
END IF
dateTest$ = LEFT$(dateTest$, 6)
NEXT dia
dateTest$ = LEFT$(dateTest$, 4)
NEXT mes
dateTest$ = ""
NEXT anno
END
|
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$ + "DATELIB"
DIM B% 8
TestDate%=FN_today
REPEAT
$B%=FN_date$(TestDate%, "yyyyMMdd")
FOR I%=0 TO 3
IF ?(B% + I%) <> ?(B% + 7 - I%) EXIT FOR
NEXT
IF I%=4 PRINT FN_date$(TestDate%, "yyyy-MM-dd")
TestDate%+=1
UNTIL VPOS=15
END |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #EchoLisp | EchoLisp |
(lib 'list) ;; (combinations L k)
;; add a combination to each partition in ps
(define (pproduct c ps) (for/list ((x ps)) (cons c x)))
;; apply to any type of set S
;; ns is list of cardinals for each partition
;; for all combinations Ci of n objects from S
;; set S <- LS minus Ci , set n <- next n , and recurse
(define (_partitions S ns )
(cond
([empty? (rest ns)] (list (combinations S (first ns))))
(else
(for/fold (parts null)
([c (combinations S (first ns))])
(append
parts
(pproduct c (_partitions (set-substract S c) (rest ns))))))))
;; task : S = ( 0 , 1 ... n-1) args = ns
(define (partitions . args)
(for-each
writeln
(_partitions (range 1 (1+ (apply + args))) args )))
|
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Rust | Rust |
fn padovan(n: u64, x: u64) -> u64 {
if n < 2 {
return 0;
}
match n {
2 if x <= n + 1 => 1,
2 => padovan(n, x - 2) + padovan(n, x - 3),
_ if x <= n + 1 => padovan(n - 1, x),
_ => ((x - n - 1)..(x - 1)).fold(0, |acc, value| acc + padovan(n, value)),
}
}
fn main() {
(2..=8).for_each(|n| {
print!("\nN={}: ", n);
(1..=15).for_each(|x| print!("{},", padovan(n, x)))
});
}
|
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Sidef | Sidef | func padovan(N) {
Enumerator({|callback|
var n = 2
var pn = [1, 1, 1]
loop {
pn << sum(pn[n-N .. (n++-1) -> grep { _ >= 0 }])
callback(pn[-4])
}
})
}
for n in (2..8) {
say "n = #{n} | #{padovan(n).first(25).join(' ')}"
} |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Wren | Wren | import "/fmt" for Fmt
var padovanN // recursive
padovanN = Fn.new { |n, t|
if (n < 2 || t < 3) return [1] * t
var p = padovanN.call(n-1, t)
if (n + 1 >= t) return p
for (i in n+1...t) {
p[i] = 0
for (j in i-2..i-n-1) p[i] = p[i] + p[j]
}
return p
}
var t = 15
System.print("First %(t) terms of the Padovan n-step number sequences:")
for (n in 2..8) Fmt.print("$d: $3d" , n, padovanN.call(n, t)) |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Perl | Perl | sub pascal {
my $rows = shift;
my @next = (1);
for my $n (1 .. $rows) {
print "@next\n";
@next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1);
}
} |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #11l | 11l | V pp = 1.324717957244746025960908854
V ss = 1.0453567932525329623
V Rules = [‘A’ = ‘B’, ‘B’ = ‘C’, ‘C’ = ‘AB’]
F padovan1(n)
V r = [1] * min(n, 3)
V (a, b, c) = (1, 1, 1)
V count = 3
L count < n
(a, b, c) = (b, c, a + b)
r [+]= c
count++
R r
F padovan2(n)
V r = [1] * (n > 1)
V p = 1.0
V count = 1
L count < n
r [+]= Int(round(p / :ss))
p *= :pp
count++
R r
F padovan3(n)
[String] r
V s = ‘A’
V count = 0
L count < n
r [+]= s
V next = ‘’
L(ch) s
next ‘’= Rules[ch]
s = next
count++
R r
print(‘First 20 terms of the Padovan sequence:’)
print(padovan1(20).join(‘ ’))
V list1 = padovan1(64)
V list2 = padovan2(64)
print(‘The first 64 iterative and calculated values ’(I list1 == list2 {‘are the same.’} E ‘differ.’))
print()
print(‘First 10 L-system strings:’)
print(padovan3(10).join(‘ ’))
print()
print(‘Lengths of the 32 first L-system strings:’)
V list3 = padovan3(32).map(x -> x.len)
print(list3.join(‘ ’))
print(‘These lengths are’(I list3 == list1[0.<32] {‘ ’} E ‘ not ’)‘the 32 first terms of the Padovan sequence.’) |
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
| #Ioke | Ioke | Text isPalindrome? = method(self chars == self chars reverse) |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #C | C | #include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
bool is_palindrome(const char* str) {
size_t n = strlen(str);
for (size_t i = 0; i + 1 < n; ++i, --n) {
if (str[i] != str[n - 1])
return false;
}
return true;
}
int main() {
time_t timestamp = time(0);
const int seconds_per_day = 24*60*60;
int count = 15;
char str[32];
printf("Next %d palindrome dates:\n", count);
for (; count > 0; timestamp += seconds_per_day) {
struct tm* ptr = gmtime(×tamp);
strftime(str, sizeof(str), "%Y%m%d", ptr);
if (is_palindrome(str)) {
strftime(str, sizeof(str), "%F", ptr);
printf("%s\n", str);
--count;
}
}
return 0;
} |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Elixir | Elixir | defmodule Ordered do
def partition([]), do: [[]]
def partition(mask) do
sum = Enum.sum(mask)
if sum == 0 do
[Enum.map(mask, fn _ -> [] end)]
else
Enum.to_list(1..sum)
|> permute
|> Enum.reduce([], fn perm,acc ->
{_, part} = Enum.reduce(mask, {perm,[]}, fn num,{pm,a} ->
{p, rest} = Enum.split(pm, num)
{rest, [Enum.sort(p) | a]}
end)
[Enum.reverse(part) | acc]
end)
|> Enum.uniq
end
end
defp permute([]), do: [[]]
defp permute(list), do: for x <- list, y <- permute(list -- [x]), do: [x|y]
end
Enum.each([[],[0,0,0],[1,1,1],[2,0,2]], fn test_case ->
IO.puts "\npartitions #{inspect test_case}:"
Enum.each(Ordered.partition(test_case), fn part ->
IO.inspect part
end)
end) |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Phix | Phix | sequence row = {}
for m = 1 to 13 do
row = row & 1
for n=length(row)-1 to 2 by -1 do
row[n] += row[n-1]
end for
printf(1,repeat(' ',(13-m)*2))
for i=1 to length(row) do
printf(1," %3d",row[i])
end for
puts(1,'\n')
end for
|
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #ALGOL_68 | ALGOL 68 | BEGIN # show members of the Padovan Sequence calculated in various ways #
# returns the first n elements of the Padovan sequence by the #
# recurance relation: P(n)=P(n-2)+P(n-3) #
OP PADOVANI = ( INT n )[]INT:
BEGIN
[ 0 : n - 1 ]INT p; p[ 0 ] := p[ 1 ] := p[ 2 ] := 1;
FOR i FROM 3 TO UPB p DO
p[ i ] := p[ i - 2 ] + p[ i - 3 ]
OD;
p
END; # PADOVANI #
# returns the first n elements of the Padovan sequence by #
# computing by truncation P(n)=floor(p^(n-1) / s + .5) #
# where s = 1.0453567932525329623 #
# and p = the "plastic ratio" #
OP PADOVANC = ( INT n )[]INT:
BEGIN
LONG REAL s = 1.0453567932525329623;
LONG REAL p = 1.324717957244746025960908854;
LONG REAL pf := 1 / p;
[ 0 : n - 1 ]INT result;
FOR i FROM LWB result TO UPB result DO
result[ i ] := SHORTEN ENTIER ( pf / s + 0.5 );
pf *:= p
OD;
result
END; # PADOVANC #
# returns the first n L System strings of the Padovan sequence #
OP PADOVANL = ( INT n )[]STRING:
BEGIN
[ 0 : n - 1 ]STRING l; l[ 0 ] := "A"; l[ 1 ] := "B"; l[ 2 ] := "C";
FOR i FROM 3 TO UPB l DO
l[ i ] := l[ i - 3 ] + l[ i - 2 ]
OD;
l
END; # PADOVANC #
# returns TRUE if a and b have the same values, FALSE otherwise #
OP = = ( []INT a, b )BOOL:
IF LWB a /= LWB b OR UPB a /= UPB b
THEN # rows are not the same size # FALSE
ELSE
BOOL result := TRUE;
FOR i FROM LWB a TO UPB a WHILE result := a[ i ] = b[ i ] DO SKIP OD;
result
FI; # = #
# returns the number of elements in a #
OP LENGTH = ( []INT a )INT: ( UPB a - LWB a ) + 1;
# returns the number of characters in s #
OP LENGTH = ( STRING s )INT: ( UPB s - LWB s ) + 1;
# returns a string representation of n #
OP TOSTRING = ( INT n )STRING: whole( n, 0 );
# generate 64 elements of the sequence and 32 L System values #
[]INT iterative = PADOVANI 64;
[]INT calculated = PADOVANC 64;
[]STRING l system = PADOVANL 32;
[ LWB l system : UPB l system ]INT l length;
FOR i FROM LWB l length TO UPB l length DO l length[ i ] := LENGTH l system[ i ] OD;
# first 20 terms #
print( ( "First 20 terms of the Padovan Sequence", newline ) );
FOR i FROM LWB iterative TO 19 DO
print( ( " ", TOSTRING iterative[ i ] ) )
OD;
print( ( newline ) );
print( ( "The first "
, TOSTRING LENGTH iterative
, " iterative and calculated values "
, IF iterative = calculated THEN "are the same" ELSE "differ" FI
, newline
)
);
# print the first 10 values of the L System strings #
print( ( newline, "First 10 L System strings", newline ) );
FOR i FROM LWB l system TO 9 DO
print( ( " ", l system[ i ] ) )
OD;
print( ( newline ) );
print( ( "The first "
, TOSTRING LENGTH l length
, " iterative values and L System lengths "
, IF l length = iterative[ LWB l length : UPB l length @ LWB l length ] THEN "are the same" ELSE "differ" FI
, newline
)
)
END
|
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
| #J | J | isPalin0=: -: |. |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #C.23 | C# | using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
static void Main()
{
foreach (var date in PalindromicDates(2021).Take(15)) WriteLine(date.ToString("yyyy-MM-dd"));
}
public static IEnumerable<DateTime> PalindromicDates(int startYear) {
for (int y = startYear; ; y++) {
int m = Reverse(y % 100);
int d = Reverse(y / 100);
if (IsValidDate(y, m, d, out var date)) yield return date;
}
int Reverse(int x) => x % 10 * 10 + x / 10;
bool IsValidDate(int y, int m, int d, out DateTime date) => DateTime.TryParse($"{y}-{m}-{d}", out date);
}
} |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #FreeBASIC | FreeBASIC | Function Perm(x() As Integer) As Boolean
Dim As Integer i, j
For i = Ubound(x,1)-1 To 0 Step -1
If x(i) < x(i+1) Then Exit For
Next i
If i < 0 Then Return False
j = Ubound(x,1)
While x(j) <= x(i)
j -= 1
Wend
Swap x(i), x(j)
i += 1
j = Ubound(x,1)
While i < j
Swap x(i), x(j)
i += 1
j -= 1
Wend
Return True
End Function
Function Particiones(list() As Integer) As String
Dim As Integer i, j, n, p ', x()
Dim As String oSS = ""
n = Ubound(list)
Dim As Integer x(n)
For i = 0 To n
If list(i) Then
For j = 1 To list(i)
x(p) = i
p += 1
Next j
End If
Next i
Do
For i = 0 To n
oSS += " ( "
For j = 0 To Ubound(x,1)
If x(j) = i Then oSS += Str(j+1) + " "
Next j
oSS += ")"
Next i
oSS += Chr(13) + Chr(10)
Loop Until Not Perm(x())
Return oSS
End Function
Dim list2(2) As Integer = {1, 1, 1}
Print "Particiones(1, 1, 1):"
Print Particiones(list2())
Dim list3(3) As Integer = {1, 2, 0, 1}
Print !"\nParticiones(1, 2, 0, 1):"
Print Particiones(list3())
Sleep |
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
| #PHP | PHP |
<?php
//Author Ivan Gavryshin @dcc0
function tre($n) {
$ck=1;
$kn=$n+1;
if($kn%2==0) {
$kn=$kn/2;
$i=0;
}
else
{
$kn+=1;
$kn=$kn/2;
$i= 1;
}
for ($k = 1; $k <= $kn-1; $k++) {
$ck = $ck/$k*($n-$k+1);
$arr[] = $ck;
echo "+" . $ck ;
}
if ($kn>1) {
echo $arr[i];
$arr=array_reverse($arr);
for ($i; $i<= $kn-1; $i++) {
echo "+" . $arr[$i] ;
}
}
}
//set amount of strings here
while ($n<=20) {
++$n;
echo tre($n);
echo "<br/>";
}
?>
|
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #AppleScript | AppleScript | --------------------- PADOVAN NUMBERS --------------------
-- padovans :: [Int]
on padovans()
script f
on |λ|(abc)
set {a, b, c} to abc
{a, {b, c, a + b}}
end |λ|
end script
unfoldr(f, {1, 1, 1})
end padovans
-- padovanFloor :: [Int]
on padovanFloor()
script f
property p : 1.324717957245
property s : 1.045356793253
on |λ|(n)
{floor(0.5 + ((p ^ (n - 1)) / s)), 1 + n}
end |λ|
end script
unfoldr(f, 0)
end padovanFloor
-- padovanLSystem :: [String]
on padovanLSystem()
script rule
on |λ|(c)
if "A" = c then
"B"
else if "B" = c then
"C"
else
"AB"
end if
end |λ|
end script
script f
on |λ|(s)
{s, concatMap(rule, characters of s) as string}
end |λ|
end script
unfoldr(f, "A")
end padovanLSystem
--------------------------- TEST -------------------------
on run
unlines({"First 20 padovans:", ¬
showList(take(20, padovans())), ¬
"", ¬
"The recurrence and floor-based functions", ¬
"match over the first 64 terms:\n", ¬
prefixesMatch(padovans(), padovanFloor(), 64), ¬
"", ¬
"First 10 L-System strings:", ¬
showList(take(10, padovanLSystem())), ¬
"", ¬
"The lengths of the first 32 L-System", ¬
"strings match the Padovan sequence:\n", ¬
prefixesMatch(padovans(), fmap(|length|, padovanLSystem()), 32)})
end run
-- prefixesMatch :: [a] -> [a] -> Bool
on prefixesMatch(xs, ys, n)
take(n, xs) = take(n, ys)
end prefixesMatch
------------------------- GENERIC ------------------------
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & (|λ|(item i of xs, i, xs))
end repeat
end tell
return acc
end concatMap
-- floor :: Num -> Int
on floor(x)
if class of x is record then
set nr to properFracRatio(x)
else
set nr to properFraction(x)
end if
set n to item 1 of nr
if 0 > item 2 of nr then
n - 1
else
n
end if
end floor
-- fmap <$> :: (a -> b) -> Gen [a] -> Gen [b]
on fmap(f, gen)
script
property g : mReturn(f)
on |λ|()
set v to gen's |λ|()
if v is missing value then
v
else
g's |λ|(v)
end if
end |λ|
end script
end fmap
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set s to xs as text
set my text item delimiters to dlm
s
end intercalate
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- properFraction :: Real -> (Int, Real)
on properFraction(n)
set i to (n div 1)
{i, n - i}
end properFraction
-- showList :: [a] -> String
on showList(xs)
"[" & intercalate(",", map(my str, xs)) & "]"
end showList
-- str :: a -> String
on str(x)
x as string
end str
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
-- A lazy (generator) list unfolded from a seed value
-- by repeated application of f to a value until no
-- residue remains. Dual to fold/reduce.
-- f returns either nothing (missing value),
-- or just (value, residue).
script
property valueResidue : {v, v}
property g : mReturn(f)
on |λ|()
set valueResidue to g's |λ|(item 2 of (valueResidue))
if missing value ≠ valueResidue then
item 1 of (valueResidue)
else
missing value
end if
end |λ|
end script
end unfoldr
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines |
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
| #Java | Java | public static boolean pali(String testMe){
StringBuilder sb = new StringBuilder(testMe);
return testMe.equals(sb.reverse().toString());
} |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #C.2B.2B | C++ | #include <iostream>
#include <string>
#include <boost/date_time/gregorian/gregorian.hpp>
bool is_palindrome(const std::string& str) {
for (size_t i = 0, j = str.size(); i + 1 < j; ++i, --j) {
if (str[i] != str[j - 1])
return false;
}
return true;
}
int main() {
using boost::gregorian::date;
using boost::gregorian::day_clock;
using boost::gregorian::date_duration;
date today(day_clock::local_day());
date_duration day(1);
int count = 15;
std::cout << "Next " << count << " palindrome dates:\n";
for (; count > 0; today += day) {
if (is_palindrome(to_iso_string(today))) {
std::cout << to_iso_extended_string(today) << '\n';
--count;
}
}
return 0;
} |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #GAP | GAP | FixedPartitions := function(arg)
local aux;
aux := function(i, u)
local r, v, w;
if i = Size(arg) then
return [[u]];
else
r := [ ];
for v in Combinations(u, arg[i]) do
for w in aux(i + 1, Difference(u, v)) do
Add(r, Concatenation([v], w));
od;
od;
return r;
fi;
end;
return aux(1, [1 .. Sum(arg)]);
end;
FixedPartitions(2, 0, 2);
# [ [ [ 1, 2 ], [ ], [ 3, 4 ] ], [ [ 1, 3 ], [ ], [ 2, 4 ] ],
# [ [ 1, 4 ], [ ], [ 2, 3 ] ], [ [ 2, 3 ], [ ], [ 1, 4 ] ],
# [ [ 2, 4 ], [ ], [ 1, 3 ] ], [ [ 3, 4 ], [ ], [ 1, 2 ] ] ]
FixedPartitions(1, 1, 1);
# [ [ [ 1 ], [ 2 ], [ 3 ] ], [ [ 1 ], [ 3 ], [ 2 ] ], [ [ 2 ], [ 1 ], [ 3 ] ],
# [ [ 2 ], [ 3 ], [ 1 ] ], [ [ 3 ], [ 1 ], [ 2 ] ], [ [ 3 ], [ 2 ], [ 1 ] ] ] |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Go | Go | package main
import (
"fmt"
"os"
"strconv"
)
func gen_part(n, res []int, pos int) {
if pos == len(res) {
x := make([][]int, len(n))
for i, c := range res {
x[c] = append(x[c], i+1)
}
fmt.Println(x)
return
}
for i := range n {
if n[i] == 0 {
continue
}
n[i], res[pos] = n[i]-1, i
gen_part(n, res, pos+1)
n[i]++
}
}
func ordered_part(n_parts []int) {
fmt.Println("Ordered", n_parts)
sum := 0
for _, c := range n_parts {
sum += c
}
gen_part(n_parts, make([]int, sum), 0)
}
func main() {
if len(os.Args) < 2 {
ordered_part([]int{2, 0, 2})
return
}
n := make([]int, len(os.Args)-1)
var err error
for i, a := range os.Args[1:] {
n[i], err = strconv.Atoi(a)
if err != nil {
fmt.Println(err)
return
}
if n[i] < 0 {
fmt.Println("negative partition size not meaningful")
return
}
}
ordered_part(n)
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two 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
| #PicoLisp | PicoLisp | (de pascalTriangle (N)
(for I N
(space (* 2 (- N I)))
(let C 1
(for K I
(prin (align 3 C) " ")
(setq C (*/ C (- I K) K)) ) )
(prinl) ) ) |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/* Generate (and memoize) the Padovan sequence using
* the recurrence relationship */
int pRec(int n) {
static int *memo = NULL;
static size_t curSize = 0;
/* grow memoization array when necessary and fill with zeroes */
if (curSize <= (size_t) n) {
size_t lastSize = curSize;
while (curSize <= (size_t) n) curSize += 1024 * sizeof(int);
memo = realloc(memo, curSize * sizeof(int));
memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int));
}
/* if we don't have the value for N yet, calculate it */
if (memo[n] == 0) {
if (n<=2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
}
return memo[n];
}
/* Calculate the Nth value of the Padovan sequence
* using the floor function */
int pFloor(int n) {
long double p = 1.324717957244746025960908854;
long double s = 1.0453567932525329623;
return powl(p, n-1)/s + 0.5;
}
/* Given the previous value for the L-system, generate the
* next value */
void nextLSystem(const char *prev, char *buf) {
while (*prev) {
switch (*prev++) {
case 'A': *buf++ = 'B'; break;
case 'B': *buf++ = 'C'; break;
case 'C': *buf++ = 'A'; *buf++ = 'B'; break;
}
}
*buf = '\0';
}
int main() {
// 8192 is enough up to P_33.
#define BUFSZ 8192
char buf1[BUFSZ], buf2[BUFSZ];
int i;
/* Print P_0..P_19 */
printf("P_0 .. P_19: ");
for (i=0; i<20; i++) printf("%d ", pRec(i));
printf("\n");
/* Check that functions match up to P_63 */
printf("The floor- and recurrence-based functions ");
for (i=0; i<64; i++) {
if (pRec(i) != pFloor(i)) {
printf("do not match at %d: %d != %d.\n",
i, pRec(i), pFloor(i));
break;
}
}
if (i == 64) {
printf("match from P_0 to P_63.\n");
}
/* Show first 10 L-system strings */
printf("\nThe first 10 L-system strings are:\n");
for (strcpy(buf1, "A"), i=0; i<10; i++) {
printf("%s\n", buf1);
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
/* Check lengths of strings against pFloor up to P_31 */
printf("\nThe floor- and L-system-based functions ");
for (strcpy(buf1, "A"), i=0; i<32; i++) {
if ((int)strlen(buf1) != pFloor(i)) {
printf("do not match at %d: %d != %d\n",
i, (int)strlen(buf1), pFloor(i));
break;
}
strcpy(buf2, buf1);
nextLSystem(buf2, buf1);
}
if (i == 32) {
printf("match from P_0 to P_31.\n");
}
return 0;
} |
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
| #JavaScript | JavaScript | function isPalindrome(str) {
return str === str.split("").reverse().join("");
}
console.log(isPalindrome("ingirumimusnocteetconsumimurigni")); |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Clojure | Clojure |
(defn valid-date? [[y m d]]
(and (<= 1 m 12)
(<= 1 d 31)))
(defn date-str [[y m d]]
(format "%4d-%02d-%02d" y m d))
(defn yr->date [y]
(let [[_ m d] (re-find #"(..)(..)" (apply str (reverse (str y))))]
[y (Long. m) (Long. d)]))
(defn palindrome-dates [start-yr n]
(->> (iterate inc start-yr)
(map yr->date)
(filter valid-date?)
(map date-str)
(take n)))
|
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Groovy | Groovy | def partitions = { int... sizes ->
int n = (sizes as List).sum()
def perms = n == 0 ? [[]] : (1..n).permutations()
Set parts = perms.collect { p -> sizes.collect { s -> (0..<s).collect { p.pop() } as Set } }
parts.sort{ a, b ->
if (!a) return 0
def comp = [a,b].transpose().find { aa, bb -> aa != bb }
if (!comp) return 0
def recomp = comp.collect{ it as List }.transpose().find { aa, bb -> aa != bb }
if (!recomp) return 0
return recomp[0] <=> recomp[1]
}
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two 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
| #PL.2FI | PL/I |
declare (t, u)(40) fixed binary;
declare (i, n) fixed binary;
t,u = 0;
get (n);
if n <= 0 then return;
do n = 1 to n;
u(1) = 1;
do i = 1 to n;
u(i+1) = t(i) + t(i+1);
end;
put skip edit ((u(i) do i = 1 to n)) (col(40-2*n), (n+1) f(4));
t = u;
end;
|
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #C.2B.2B | C++ | #include <iostream>
#include <map>
#include <cmath>
// Generate the Padovan sequence using the recurrence
// relationship.
int pRec(int n) {
static std::map<int,int> memo;
auto it = memo.find(n);
if (it != memo.end()) return it->second;
if (n <= 2) memo[n] = 1;
else memo[n] = pRec(n-2) + pRec(n-3);
return memo[n];
}
// Calculate the N'th Padovan sequence using the
// floor function.
int pFloor(int n) {
long const double p = 1.324717957244746025960908854;
long const double s = 1.0453567932525329623;
return std::pow(p, n-1)/s + 0.5;
}
// Return the N'th L-system string
std::string& lSystem(int n) {
static std::map<int,std::string> memo;
auto it = memo.find(n);
if (it != memo.end()) return it->second;
if (n == 0) memo[n] = "A";
else {
memo[n] = "";
for (char ch : memo[n-1]) {
switch(ch) {
case 'A': memo[n].push_back('B'); break;
case 'B': memo[n].push_back('C'); break;
case 'C': memo[n].append("AB"); break;
}
}
}
return memo[n];
}
// Compare two functions up to p_N
using pFn = int(*)(int);
void compare(pFn f1, pFn f2, const char* descr, int stop) {
std::cout << "The " << descr << " functions ";
int i;
for (i=0; i<stop; i++) {
int n1 = f1(i);
int n2 = f2(i);
if (n1 != n2) {
std::cout << "do not match at " << i
<< ": " << n1 << " != " << n2 << ".\n";
break;
}
}
if (i == stop) {
std::cout << "match from P_0 to P_" << stop << ".\n";
}
}
int main() {
/* Print P_0 to P_19 */
std::cout << "P_0 .. P_19: ";
for (int i=0; i<20; i++) std::cout << pRec(i) << " ";
std::cout << "\n";
/* Check that floor and recurrence match up to P_64 */
compare(pFloor, pRec, "floor- and recurrence-based", 64);
/* Show first 10 L-system strings */
std::cout << "\nThe first 10 L-system strings are:\n";
for (int i=0; i<10; i++) std::cout << lSystem(i) << "\n";
std::cout << "\n";
/* Check lengths of strings against pFloor up to P_31 */
compare(pFloor, [](int n){return (int)lSystem(n).length();},
"floor- and L-system-based", 32);
return 0;
} |
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
| #jq | jq | def palindrome: explode as $in | ($in|reverse) == $in; |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #F.23 | F# | // palindrome_dates.fsx
open System
let is_palindrome_date =
let date_string (date: DateTime) = date.ToString "yyyyMMdd"
let is_palindrome s =
let rev_string = Seq.rev >> Seq.map string >> String.concat ""
s = rev_string s
date_string >> is_palindrome
let palindrome_dates =
let rec loop date =
seq {
if is_palindrome_date date
then
yield date
yield! loop (date.AddDays 1.0)
else
yield! loop (date.AddDays 1.0)
}
loop DateTime.Now
let print_date =
let iso_string (date: DateTime) = date.ToString "yyyy-MM-dd"
iso_string >> printfn "%s"
palindrome_dates
|> Seq.take 15
|> Seq.iter print_date
|
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Haskell | Haskell | import Data.List ((\\))
comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb _ [] = []
comb k (x:xs) = map (x:) (comb (k-1) xs) ++ comb k xs
partitions :: [Int] -> [[[Int]]]
partitions xs = p [1..sum xs] xs
where p _ [] = [[]]
p xs (k:ks) = [ cs:rs | cs <- comb k xs, rs <- p (xs \\ cs) ks ]
main = print $ partitions [2,0,2] |
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
| #Potion | Potion | printpascal = (n) :
if (n < 1) :
1 print
(1)
. else :
prev = printpascal(n - 1)
prev append(0)
curr = (1)
n times (i):
curr append(prev(i) + prev(i + 1))
.
"\n" print
curr join(", ") print
curr
.
.
printpascal(read number integer) |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Clojure | Clojure | (def padovan (map first (iterate (fn [[a b c]] [b c (+ a b)]) [1 1 1])))
(def pad-floor
(let [p 1.324717957244746025960908854
s 1.0453567932525329623]
(map (fn [n] (int (Math/floor (+ (/ (Math/pow p (dec n)) s) 0.5)))) (range))))
(def pad-l
(iterate (fn f [[c & s]]
(case c
\A (str "B" (f s))
\B (str "C" (f s))
\C (str "AB" (f s))
(str "")))
"A"))
(defn comp-seq [n seqa seqb]
(= (take n seqa) (take n seqb)))
(defn comp-all [n]
(= (map count (vec (take n pad-l)))
(take n padovan)
(take n pad-floor)))
(defn padovan-print [& args]
((print "The first 20 items with recursion relation are: ")
(println (take 20 padovan))
(println)
(println (str
"The recurrence and floor based algorithms "
(if (comp-seq 64 padovan pad-floor) "match" "not match")
" to n=64"))
(println)
(println "The first 10 L-system strings are:")
(println (take 10 pad-l))
(println)
(println (str
"The L-system, recurrence and floor based algorithms "
(if (comp-all 32) "match" "not match")
" to n=32")))) |
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
| #Jsish | Jsish | /* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
str = str.toLowerCase();
str = str.replace(/[ \t,;:!?.]/g, '');
}
return str === str.match(/./g).reverse().join('');
}
;isPalindrome('BUB');
;isPalindrome('CUB');
;isPalindrome('Bub');
;isPalindrome('Bub', false);
;isPalindrome('In girum imus nocte et consumimur igni', false);
;isPalindrome('A man, a plan, a canal; Panama!', false);
;isPalindrome('Never odd or even', false);
/*
=!EXPECTSTART!=
isPalindrome('BUB') ==> true
isPalindrome('CUB') ==> false
isPalindrome('Bub') ==> false
isPalindrome('Bub', false) ==> true
isPalindrome('In girum imus nocte et consumimur igni', false) ==> true
isPalindrome('A man, a plan, a canal; Panama!', false) ==> true
isPalindrome('Never odd or even', false) ==> true
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Factor | Factor | USING: calendar calendar.format io kernel lists lists.lazy
sequences sets ;
: palindrome-dates ( -- list )
2020 2 2 <date> [ 1 days time+ ] lfrom-by
[ timestamp>ymd ] lmap-lazy
[ "-" without dup reverse = ] lfilter ;
15 palindrome-dates ltake [ print ] leach |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #FreeBASIC | FreeBASIC |
Dim As String dateTest = ""
Dim As Integer Pal =0, total = 0
Print "Siguientes 15 fechas palindr¢micas al 2020-02-02:"
For anno As Integer = 2021 To 9999
dateTest = Ltrim(Str(anno))
For mes As Integer = 1 To 12
If mes < 10 Then dateTest = dateTest + "0"
dateTest += Ltrim(Str(mes))
For dia As Integer = 1 To 31
If mes = 2 And dia > 28 Then Exit For
If (mes = 4 Or mes = 6 Or mes = 9 Or mes = 11) And dia > 30 Then Exit For
If dia < 10 Then dateTest += "0"
dateTest = dateTest + Ltrim(Str(dia))
For Pal = 1 To 4
If Mid(dateTest, Pal, 1) <> Mid(dateTest, 9 - Pal, 1) Then Exit For
Next Pal
If Pal = 5 Then
total += 1
If total <= 15 Then Print Left(dateTest,4);"-";Mid(dateTest,5,2);"-";Right(dateTest,2)
End If
if total > 15 then Exit For : Exit For : Exit For
dateTest = Left(dateTest, 6)
Next dia
dateTest = Left(dateTest, 4)
Next mes
dateTest = ""
Next anno
Sleep
|
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #J | J | require'stats'
partitions=: ([,] {L:0 (i.@#@, -. [)&;)/"1@>@,@{@({@comb&.> +/\.) |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #JavaScript | JavaScript | (function () {
'use strict';
// [n] -> [[[n]]]
function partitions(a1, a2, a3) {
var n = a1 + a2 + a3;
return combos(range(1, n), n, [a1, a2, a3]);
}
function combos(s, n, xxs) {
if (!xxs.length) return [[]];
var x = xxs[0],
xs = xxs.slice(1);
return mb( choose(s, n, x), function (l_rest) {
return mb( combos(l_rest[1], (n - x), xs), function (r) {
// monadic return/injection requires 1 additional
// layer of list nesting:
return [ [l_rest[0]].concat(r) ];
})});
}
function choose(aa, n, m) {
if (!m) return [[[], aa]];
var a = aa[0],
as = aa.slice(1);
return n === m ? (
[[aa, []]]
) : (
choose(as, n - 1, m - 1).map(function (xy) {
return [[a].concat(xy[0]), xy[1]];
}).concat(choose(as, n - 1, m).map(function (xy) {
return [xy[0], [a].concat(xy[1])];
}))
);
}
// GENERIC
// Monadic bind (chain) for lists
function mb(xs, f) {
return [].concat.apply([], xs.map(f));
}
// [m..n]
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
return m + i;
});
}
// EXAMPLE
return partitions(2, 0, 2);
})(); |
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
| #PowerShell | PowerShell |
$Infinity = 1
$NewNumbers = $null
$Numbers = $null
$Result = $null
$Number = $null
$Power = $args[0]
Write-Host $Power
For(
$i=0;
$i -lt $Infinity;
$i++
)
{
$Numbers = New-Object Object[] 1
$Numbers[0] = $Power
For(
$k=0;
$k -lt $NewNumbers.Length;
$k++
)
{
$Numbers = $Numbers + $NewNumbers[$k]
}
If(
$i -eq 0
)
{
$Numbers = $Numbers + $Power
}
$NewNumbers = New-Object Object[] 0
Try
{
For(
$j=0;
$j -lt $Numbers.Length;
$j++
)
{
$Result = $Numbers[$j] + $Numbers[$j+1]
$NewNumbers = $NewNumbers + $Result
}
}
Catch [System.Management.Automation.RuntimeException]
{
Write-Warning "Value was too large for a Decimal. Script aborted."
Break;
}
Foreach(
$Number in $Numbers
)
{
If(
$Number.ToString() -eq "+unendlich"
)
{
Write-Warning "Value was too large for a Decimal. Script aborted."
Exit
}
}
Write-Host $Numbers
$Infinity++
}
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | V words = File(‘unixdict.txt’).read().split("\n")
V ordered = words.filter(word -> word == sorted(word).join(‘’))
V maxlen = max(ordered, key' w -> w.len).len
V maxorderedwords = ordered.filter(word -> word.len == :maxlen)
print(maxorderedwords.join(‘ ’)) |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Delphi | Delphi |
program Padovan_sequence;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Velthuis.BigDecimals,
Boost.Generics.Collection;
type
TpFn = TFunc<Integer, Integer>;
var
RecMemo: TDictionary<Integer, Integer>;
lSystemMemo: TDictionary<Integer, string>;
function pRec(n: Integer): Integer;
begin
if RecMemo.HasKey(n) then
exit(RecMemo[n]);
if (n <= 2) then
RecMemo[n] := 1
else
RecMemo[n] := pRec(n - 2) + pRec(n - 3);
Result := RecMemo[n];
end;
function pFloor(n: Integer): Integer;
var
p, s, a: BigDecimal;
begin
p := '1.324717957244746025960908854';
s := '1.0453567932525329623';
a := p.IntPower(n - 1, 64);
Result := Round(BigDecimal.Divide(a, s));
end;
function lSystem(n: Integer): string;
begin
if n = 0 then
lSystemMemo[n] := 'A'
else
begin
lSystemMemo[n] := '';
for var ch in lSystemMemo[n - 1] do
begin
case ch of
'A':
lSystemMemo[n] := lSystemMemo[n] + 'B';
'B':
lSystemMemo[n] := lSystemMemo[n] + 'C';
'C':
lSystemMemo[n] := lSystemMemo[n] + 'AB';
end;
end;
end;
Result := lSystemMemo[n];
end;
procedure Compare(f1, f2: TpFn; descr: string; stop: Integer);
begin
write('The ', descr, ' functions ');
var i := 0;
while i < stop do
begin
var n1 := f1(i);
var n2 := f2(i);
if n1 <> n2 then
begin
write('do not match at ', i);
writeln(': ', n1, ' != ', n2, '.');
break;
end;
inc(i);
end;
if i = stop then
writeln('match from P_0 to P_', stop, '.');
end;
begin
RecMemo := TDictionary<Integer, Integer>.Create([], []);
lSystemMemo := TDictionary<Integer, string>.Create([], []);
write('P_0 .. P_19: ');
for var i := 0 to 19 do
write(pRec(i), ' ');
writeln;
Compare(pFloor, pRec, 'floor- and recurrence-based', 64);
writeln(#10'The first 10 L-system strings are:');
for var i := 0 to 9 do
writeln(lSystem(i));
writeln;
Compare(pFloor,
function(n: Integer): Integer
begin
Result := length(lSystem(n));
end, 'floor- and L-system-based', 32);
readln;
end. |
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
| #Julia | Julia | palindrome(s) = s == reverse(s) |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Go | Go | package main
import (
"fmt"
"time"
)
func reverse(s string) string {
chars := []rune(s)
for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
chars[i], chars[j] = chars[j], chars[i]
}
return string(chars)
}
func main() {
const (
layout = "20060102"
layout2 = "2006-01-02"
)
fmt.Println("The next 15 palindromic dates in yyyymmdd format after 20200202 are:")
date := time.Date(2020, 2, 2, 0, 0, 0, 0, time.UTC)
count := 0
for count < 15 {
date = date.AddDate(0, 0, 1)
s := date.Format(layout)
r := reverse(s)
if r == s {
fmt.Println(date.Format(layout2))
count++
}
}
} |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #jq | jq | # Generate a stream of the distinct combinations of r items taken from the input array.
def combination(r):
if r > length or r < 0 then empty
elif r == length then .
else ( [.[0]] + (.[1:]|combination(r-1))),
( .[1:]|combination(r))
end;
# Input: a mask, that is, an array of lengths.
# Output: a stream of the distinct partitions defined by the mask.
def partition:
# partition an array of entities, s, according to a mask presented as input:
def p(s):
if length == 0 then []
else . as $mask
| (s | combination($mask[0])) as $c
| [$c] + ($mask[1:] | p(s - $c))
end;
. as $mask | p( [range(1; 1 + ($mask|add))] ); |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Julia | Julia |
using Combinatorics
function masked(mask, lis)
combos = []
idx = 1
for step in mask
if(step < 1)
push!(combos, Array{Int,1}[])
else
push!(combos, sort(lis[idx:idx+step-1]))
idx += step
end
end
Array{Array{Int, 1}, 1}(combos)
end
function orderedpartitions(mask)
tostring(masklis) = replace("$masklis", r"Array{Int\d?\d?,1}|Int\d?\d?", "")
join([tostring(lis) for lis in unique([masked(mask, p)
for p in permutations(1:sum(mask))])], "\n")
end
println(orderedpartitions([2, 0, 2]))
println(orderedpartitions([1, 1, 1]))
|
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two 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
| #Prolog | Prolog | pascal(N) :-
pascal(1, N, [1], [[1]|X]-X, L),
maplist(my_format, L).
pascal(Max, Max, L, LC, LF) :-
!,
make_new_line(L, NL),
append_dl(LC, [NL|X]-X, LF-[]).
pascal(N, Max, L, NC, LF) :-
build_new_line(L, NL),
append_dl(NC, [NL|X]-X, NC1),
N1 is N+1,
pascal(N1, Max, NL, NC1, LF).
build_new_line(L, R) :-
build(L, 0, X-X, R).
build([], V, RC, RF) :-
append_dl(RC, [V|Y]-Y, RF-[]).
build([H|T], V, RC, R) :-
V1 is V+H,
append_dl(RC, [V1|Y]-Y, RC1),
build(T, H, RC1, R).
append_dl(X1-X2, X2-X3, X1-X3).
% to have a correct output !
my_format([H|T]) :-
write(H),
maplist(my_writef, T),
nl.
my_writef(X) :-
writef(' %5r', [X]).
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
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! | CHAR ARRAY line(256)
BYTE FUNC IsOrderedWord(CHAR ARRAY word)
BYTE len,i
len=word(0)
IF len<=1 THEN RETURN (1) FI
FOR i=1 TO len-1
DO
IF word(i)>word(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
BYTE FUNC FindLongestOrdered(CHAR ARRAY fname)
BYTE max,dev=[1]
max=0
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
IF line(0)>max AND IsOrderedWord(line)=1 THEN
max=line(0)
FI
OD
Close(dev)
RETURN (max)
PROC FindWords(CHAR ARRAY fname BYTE n)
BYTE count,dev=[1]
Close(dev)
Open(dev,fname,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
IF line(0)=n AND IsOrderedWord(line)=1 THEN
Print(line) Put(32)
FI
OD
Close(dev)
RETURN
PROC Main()
CHAR ARRAY fname="H6:UNIXDICT.TXT"
BYTE max
PrintE("Finding the longest words...")
PutE()
max=FindLongestOrdered(fname)
FindWords(fname,max)
RETURN |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Factor | Factor | USING: L-system accessors io kernel make math math.functions
memoize prettyprint qw sequences ;
CONSTANT: p 1.324717957244746025960908854
CONSTANT: s 1.0453567932525329623
: pfloor ( m -- n ) 1 - p swap ^ s /f .5 + >integer ;
MEMO: precur ( m -- n )
dup 3 < [ drop 1 ]
[ [ 2 - precur ] [ 3 - precur ] bi + ] if ;
: plsys, ( L-system -- )
[ iterate-L-system-string ] [ string>> , ] bi ;
: plsys ( n -- seq )
<L-system>
"A" >>axiom
{ qw{ A B } qw{ B C } qw{ C AB } } >>rules
swap 1 - '[ "A" , _ [ dup plsys, ] times ] { } make nip ;
"First 20 terms of the Padovan sequence:" print
20 [ pfloor pprint bl ] each-integer nl nl
64 [ [ pfloor ] [ precur ] bi assert= ] each-integer
"Recurrence and floor based algorithms match to n=63." print nl
"First 10 L-system strings:" print
10 plsys . nl
32 <iota> [ pfloor ] map 32 plsys [ length ] map assert=
"The L-system, recurrence and floor based algorithms match to n=31." print |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Go | Go | package main
import (
"fmt"
"math"
"math/big"
"strings"
)
func padovanRecur(n int) []int {
p := make([]int, n)
p[0], p[1], p[2] = 1, 1, 1
for i := 3; i < n; i++ {
p[i] = p[i-2] + p[i-3]
}
return p
}
func padovanFloor(n int) []int {
var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat)
p, _ = p.SetString("1.324717957244746025960908854")
s, _ = s.SetString("1.0453567932525329623")
f := make([]int, n)
pow := new(big.Rat).SetInt64(1)
u = u.SetFrac64(1, 2)
t.Quo(pow, p)
t.Quo(t, s)
t.Add(t, u)
v, _ := t.Float64()
f[0] = int(math.Floor(v))
for i := 1; i < n; i++ {
t.Quo(pow, s)
t.Add(t, u)
v, _ = t.Float64()
f[i] = int(math.Floor(v))
pow.Mul(pow, p)
}
return f
}
type LSystem struct {
rules map[string]string
init, current string
}
func step(lsys *LSystem) string {
var sb strings.Builder
if lsys.current == "" {
lsys.current = lsys.init
} else {
for _, c := range lsys.current {
sb.WriteString(lsys.rules[string(c)])
}
lsys.current = sb.String()
}
return lsys.current
}
func padovanLSys(n int) []string {
rules := map[string]string{"A": "B", "B": "C", "C": "AB"}
lsys := &LSystem{rules, "A", ""}
p := make([]string, n)
for i := 0; i < n; i++ {
p[i] = step(lsys)
}
return p
}
// assumes lists are same length
func areSame(l1, l2 []int) bool {
for i := 0; i < len(l1); i++ {
if l1[i] != l2[i] {
return false
}
}
return true
}
func main() {
fmt.Println("First 20 members of the Padovan sequence:")
fmt.Println(padovanRecur(20))
recur := padovanRecur(64)
floor := padovanFloor(64)
same := areSame(recur, floor)
s := "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.")
p := padovanLSys(32)
lsyst := make([]int, 32)
for i := 0; i < 32; i++ {
lsyst[i] = len(p[i])
}
fmt.Println("\nFirst 10 members of the Padovan L-System:")
fmt.Println(p[:10])
fmt.Println("\nand their lengths:")
fmt.Println(lsyst[:10])
same = areSame(recur[:32], lsyst)
s = "give"
if !same {
s = "do not give"
}
fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
|
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
| #k | k | is_palindrome:{x~|x} |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Haskell | Haskell | import Data.Time.Calendar (Day, fromGregorianValid)
import Data.List.Split (chunksOf)
import Data.List (unfoldr)
import Data.Tuple (swap)
import Data.Bool (bool)
import Data.Maybe (mapMaybe)
palinDates :: [Day]
palinDates = mapMaybe palinDay [2021 .. 9999]
palinDay :: Integer -> Maybe Day
palinDay y = fromGregorianValid y m d
where
[m, d] = unDigits <$> chunksOf 2 (reversedDecimalDigits (fromInteger y))
reversedDecimalDigits :: Int -> [Int]
reversedDecimalDigits =
unfoldr ((flip bool Nothing . Just . swap . flip quotRem 10) <*> (0 ==))
unDigits :: [Int] -> Int
unDigits = foldl ((+) . (10 *)) 0
main :: IO ()
main = do
let n = length palinDates
putStrLn $ "Count of palindromic dates [2021..9999]: " ++ show n
putStrLn "\nFirst 15:"
mapM_ print $ take 15 palinDates
putStrLn "\nLast 15:"
mapM_ print $ take 15 (drop (n - 15) palinDates) |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Kotlin | Kotlin | // version 1.1.3
fun nextPerm(perm: IntArray): Boolean {
val size = perm.size
var k = -1
for (i in size - 2 downTo 0) {
if (perm[i] < perm[i + 1]) {
k = i
break
}
}
if (k == -1) return false // last permutation
for (l in size - 1 downTo k) {
if (perm[k] < perm[l]) {
val temp = perm[k]
perm[k] = perm[l]
perm[l] = temp
var m = k + 1
var n = size - 1
while (m < n) {
val temp2 = perm[m]
perm[m++] = perm[n]
perm[n--] = temp2
}
break
}
}
return true
}
fun List<Int>.isMonotonic(): Boolean {
for (i in 1 until this.size) {
if (this[i] < this[i - 1]) return false
}
return true
}
fun main(args: Array<String>) {
val sizes = args.map { it.toInt() }
println("Partitions for $sizes:\n[")
val totalSize = sizes.sum()
val perm = IntArray(totalSize) { it + 1 }
do {
val partition = mutableListOf<List<Int>>()
var sum = 0
var isValid = true
for (size in sizes) {
if (size == 0) {
partition.add(emptyList<Int>())
}
else if (size == 1) {
partition.add(listOf(perm[sum]))
}
else {
val sl = perm.slice(sum until sum + size)
if (!sl.isMonotonic()) {
isValid = false
break
}
partition.add(sl)
}
sum += size
}
if (isValid) println(" $partition")
}
while (nextPerm(perm))
println("]")
} |
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
| #PureBasic | PureBasic | Procedure pascaltriangle( n.i)
For i= 0 To n
c = 1
For k=0 To i
Print(Str( c)+" ")
c = c * (i-k)/(k+1);
Next ;k
PrintN(" "); nächste zeile
Next ;i
EndProcedure
OpenConsole()
Parameter.i = Val(ProgramParameter(0))
pascaltriangle(Parameter);
Input() |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
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
| #Ada | Ada |
with Ada.Text_IO, Ada.Containers.Indefinite_Vectors;
use Ada.Text_IO;
procedure Ordered_Words is
package Word_Vectors is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive, Element_Type => String);
use Word_Vectors;
File : File_Type;
Ordered_Words : Vector;
Max_Length : Positive := 1;
begin
Open (File, In_File, "unixdict.txt");
while not End_Of_File (File) loop
declare
Word : String := Get_Line (File);
begin
if (for all i in Word'First..Word'Last-1 => Word (i) <= Word(i+1)) then
if Word'Length > Max_Length then
Max_Length := Word'Length;
Ordered_Words.Clear;
Ordered_Words.Append (Word);
elsif Word'Length = Max_Length then
Ordered_Words.Append (Word);
end if;
end if;
end;
end loop;
for Word of Ordered_Words loop
Put_Line (Word);
end loop;
Close (File);
end Ordered_Words;
|
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Haskell | Haskell | -- list of Padovan numbers using recurrence
pRec = map (\(a,_,_) -> a) $ iterate (\(a,b,c) -> (b,c,a+b)) (1,1,1)
-- list of Padovan numbers using self-referential lazy lists
pSelfRef = 1 : 1 : 1 : zipWith (+) pSelfRef (tail pSelfRef)
-- list of Padovan numbers generated from floor function
pFloor = map f [0..]
where f n = floor $ p**fromInteger (pred n) / s + 0.5
p = 1.324717957244746025960908854
s = 1.0453567932525329623
-- list of L-system strings
lSystem = iterate f "A"
where f [] = []
f ('A':s) = 'B':f s
f ('B':s) = 'C':f s
f ('C':s) = 'A':'B':f s
-- check if first N elements match
checkN n as bs = take n as == take n bs
main = do
putStr "P_0 .. P_19: "
putStrLn $ unwords $ map show $ take 20 pRec
putStr "The floor- and recurrence-based functions "
putStr $ if checkN 64 pRec pFloor then "match" else "do not match"
putStr " from P_0 to P_63.\n"
putStr "The self-referential- and recurrence-based functions "
putStr $ if checkN 64 pRec pSelfRef then "match" else "do not match"
putStr " from P_0 to P_63.\n\n"
putStr "The first 10 L-system strings are:\n"
putStrLn $ unwords $ take 10 lSystem
putStr "\nThe floor- and L-system-based functions "
putStr $ if checkN 32 pFloor (map length lSystem)
then "match" else "do not match"
putStr " from P_0 to P_31.\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
| #Kotlin | Kotlin | // version 1.1.2
/* These functions deal automatically with Unicode as all strings are UTF-16 encoded in Kotlin */
fun isExactPalindrome(s: String) = (s == s.reversed())
fun isInexactPalindrome(s: String): Boolean {
var t = ""
for (c in s) if (c.isLetterOrDigit()) t += c
t = t.toLowerCase()
return t == t.reversed()
}
fun main(args: Array<String>) {
val candidates = arrayOf("rotor", "rosetta", "step on no pets", "été")
for (candidate in candidates) {
println("'$candidate' is ${if (isExactPalindrome(candidate)) "an" else "not an"} exact palindrome")
}
println()
val candidates2 = arrayOf(
"In girum imus nocte et consumimur igni",
"Rise to vote, sir",
"A man, a plan, a canal - Panama!",
"Ce repère, Perec" // note: 'è' considered a distinct character from 'e'
)
for (candidate in candidates2) {
println("'$candidate' is ${if (isInexactPalindrome(candidate)) "an" else "not an"} inexact palindrome")
}
} |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Java | Java |
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class PalindromeDates {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2020, 2, 3);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
DateTimeFormatter formatterDash = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.printf("First 15 palindrome dates after 2020-02-02 are:%n");
for ( int count = 0 ; count < 15 ; date = date.plusDays(1) ) {
String dateFormatted = date.format(formatter);
if ( dateFormatted.compareTo(new StringBuilder(dateFormatted).reverse().toString()) == 0 ) {
count++;
System.out.printf("date = %s%n", date.format(formatterDash));
}
}
}
}
|
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Lua | Lua | --- Create a list {1,...,n}.
local function range(n)
local res = {}
for i=1,n do
res[i] = i
end
return res
end
--- Return true if the element x is in t.
local function isin(t, x)
for _,x_t in ipairs(t) do
if x_t == x then return true end
end
return false
end
--- Return the sublist from index u to o (inclusive) from t.
local function slice(t, u, o)
local res = {}
for i=u,o do
res[#res+1] = t[i]
end
return res
end
--- Compute the sum of the elements in t.
-- Assume that t is a list of numbers.
local function sum(t)
local s = 0
for _,x in ipairs(t) do
s = s + x
end
return s
end
--- Generate all combinations of t of length k (optional, default is #t).
local function combinations(m, r)
local function combgen(m, n)
if n == 0 then coroutine.yield({}) end
for i=1,#m do
if n == 1 then coroutine.yield({m[i]})
else
for m0 in coroutine.wrap(function() combgen(slice(m, i+1, #m), n-1) end) do
coroutine.yield({m[i], unpack(m0)})
end
end
end
end
return coroutine.wrap(function() combgen(m, r) end)
end
--- Generate a list of partitions into fized-size blocks.
local function partitions(...)
local function helper(s, ...)
local args = {...}
if #args == 0 then return {% templatetag openvariable %}{% templatetag closevariable %} end
local res = {}
for c in combinations(s, args[1]) do
local s0 = {}
for _,x in ipairs(s) do if not isin(c, x) then s0[#s0+1] = x end end
for _,r in ipairs(helper(s0, unpack(slice(args, 2, #args)))) do
res[#res+1] = {{unpack(c)}, unpack(r)}
end
end
return res
end
return helper(range(sum({...})), ...)
end
-- Print the solution
io.write "["
local parts = partitions(2,0,2)
for i,tuple in ipairs(parts) do
io.write "("
for j,set in ipairs(tuple) do
io.write "{"
for k,element in ipairs(set) do
io.write(element)
if k ~= #set then io.write(", ") end
end
io.write "}"
if j ~= #tuple then io.write(", ") end
end
io.write ")"
if i ~= #parts then io.write(", ") end
end
io.write "]"
io.write "\n" |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two 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
| #Python | Python | def pascal(n):
"""Prints out n rows of Pascal's triangle.
It returns False for failure and True for success."""
row = [1]
k = [0]
for x in range(max(n,0)):
print row
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
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
| #Aime | Aime | integer
ordered(data s)
{
integer a, c, p;
a = 1;
p = -1;
for (, c in s) {
if (c < p) {
a = 0;
break;
} else {
p = c;
}
}
a;
}
integer
main(void)
{
file f;
text s;
index x;
f.affix("unixdict.txt");
while (f.line(s) != -1) {
if (ordered(s)) {
x.v_list(~s).append(s);
}
}
l_ucall(x.back, o_, 0, "\n");
return 0;
} |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #J | J |
padovanSeq=: (],+/@(_2 _3{]))^:([-3:)&1 1 1
realRoot=. {:@(#~ ]=|)@;@p.
padovanNth=: 0.5 <.@+ (realRoot _23 23 _2 1) %~ (realRoot _1 _1 0 1)^<:
padovanL=: rplc&('A';'B'; 'B';'C'; 'C';'AB')@]^:[&'A'
seqLen=. #@(-.&' ')"1
|
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #JavaScript | JavaScript | (() => {
"use strict";
// ----------------- PADOVAN NUMBERS -----------------
// padovans :: [Int]
const padovans = () => {
// Non-finite series of Padovan numbers,
// defined in terms of recurrence relations.
const f = ([a, b, c]) => [
a,
[b, c, a + b]
];
return unfoldr(f)([1, 1, 1]);
};
// padovanFloor :: [Int]
const padovanFloor = () => {
// The Padovan series, defined in terms
// of a floor function.
const
// NB JavaScript loses some of this
// precision at run-time.
p = 1.324717957244746025960908854,
s = 1.0453567932525329623;
const f = n => [
Math.floor(((p ** (n - 1)) / s) + 0.5),
1 + n
];
return unfoldr(f)(0);
};
// padovanLSystem : [Int]
const padovanLSystem = () => {
// An L-system generating terms whose lengths
// are the values of the Padovan integer series.
const rule = c =>
"A" === c ? (
"B"
) : "B" === c ? (
"C"
) : "AB";
const f = s => [
s,
chars(s).flatMap(rule)
.join("")
];
return unfoldr(f)("A");
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => {
// prefixesMatch :: [a] -> [a] -> Bool
const prefixesMatch = xs =>
ys => n => and(
zipWith(a => b => a === b)(
take(n)(xs)
)(
take(n)(ys)
)
);
return [
"First 20 padovans:",
take(20)(padovans()),
"\nThe recurrence and floor-based functions",
"match over the first 64 terms:\n",
prefixesMatch(
padovans()
)(
padovanFloor()
)(64),
"\nFirst 10 L-System strings:",
take(10)(padovanLSystem()),
"\nThe lengths of the first 32 L-System",
"strings match the Padovan sequence:\n",
prefixesMatch(
padovans()
)(
fmap(length)(padovanLSystem())
)(32)
]
.map(str)
.join("\n");
};
// --------------------- GENERIC ---------------------
// and :: [Bool] -> Bool
const and = xs =>
// True unless any value in xs is false.
[...xs].every(Boolean);
// chars :: String -> [Char]
const chars = s =>
s.split("");
// fmap <$> :: (a -> b) -> Gen [a] -> Gen [b]
const fmap = f =>
function* (gen) {
let v = take(1)(gen);
while (0 < v.length) {
yield f(v[0]);
v = take(1)(gen);
}
};
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
"GeneratorFunction" !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat(...Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// str :: a -> String
const str = x =>
"string" !== typeof x ? (
JSON.stringify(x)
) : x;
// unfoldr :: (b -> Maybe (a, b)) -> b -> Gen [a]
const unfoldr = f =>
// A lazy (generator) list unfolded from a seed value
// by repeated application of f to a value until no
// residue remains. Dual to fold/reduce.
// f returns either Null or just (value, residue).
// For a strict output list,
// wrap with `list` or Array.from
x => (
function* () {
let valueResidue = f(x);
while (null !== valueResidue) {
yield valueResidue[0];
valueResidue = f(valueResidue[1]);
}
}()
);
// zipWithList :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple constructor.
xs => ys => ((xs_, ys_) => {
const lng = Math.min(length(xs_), length(ys_));
return take(lng)(xs_).map(
(x, i) => f(x)(ys_[i])
);
})([...xs], [...ys]);
// MAIN ---
return main();
})(); |
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
| #LabVIEW | LabVIEW | val .ispal = f len(.s) > 0 and .s == s2s .s, len(.s)..1
val .tests = h{
"": false,
"z": true,
"aha": true,
"αηα": true,
"αννα": true,
"αννασ": false,
"sees": true,
"seas": false,
"deified": true,
"solo": false,
"solos": true,
"amanaplanacanalpanama": true,
"a man a plan a canal panama": false, # true if we remove spaces
"ingirumimusnocteetconsumimurigni": true,
}
for .word in sort(keys .tests) {
val .foundpal = .ispal(.word)
writeln .word, ": ", .foundpal, if(.foundpal == .tests[.word]: ""; " (FAILED TEST)")
} |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #JavaScript | JavaScript | /**
* Adds zeros for 1 digit days/months
* @param date: string
*/
const addMissingZeros = date => (/^\d$/.test(date) ? `0${date}` : date);
/**
* Formats a Date to a string. If readable is false,
* string is only numbers (used for comparison), else
* is a human readable date.
* @param date: Date
* @param readable: boolean
*/
const formatter = (date, readable) => {
const year = date.getFullYear();
const month = addMissingZeros(date.getMonth() + 1);
const day = addMissingZeros(date.getDate());
return readable ? `${year}-${month}-${day}` : `${year}${month}${day}`;
};
/**
* Returns n (palindromesToShow) palindrome dates
* since start (or 2020-02-02)
* @param start: Date
* @param palindromesToShow: number
*/
function getPalindromeDates(start, palindromesToShow = 15) {
let date = start || new Date(2020, 3, 2);
for (
let i = 0;
i < palindromesToShow;
date = new Date(date.setDate(date.getDate() + 1))
) {
const formattedDate = formatter(date);
if (formattedDate === formattedDate.split("").reverse().join("")) {
i++;
console.log(formatter(date, true));
}
}
}
getPalindromeDates(); |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | w[partitions_]:=Module[{s={},t=Total@partitions,list=partitions,k}, n=Length[list];
While[n>0,s=Join[s,{Take[t,(k=First[list])]}];t=Drop[t,k];list=Rest[list];n--]; s]
m[p_]:=(Sort/@#)&/@(w[#,p]&/@Permutations[Range@Total[p]])//Union |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Nim | Nim | import algorithm, math, sequtils, strutils
type Partition = seq[seq[int]]
func isIncreasing(s: seq[int]): bool =
## Return true if the sequence is sorted in increasing order.
var prev = 0
for val in s:
if prev >= val: return false
prev = val
result = true
iterator partitions(lengths: varargs[int]): Partition =
## Yield the partitions for lengths "lengths".
# Build the list of slices to use for partitionning.
var slices: seq[Slice[int]]
var delta = -1
var idx = 0
for length in lengths:
assert length >= 0, "lengths must not be negative."
inc delta, length
slices.add idx..delta
inc idx, length
# Build the partitions.
let n = sum(lengths)
var perm = toSeq(1..n)
while true:
block buildPartition:
var part: Partition
for slice in slices:
let s = perm[slice]
if not s.isIncreasing():
break buildPartition
part.add s
yield part
if not perm.nextPermutation():
break
func toString(part: Partition): string =
## Return the string representation of a partition.
result = "("
for s in part:
result.addSep(", ", 1)
result.add '{' & s.join(", ") & '}'
result.add ')'
when isMainModule:
import os
proc displayPermutations(lengths: varargs[int]) =
## Display the permutations.
echo "Ordered permutations for (", lengths.join(", "), "):"
for part in partitions(lengths):
echo part.toString
if paramCount() > 0:
var args: seq[int]
for param in commandLineParams():
try:
let val = param.parseInt()
if val < 0: raise newException(ValueError, "")
args.add val
except ValueError:
quit "Wrong parameter: " & param
displayPermutations(args)
else:
displayPermutations(2, 0, 2) |
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
| #q | q |
pascal:{(x-1){0+':x,0}\1}
pascal 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
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
| #ALGOL_68 | ALGOL 68 | PROC ordered = (STRING s)BOOL:
BEGIN
FOR i TO UPB s - 1 DO IF s[i] > s[i+1] THEN return false FI OD;
TRUE EXIT
return false: FALSE
END;
IF FILE input file;
STRING file name = "unixdict.txt";
open(input file, file name, stand in channel) /= 0
THEN
print(("Unable to open file """ + file name + """", newline))
ELSE
BOOL at eof := FALSE;
on logical file end (input file, (REF FILE f)BOOL: at eof := TRUE);
FLEX [1:0] STRING words;
INT idx := 1;
INT max length := 0;
WHILE NOT at eof
DO
STRING word;
get(input file, (word, newline));
IF UPB word >= max length
THEN IF ordered(word)
THEN
max length := UPB word;
IF idx > UPB words
THEN
[1 : UPB words + 20] STRING tmp;
tmp[1 : UPB words] := words;
words := tmp
FI;
words[idx] := word;
idx +:= 1
FI
FI
OD;
print(("Maximum length of ordered words: ", whole(max length, -4), newline));
FOR i TO idx-1
DO
IF UPB words[i] = max length THEN print((words[i], newline)) FI
OD
FI |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #jq | jq | # Output: first $n Padovans
def padovanRecur($n):
[range(0;$n) | 1] as $p
| if $n < 3 then $p
else reduce range(3;$n) as $i ($p; .[$i] = .[$i-2] + .[$i-3])
end;
# Output: first $n Padovans
def padovanFloor($n):
{ p: 1.324717957244746025960908854,
s: 1.0453567932525329623,
pow: 1 }
| reduce range (1;$n) as $i ( .f = [ ((.pow/.p/.s) + 0.5)|floor];
.f[$i] = (((.pow/.s) + 0.5)|floor)
| .pow *= .p)
| .f ;
# Output: a stream of the L-System Padovan strings
def padovanStrings:
{A: "B", B: "C", C: "AB", "": "A"} as $rules
| $rules[""]
| while(true;
ascii_downcase
| gsub("a"; $rules["A"]) | gsub("b"; $rules["B"]) | gsub("c"; $rules["C"]) ) ;
# Output: a stream of the Padovan numbers using the L-System strings
def padovanNumbers:
padovanStrings | length;
def task:
def s1($n):
if padovanFloor($n) == padovanRecur($n) then "give" else "do not give" end;
def s2($n):
if [limit($n; padovanNumbers)] == padovanRecur($n) then "give" else "do not give" end;
"The first 20 members of the Padovan sequence:", padovanRecur(20),
"",
"The recurrence and floor-based functions \(s1(64)) the same results for 64 terms.",
"",
([limit(10; padovanStrings)]
| "First 10 members of the Padovan L-System:", .,
"and their lengths:",
map(length)),
"",
"The recurrence and L-system based functions \(s2(32)) the same results for 32 terms."
;
task |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Julia | Julia | """ Recursive Padovan """
rPadovan(n) = (n < 4) ? one(n) : rPadovan(n - 3) + rPadovan(n - 2)
""" Floor function calculation Padovan """
function fPadovan(n)::Int
p, s = big"1.324717957244746025960908854", big"1.0453567932525329623"
return Int(floor(p^(n-2) / s + .5))
end
""" LSystem Padovan """
function list_LsysPadovan(N)
rules = Dict("A" => "B", "B" => "C", "C" => "AB")
seq, lens = ["A"], [1]
for i in 1:N
str = prod([rules[string(c)] for c in seq[end]])
push!(seq, str)
push!(lens, length(str))
end
return seq, lens
end
const lr, lf = [rPadovan(i) for i in 1:64], [fPadovan(i) for i in 1:64]
const sL, lL = list_LsysPadovan(32)
println("N Recursive Floor LSystem String\n=============================================")
foreach(i -> println(rpad(i, 4), rpad(lr[i], 12), rpad(lf[i], 12),
rpad(i < 33 ? lL[i] : "", 12), (i < 11 ? sL[i] : "")), 1:64)
|
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
| #langur | langur | val .ispal = f len(.s) > 0 and .s == s2s .s, len(.s)..1
val .tests = h{
"": false,
"z": true,
"aha": true,
"αηα": true,
"αννα": true,
"αννασ": false,
"sees": true,
"seas": false,
"deified": true,
"solo": false,
"solos": true,
"amanaplanacanalpanama": true,
"a man a plan a canal panama": false, # true if we remove spaces
"ingirumimusnocteetconsumimurigni": true,
}
for .word in sort(keys .tests) {
val .foundpal = .ispal(.word)
writeln .word, ": ", .foundpal, if(.foundpal == .tests[.word]: ""; " (FAILED TEST)")
} |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Julia | Julia | using Dates
function datepalindromes(nextcount=20)
println("Date palindromes:")
count, d = 0, Date(1000, 1, 1)
for year in 2021:9200
try
dig = digits(year)
month = 10 * dig[1] + dig[2]
day = 10 * dig[3] + dig[4]
d = Date(year, month, day)
catch
continue
end
println(d)
count += 1
if count >= nextcount
break
end
end
end
datepalindromes()
|
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | today = DateList[Today];
res = {};
i = 0;
While[Length[res] < 15,
date = DatePlus[today, i];
ds = DateString[date, {"Year", "Month", "Day"}];
If[PalindromeQ[ds],
AppendTo[res, date]
];
i++;
]
Column[DateString[#, {"Year", "-", "Month", "-", "Day"}] & /@ res] |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Perl | Perl | use Thread 'async';
use Thread::Queue;
sub make_slices {
my ($n, @avail) = (shift, @{ +shift });
my ($q, @part, $gen);
$gen = sub {
my $pos = shift; # where to start in the list
if (@part == $n) {
# we accumulated enough for a partition, emit them and
# wait for main thread to pick them up, then back up
$q->enqueue(\@part, \@avail);
return;
}
# obviously not enough elements left to make a partition, back up
return if (@part + @avail < $n);
for my $i ($pos .. @avail - 1) { # try each in turn
push @part, splice @avail, $i, 1; # take one
$gen->($i); # go deeper
splice @avail, $i, 0, pop @part; # put it back
}
};
$q = new Thread::Queue;
(async{ &$gen; # start the main work load
$q->enqueue(undef) # signal that there's no more data
})->detach; # let the thread clean up after itself, not my problem
return $q;
}
my $qa = make_slices(4, [ 0 .. 9 ]);
while (my $a = $qa->dequeue) {
my $qb = make_slices(2, $qa->dequeue);
while (my $b = $qb->dequeue) {
my $rb = $qb->dequeue;
print "@$a | @$b | @$rb\n";
}
}
|
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two 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
| #Qi | Qi |
(define iterate
_ _ 0 -> []
F V N -> [V|(iterate F (F V) (1- N))])
(define next-row
R -> (MAPCAR + [0|R] (append R [0])))
(define pascal
N -> (iterate next-row [1] N))
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
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
| #APL | APL | result←longest_ordered_words file_path
f←file_path ⎕NTIE 0 ⍝ open file
text←⎕NREAD f 'char8' ⍝ read vector of 8bit chars
⎕NUNTIE f ⍝ close file
lines←text⊂⍨~text∊(⎕UCS 10 13) ⍝ split into lines (\r\n)
⍝ filter only words with ordered characters
ordered_words←lines/⍨{(⍳∘≢≡⍋)⍵}¨lines
⍝ find max of word lengths, filter only words with that length
result←ordered_words/⍨lengths=⍨⌈/lengths←≢¨ordered_words
|
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Padovan1,a,p,s]
p=N[Surd[((9+Sqrt[69])/18),3]+Surd[((9-Sqrt[69])/18),3],200];
s=1.0453567932525329623;
Padovan1[nmax_Integer]:=RecurrenceTable[{a[n+1]==a[n-1]+a[n-2],a[0]==1,a[1]==1,a[2]==1},a,{n,0,nmax-1}]
Padovan2[nmax_Integer]:=With[{},Floor[p^Range[-1,nmax-2]/s+1/2]]
Padovan1[20]
Padovan2[20]
Padovan1[64]===Padovan2[64]
SubstitutionSystem[{"A"->"B","B"->"C","C"->"AB"},"A",10]//Column
(StringLength/@SubstitutionSystem[{"A"->"B","B"->"C","C"->"AB"},"A",31])==Padovan2[32] |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Nim | Nim | import sequtils, strutils, tables
const
P = 1.324717957244746025960908854
S = 1.0453567932525329623
Rules = {'A': "B", 'B': "C", 'C': "AB"}.toTable
iterator padovan1(n: Natural): int {.closure.} =
## Yield the first "n" Padovan values using recurrence relation.
for _ in 1..min(n, 3): yield 1
var a, b, c = 1
var count = 3
while count < n:
(a, b, c) = (b, c, a + b)
yield c
inc count
iterator padovan2(n: Natural): int {.closure.} =
## Yield the first "n" Padovan values using formula.
if n > 1: yield 1
var p = 1.0
var count = 1
while count < n:
yield (p / S).toInt
p *= P
inc count
iterator padovan3(n: Natural): string {.closure.} =
## Yield the strings produced by the L-system.
var s = "A"
var count = 0
while count < n:
yield s
var next: string
for ch in s:
next.add Rules[ch]
s = move(next)
inc count
echo "First 20 terms of the Padovan sequence:"
echo toSeq(padovan1(20)).join(" ")
let list1 = toSeq(padovan1(64))
let list2 = toSeq(padovan2(64))
echo "The first 64 iterative and calculated values ",
if list1 == list2: "are the same." else: "differ."
echo ""
echo "First 10 L-system strings:"
echo toSeq(padovan3(10)).join(" ")
echo ""
echo "Lengths of the 32 first L-system strings:"
let list3 = toSeq(padovan3(32)).mapIt(it.len)
echo list3.join(" ")
echo "These lengths are",
if list3 == list1[0..31]: " " else: " not ",
"the 32 first terms of the Padovan sequence." |
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
| #Lasso | Lasso | define ispalindrome(text::string) => {
local(_text = string(#text)) // need to make copy to get rid of reference issues
#_text -> replace(regexp(`(?:$|\W)+`), -ignorecase)
local(reversed = string(#_text))
#reversed -> reverse
return #_text == #reversed
}
ispalindrome('Tätatät') // works with high ascii
ispalindrome('Hello World')
ispalindrome('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal – Panama!') |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Nim | Nim | import strformat, times
func digits(n: int): seq[int] =
var n = n
while n != 0:
result.add n mod 10
n = n div 10
echo "First 15 palindrome dates after 2020-02-02:"
var count = 0
var year = 2021
while count != 15:
let d = year.digits
let monthNum = 10 * d[0] + d[1]
let dayNum = 10 * d[2] + d[3]
if monthNum in 1..12:
if dayNum <= getDaysInMonth(Month(monthNum), year):
# Date is valid.
echo &"{year}-{monthNum:02}-{dayNum:02}"
inc count
inc year |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Perl | Perl | use Time::Piece;
my $d = Time::Piece->strptime("2020-02-02", "%Y-%m-%d");
for (my $k = 1 ; $k <= 15 ; $d += Time::Piece::ONE_DAY) {
my $s = $d->strftime("%Y%m%d");
if ($s eq reverse($s) and ++$k) {
print $d->strftime("%Y-%m-%d\n");
}
} |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Phix | Phix | with javascript_semantics
requires("1.0.2")
function partitions(sequence s)
integer l = length(s), N = sum(s)
sequence pset = {}, -- eg s==={2,0,2} -> {1,1,3,3}
rn = repeat(0,l) -- "" -> {{0,0},{},{0,0}}
for i=1 to l do
pset &= repeat(i,s[i])
rn[i] = repeat(0,s[i])
end for
if pset={} then return {rn} end if -- edge case
sequence res = permutes(pset,0)
-- eg {1,1,3,3} means put 1,2 in [1], 3,4 in [3]
-- .. {3,3,1,1} means put 1,2 in [3], 3,4 in [1]
for i=1 to length(res) do
sequence ri = res[i], -- a "flat" permute
rdii = repeat(1,l) -- where per set
integer rii = 0
for j=1 to length(ri) do
integer rdx = ri[j], -- which set
rnx = rdii[rdx] -- wherein""
rii += 1
rn[rdx][rnx] = rii -- plant 1..N
rdii[rdx] = rnx+1
end for
assert(rii=N)
res[i] = deep_copy(rn)
end for
return res
end function
procedure test(sequence p)
sequence q = partitions(p)
string {ia,s} = iff(length(q)=1?{"is",""}:{"are","s"})
printf(1,"There %s %,d ordered partion%s for %v:\n{%s}\n",
{ia,length(q),s,p,join(shorten(q,"",5,"%v"),"\n ")})
end procedure
papply({{2,0,2},{1,1,1},{1,2,0,1},{1,2,3,4},{},{0,0,0}},test)
|
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
| #Quackery | Quackery | [ over size -
space swap of
swap join ] is justify ( $ n --> )
[ witheach
[ number$
5 justify echo$ ]
cr ] is echoline ( [ --> )
[ [] 0 rot 0 join
witheach
[ tuck +
rot join swap ]
drop ] is nextline ( [ --> [ )
[ ' [ 1 ] swap
1 - times
[ dup echoline
nextline ]
echoline ] is pascal ( n --> )
16 pascal |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
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
| #AppleScript | AppleScript | use AppleScript version "2.3.1" -- Mac OS 10.9 (Mavericks) or later — for these 'use' commands.
use sorter : script "Insertion sort" -- https://www.rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#AppleScript.
use scripting additions
on longestOrderedWords(wordList)
script o
property allWords : wordList
property orderedWords : {}
end script
set longestWordLength to 0
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ""
ignoring case
repeat with i from 1 to (count o's allWords)
set thisWord to item i of o's allWords
set thisWordLength to (count thisWord)
if (thisWordLength ≥ longestWordLength) then
set theseCharacters to thisWord's characters
tell sorter to sort(theseCharacters, 1, -1)
set sortedWord to theseCharacters as text
if (sortedWord = thisWord) then
if (thisWordLength > longestWordLength) then
set o's orderedWords to {thisWord}
set longestWordLength to thisWordLength
else
set end of o's orderedWords to thisWord
end if
end if
end if
end repeat
end ignoring
set AppleScript's text item delimiters to astid
return (o's orderedWords)
end longestOrderedWords
-- Test code:
local wordList
set wordList to paragraphs of (read (((path to desktop as text) & "www.rosettacode.org:unixdict.txt") as alias) as «class utf8»)
-- ignoring white space, punctuation and diacriticals
return longestOrderedWords(wordList)
--- end ignoring |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Perl | Perl | use strict;
use warnings;
use feature <state say>;
use List::Lazy 'lazy_list';
my $p = 1.32471795724474602596;
my $s = 1.0453567932525329623;
my %rules = (A => 'B', B => 'C', C => 'AB');
my $pad_recur = lazy_list { state @p = (1, 1, 1, 2); push @p, $p[1]+$p[2]; shift @p };
sub pad_floor { int 1/2 + $p**($_<3 ? 1 : $_-2) / $s }
my($l, $m, $n) = (10, 20, 32);
my(@pr, @pf);
push @pr, $pad_recur->next() for 1 .. $n; say join ' ', @pr[0 .. $m-1];
push @pf, pad_floor($_) for 1 .. $n; say join ' ', @pf[0 .. $m-1];
my @L = 'A';
push @L, join '', @rules{split '', $L[-1]} for 1 .. $n;
say join ' ', @L[0 .. $l-1];
$pr[$_] == $pf[$_] and $pr[$_] == length $L[$_] or die "Uh oh, n=$_: $pr[$_] vs $pf[$_] vs " . length $L[$_] for 0 .. $n-1;
say '100% agreement among all 3 methods.'; |
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
| #Liberty_BASIC | Liberty BASIC | print isPalindrome("In girum imus nocte et consumimur igni")
print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "S"))
print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "SC"))
function isPalindrome(string$)
isPalindrome = 1
for i = 1 to int(len(string$)/2)
if mid$(string$, i, 1) <> mid$(string$, len(string$)-i+1, 1) then isPalindrome = 0 : exit function
next i
end function
function removePunctuation$(string$, remove$)
'P = remove puctuation. S = remove spaces C = remove case
If instr(upper$(remove$), "C") then string$ = lower$(string$)
If instr(upper$(remove$), "P") then removeCharacters$ = ",.!'()-&*?<>:;~[]{}"
If instr(upper$(remove$), "S") then removeCharacters$ = removeCharacters$;" "
for i = 1 to len(string$)
if instr(removeCharacters$, mid$(string$, i, 1)) then string$ = left$(string$, i-1);right$(string$, len(string$)-i) : i = i - 1
next i
removePunctuation$ = string$
end function |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Phix | Phix | with javascript_semantics
include builtins\timedate.e
sequence res = {}
for d=2021 to 9999 do
string s = sprintf("%4d",d),
t = reverse(s)
s &= "-"&t[1..2]&"-"&t[3..4]
sequence td = parse_date_string(s, {"YYYY-MM-DD"})
if timedate(td) then res = append(res,s) end if
end for
printf(1,"Count of palindromic dates [2021..9999]: %d\n\n",length(res))
printf(1,"first 15:\n%s\n",join_by(res[1..15],3,5))
printf(1,"last 15:\n%s\n",join_by(res[-15..-1],3,5))
|
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #PicoLisp | PicoLisp | (de partitions (Args)
(let Lst (range 1 (apply + Args))
(recur (Args Lst)
(ifn Args
'(NIL)
(mapcan
'((L)
(mapcar
'((R) (cons L R))
(recurse (cdr Args) (diff Lst L)) ) )
(comb (car Args) Lst) ) ) ) ) ) |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Python | Python | from itertools import combinations
def partitions(*args):
def p(s, *args):
if not args: return [[]]
res = []
for c in combinations(s, args[0]):
s0 = [x for x in s if x not in c]
for r in p(s0, *args[1:]):
res.append([c] + r)
return res
s = range(sum(args))
return p(s, *args)
print partitions(2, 0, 2) |
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
| #R | R | pascalTriangle <- function(h) {
for(i in 0:(h-1)) {
s <- ""
for(k in 0:(h-i)) s <- paste(s, " ", sep="")
for(j in 0:i) {
s <- paste(s, sprintf("%3d ", choose(i, j)), sep="")
}
print(s)
}
} |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
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
| #Arturo | Arturo | ordered?: function [w]->
w = join sort split w
words: read.lines relative "unixdict.txt"
ret: new []
loop words 'wrd [
if ordered? wrd ->
'ret ++ #[w: wrd l: size wrd]
]
sort.descending.by: 'l 'ret
maxl: get first ret 'l
print sort map select ret 'x -> maxl = x\l
'x -> x\w |
http://rosettacode.org/wiki/Padovan_sequence | Padovan sequence |
The Padovan sequence is similar to the Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.
Comment
Padovan
Fibonacci
Named after.
Richard Padovan
Leonardo of Pisa: Fibonacci
Recurrence initial values.
P(0)=P(1)=P(2)=1
F(0)=0, F(1)=1
Recurrence relation.
P(n)=P(n-2)+P(n-3)
F(n)=F(n-1)+F(n-2)
First 10 terms.
1,1,1,2,2,3,4,5,7,9
0,1,1,2,3,5,8,13,21,34
Ratio of successive terms...
Plastic ratio, p
Golden ratio, g
1.324717957244746025960908854…
1.6180339887498948482...
Exact formula of ratios p and q.
((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3)
(1+5**0.5)/2
Ratio is real root of polynomial.
p: x**3-x-1
g: x**2-x-1
Spirally tiling the plane using.
Equilateral triangles
Squares
Constants for ...
s= 1.0453567932525329623
a=5**0.5
... Computing by truncation.
P(n)=floor(p**(n-1) / s + .5)
F(n)=floor(g**n / a + .5)
L-System Variables.
A,B,C
A,B
L-System Start/Axiom.
A
A
L-System Rules.
A->B,B->C,C->AB
A->B,B->AB
Task
Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
Show the first twenty terms of the sequence.
Confirm that the recurrence and floor based functions give the same results for 64 terms,
Write a function/method/... using the L-system to generate successive strings.
Show the first 10 strings produced from the L-system
Confirm that the length of the first 32 strings produced is the Padovan sequence.
Show output here, on this page.
Ref
The Plastic Ratio - Numberphile video.
| #Phix | Phix | with javascript_semantics
sequence padovan = {1,1,1}
function padovanr(integer n)
while length(padovan)<n do
padovan &= padovan[$-2]+padovan[$-1]
end while
return padovan[n]
end function
constant p = 1.324717957244746025960908854,
s = 1.0453567932525329623
function padovana(integer n)
return floor(power(p,n-2)/s + 0.5)
end function
constant l = {"B","C","AB"}
function padovanl(string prev)
string res = ""
for i=1 to length(prev) do
res &= l[prev[i]-64]
end for
return res
end function
sequence pl = "A", l10 = {}
for n=1 to 64 do
integer pn = padovanr(n)
if padovana(n)!=pn or length(pl)!=pn then crash("oops") end if
if n<=10 then l10 = append(l10,pl) end if
pl = padovanl(pl)
end for
printf(1,"The first 20 terms of the Padovan sequence: %v\n\n",{padovan[1..20]})
printf(1,"The first 10 L-system strings: %v\n\n",{l10})
printf(1,"recursive, algorithmic, and l-system agree to n=64\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
| #LiveCode | LiveCode | function palindrome txt exact
if exact is empty or exact is not false then
set caseSensitive to true --default is false
else
replace space with empty in txt
put lower(txt) into txt
end if
return txt is reverse(txt)
end palindrome
function reverse str
repeat with i = the length of str down to 1
put byte i of str after revstr
end repeat
return revstr
end reverse |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #PureBasic | PureBasic | NewList pdates.s()
Procedure.b IsLeap(y.i)
ProcedureReturn Bool( y % 4 = 0 ) & Bool( y % 100 <> 0 ) | Bool( y % 400 = 0 )
EndProcedure
If OpenConsole("")=0 : End 1 : EndIf
For j=2021 To 9999
For m=1 To 12
tm2=28+1*IsLeap(j)
For t=1 To 31
If m=2 And t>tm2 : Break : EndIf
If (m=4 Or m=6 Or m=9 Or m=11) And t>30 : Break : EndIf
s$=Str(j)+RSet(Str(m),2,"0")+RSet(Str(t),2,"0")
If ReverseString(s$)=s$
AddElement(pdates()) : pdates()=Mid(s$,1,4)+"-"+Mid(s$,5,2)+"-"+Mid(s$,7,2)
EndIf
Next t
Next m
Next j
PrintN("Count of palindromic dates [2021..9999]: "+Str(ListSize(pdates())))
FirstElement(pdates())
t$="First 15:"
For x=1 To 2
PrintN(~"\n"+t$)
For y=1 To 15 : PrintN(pdates()) : NextElement(pdates()) : Next
t$="Last 15:" : SelectElement(pdates(),ListSize(pdates())-15)
Next
Input() : End |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Racket | Racket |
#lang racket
(define (comb k xs)
(cond [(zero? k) (list (cons '() xs))]
[(null? xs) '()]
[else (append (for/list ([cszs (comb (sub1 k) (cdr xs))])
(cons (cons (car xs) (car cszs)) (cdr cszs)))
(for/list ([cszs (comb k (cdr xs))])
(cons (car cszs) (cons (car xs) (cdr cszs)))))]))
(define (partitions xs)
(define (p xs ks)
(if (null? ks)
'(())
(for*/list ([cszs (comb (car ks) xs)] [rs (p (cdr cszs) (cdr ks))])
(cons (car cszs) rs))))
(p (range 1 (add1 (foldl + 0 xs))) xs))
(define (run . xs)
(printf "partitions~s:\n" xs)
(for ([x (partitions xs)]) (printf " ~s\n" x))
(newline))
(run 2 0 2)
(run 1 1 1)
|
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two 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
| #Racket | Racket | #lang racket
(define (pascal n)
(define (next-row current-row)
(map + (cons 0 current-row)
(append current-row '(0))))
(reverse
(for/fold ([triangle '((1))])
([row (in-range 1 n)])
(cons (next-row (first triangle)) triangle))))
|
http://rosettacode.org/wiki/Order_by_pair_comparisons | Order by pair comparisons |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Assume we have a set of items that can be sorted into an order by the user.
The user is presented with pairs of items from the set in no order,
the user states which item
is less than, equal to, or greater than the other (with respect to their
relative positions if fully ordered).
Write a function that given items that the user can order, asks the user to
give the result of comparing two items at a time and uses the comparison results
to eventually return the items in order.
Try and minimise the comparisons the user is asked for.
Show on this page, the function ordering the colours of the rainbow:
violet red green indigo blue yellow orange
The correct ordering being:
red orange yellow green blue indigo violet
Note:
Asking for/receiving user comparisons is a part of the task.
Code inputs should not assume an ordering.
The seven colours can form twenty-one different pairs.
A routine that does not ask the user "too many" comparison questions should be used.
| #11l | 11l | F user_cmp(String a, b)
R Int(input(‘IS #6 <, ==, or > #6 answer -1, 0 or 1:’.format(a, b)))
V items = ‘violet red green indigo blue yellow orange’.split(‘ ’)
V ans = sorted(items, key' cmp_to_key(user_cmp))
print("\n"ans.join(‘ ’)) |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
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
| #AutoHotkey | AutoHotkey |
MaxLen=0
Loop, Read, UnixDict.txt ; Assigns A_LoopReadLine to each line of the file
{
thisword := A_LoopReadLine ; Just for readability
blSort := isSorted(thisWord) ; reduce calls to IsSorted to improve performance
ThisLen := StrLen(ThisWord) ; reduce calls to StrLen to improve performance
If (blSort = true and ThisLen = maxlen)
list .= ", " . thisword
Else If (blSort = true and ThisLen > maxlen)
{
list := thisword
maxlen := ThisLen
}
}
IsSorted(word){ ; This function uses the ASCII value of the letter to determine its place in the alphabet.
; Thankfully, the dictionary is in all lowercase
lastchar=0
Loop, parse, word
{
if ( Asc(A_LoopField) < lastchar )
return false
lastchar := Asc(A_loopField)
}
return true
}
GUI, Add, Edit, w300 ReadOnly, %list%
GUI, Show
return ; End Auto-Execute Section
GUIClose:
ExitApp
|
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.