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/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.
| #Python | Python | from math import floor
from collections import deque
from typing import Dict, Generator
def padovan_r() -> Generator[int, None, None]:
last = deque([1, 1, 1], 4)
while True:
last.append(last[-2] + last[-3])
yield last.popleft()
_p, _s = 1.324717957244746025960908854, 1.0453567932525329623
def padovan_f(n: int) -> int:
return floor(_p**(n-1) / _s + .5)
def padovan_l(start: str='A',
rules: Dict[str, str]=dict(A='B', B='C', C='AB')
) -> Generator[str, None, None]:
axiom = start
while True:
yield axiom
axiom = ''.join(rules[ch] for ch in axiom)
if __name__ == "__main__":
from itertools import islice
print("The first twenty terms of the sequence.")
print(str([padovan_f(n) for n in range(20)])[1:-1])
r_generator = padovan_r()
if all(next(r_generator) == padovan_f(n) for n in range(64)):
print("\nThe recurrence and floor based algorithms match to n=63 .")
else:
print("\nThe recurrence and floor based algorithms DIFFER!")
print("\nThe first 10 L-system string-lengths and strings")
l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))
print('\n'.join(f" {len(string):3} {repr(string)}"
for string in islice(l_generator, 10)))
r_generator = padovan_r()
l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB'))
if all(len(next(l_generator)) == padovan_f(n) == next(r_generator)
for n in range(32)):
print("\nThe L-system, recurrence and floor based algorithms match to n=31 .")
else:
print("\nThe L-system, recurrence and floor based algorithms DIFFER!") |
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
| #Logo | Logo | to palindrome? :w
output equal? :w reverse :w
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.
| #Python | Python | '''Palindrome dates'''
from datetime import datetime
from itertools import chain
# palinDay :: Int -> [ISO Date]
def palinDay(y):
'''A possibly empty list containing the palindromic
date for the given year, if such a date exists.
'''
s = str(y)
r = s[::-1]
iso = '-'.join([s, r[0:2], r[2:]])
try:
datetime.strptime(iso, '%Y-%m-%d')
return [iso]
except ValueError:
return []
# --------------------------TEST---------------------------
# main :: IO ()
def main():
'''Count and samples of palindromic dates [2021..9999]
'''
palinDates = list(chain.from_iterable(
map(palinDay, range(2021, 10000))
))
for x in [
'Count of palindromic dates [2021..9999]:',
len(palinDates),
'\nFirst 15:',
'\n'.join(palinDates[0:15]),
'\nLast 15:',
'\n'.join(palinDates[-15:])
]:
print(x)
# MAIN ---
if __name__ == '__main__':
main() |
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.
| #Raku | Raku | sub partition(@mask is copy) {
my @op;
my $last = [+] @mask or return [] xx 1;
for @mask.kv -> $k, $v {
next unless $v;
temp @mask[$k] -= 1;
for partition @mask -> @p {
@p[$k].push: $last;
@op.push: @p;
}
}
return @op;
}
.say for reverse partition [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
| #Raku | Raku | sub pascal {
[1], { [0, |$_ Z+ |$_, 0] } ... *
}
.say for pascal[^10]; |
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.
| #Action.21 | Action! | DEFINE PTR="CARD"
PROC PrintArray(PTR ARRAY a BYTE size)
BYTE i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
Print(a(i))
OD
Put(']) PutE()
RETURN
BYTE FUNC IsBefore(CHAR ARRAY a,b)
DEFINE NO_KEY="255"
DEFINE KEY_Y="43"
DEFINE KEY_N="35"
BYTE CH=$02FC ;Internal hardware value for last key pressed
BYTE k
PrintF("Is %S before %S (y/n)? ",a,b)
CH=NO_KEY ;Flush the keyboard
DO
k=CH
UNTIL k=KEY_Y OR k=KEY_N
OD
CH=NO_KEY ;Flush the keyboard
IF k=KEY_Y THEN
PrintE("yes")
RETURN (1)
FI
PrintE("no")
RETURN (0)
PROC InteractiveInsertionSort(PTR ARRAY a BYTE size)
INT i,j
PTR value
FOR i=1 TO size-1
DO
value=a(i)
j=i-1
WHILE j>=0 AND IsBefore(value,a(j))=1
DO
a(j+1)=a(j)
j==-1
OD
a(j+1)=value
OD
RETURN
PROC Main()
DEFINE COUNT="7"
PTR ARRAY arr(COUNT)
arr(0)="violet" arr(1)="red"
arr(2)="green" arr(3)="indigo"
arr(4)="blue" arr(5)="yellow"
arr(6)="orange"
Print("Shuffled array: ")
PrintArray(arr,COUNT) PutE()
InteractiveInsertionSort(arr,COUNT)
PutE() Print("Sorted array: ")
PrintArray(arr,COUNT)
RETURN |
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.
| #Arturo | Arturo | lst: ["violet" "red" "green" "indigo" "blue" "yellow" "orange"]
count: 0
findSpot: function [l,e][
if empty? l -> return 0
loop.with:'i l 'item [
answer: input ~"Is |item| greater than |e| [y/n]? "
if answer="y" -> return i
]
return dec size l
]
sortedLst: new []
loop lst 'element ->
insert 'sortedLst findSpot sortedLst element element
print ""
print ["sorted =>" sortedLst] |
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
| #AWK | AWK | BEGIN {
abc = "abcdefghijklmnopqrstuvwxyz"
}
{
# Check if this line is an ordered word.
ordered = 1 # true
left = -1
for (i = 1; i <= length($0); i++) {
right = index(abc, substr($0, i, 1))
if (right == 0 || left > right) {
ordered = 0 # false
break
}
left = right
}
if (ordered) {
score = length($0)
if (score > best["score"]) {
# Reset the list of best ordered words.
best["score"] = score
best["count"] = 1
best[1] = $0
} else if (score == best["score"]) {
# Add this word to the list.
best[++best["count"]] = $0
}
}
}
END {
# Print the list of best ordered words.
for (i = 1; i <= best["count"]; i++)
print best[i]
} |
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.
| #Quackery | Quackery | ( --------------------- Recurrence -------------------- )
[ dup 0 = iff
[ drop ' [ ] ] done
dup 1 = iff
[ drop ' [ 1 ] ] done
dip [ [] 0 1 1 ]
2 - times
[ dip [ 2dup + ] swap
3 pack dip join
unpack ]
3 times join behead drop ] is padovan1 ( n --> [ )
say "With recurrence: " 20 padovan1 echo cr cr
( ------------------- Floor Function ------------------ )
$ "bigrat.qky" loadfile
[ [ $ "1.324717957244746025960908854"
$->v drop join ] constant
do ] is p ( --> n/d )
[ [ $ "1.0453567932525329623"
$->v drop join ] constant
do ] is s ( --> n/d )
[ 1 -
p rot v** s v/ 1 2 v+ / ] is padovan2 ( n --> n )
say "With floor function: "
[]
20 times [ i^ padovan2 join ]
echo cr cr
( ---------------------- L-System --------------------- )
[ $ "" swap witheach
[ nested quackery join ] ] is expand ( $ --> $ )
[ $ "B" ] is A ( $ --> $ )
[ $ "C" ] is B ( $ --> $ )
[ $ "AB" ] is C ( $ --> $ )
$ "A"
say "First 10 L System strings: "
9 times
[ dup echo$ sp
expand ]
echo$ cr cr
[] $ "A"
31 times
[ dup size
swap dip join
expand ]
size join
32 padovan1 = iff
[ say "The first 32 recurrence terms and L System lengths are the same." ]
else [ say "Oh no! It's all gone pear-shaped!" ]
|
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.
| #Raku | Raku | constant p = 1.32471795724474602596;
constant s = 1.0453567932525329623;
constant %rules = A => 'B', B => 'C', C => 'AB';
my @pad-recur = 1, 1, 1, -> $c, $b, $ { $b + $c } … *;
my @pad-floor = { floor 1/2 + p ** ($++ - 1) / s } … *;
my @pad-L-sys = 'A', { %rules{$^axiom.comb}.join } … *;
my @pad-L-len = @pad-L-sys.map: *.chars;
say @pad-recur.head(20);
say @pad-L-sys.head(10);
say "Recurrence == Floor to N=64" if (@pad-recur Z== @pad-floor).head(64).all;
say "Recurrence == L-len to N=32" if (@pad-recur Z== @pad-L-len).head(32).all; |
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
| #Lua | Lua | function ispalindrome(s) return s == string.reverse(s) 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.
| #QB64 | QB64 |
'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
' and for those countries which express their dates int dd-mm-yyyy format
' the user will choose what format to use for calculating
Dim dateTest As String, Mounth As Integer, Day As Integer, Year As Integer, Pal As Integer, choice As Integer
dateTest = ""
Mounth = 0
Day = 0
Year = 0
Pal = 0
choice = 0
Print " choose date format:"
Print " press 1 for using YYYY-MM-DD format"
Print " press 2 for using DD-MM-YYYY format"
While choice < 1 Or choice > 2
choice = Val(InKey$)
Wend
Print " Well, you have choosen format number "; choice
Sleep 2
For Year = 2020 To 2420
dateTest = LTrim$(Str$(Year))
For Mounth = 1 To 12
If Mounth < 10 Then k$ = "0" Else k$ = ""
If choice = 1 Then
dateTest = dateTest + k$ + LTrim$(Str$(Mounth))
Else
dateTest = k$ + LTrim$(Str$(Mounth)) + dateTest
End If
For Day = 1 To 31
If Mounth = 2 And Day > 28 Then Exit For
If (Mounth = 4 Or Mounth = 6 Or Mounth = 9 Or Mounth = 11) And Day > 30 Then Exit For
If Day < 10 Then k$ = "0" Else k$ = ""
If choice = 1 Then
dateTest = dateTest + k$ + LTrim$(Str$(Day))
Else
dateTest = k$ + LTrim$(Str$(Day)) + dateTest
End If
'Print dateTest: Sleep
For Pal = 1 To 4
If Mid$(dateTest, Pal, 1) <> Mid$(dateTest, 9 - Pal, 1) Then Exit For
Next
If Pal = 5 Then Print dateTest
If choice = 1 Then
dateTest = Left$(dateTest, 6)
Else
dateTest = Right$(dateTest, 6)
End If
Next
If choice = 1 Then
dateTest = Left$(dateTest, 4)
Else
dateTest = Right$(dateTest, 4)
End If
Next
dateTest = ""
Next
|
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.
| #Raku | Raku | my $start = '1000-01-01';
my @palindate = {
state $year = $start.substr(0,4);
++$year;
my $m = $year.substr(2, 2).flip;
my $d = $year.substr(0, 2).flip;
next if not try Date.new("$year-$m-$d");
"$year-$m-$d"
} … *;
my $date-today = Date.today; # 2020-02-02
my $k = @palindate.first: { Date.new($_) > $date-today }, :k;
say join "\n", @palindate[$k - 1 .. $k + 14];
say "\nTotal number of four digit year palindrome dates:\n" ~
my $four = @palindate.first( { .substr(5,1) eq '-' }, :k );
say "between {@palindate[0]} and {@palindate[$four - 1]}.";
my $five = @palindate.first: { .substr(6,1) eq '-' }, :k;
say "\nTotal number of five digit year palindrome dates:\n" ~
+@palindate[$four .. $five] |
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.
| #REXX | REXX | //*REXX program displays the ordered partitions as: orderedPartitions(i, j, k, ···). */
call orderedPartitions 2,0,2 /*Note: 2,,2 will also work. */
call orderedPartitions 1,1,1
call orderedPartitions 1,2,0,1 /*Note: 1,2,,1 will also work. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
orderedPartitions: procedure; #=arg(); bot.=; top.=; low=; high=; d=123456789
t=0 /*T: is the sum of all the arguments.*/
do i=1 for #; t=t + arg(i) /*sum all the highest numbers in parts.*/
end /*i*/ /* [↑] may have an omitted argument. */
hdr= ' partitions for: ' /*define the start of the header text. */
do j=1 for #; _= arg(j) /* _: is the Jth argument. */
len.j=max(1, _) /*LEN: length of args. «0 is special»*/
bot.j=left(d, _); if _==0 then bot.j=0 /*define the bottom number for range.*/
top.j=right(left(d,t),_); if _==0 then top.j=0 /* " " top " " " */
@.j=left(d, t); if _==0 then @.j=0 /*define the digits used for VERIFY. */
hdr=hdr _ /*build (by appending) display header.*/
low=low || bot.j; high=high || top.j /*the low and high numbers for DO below*/
end /*j*/
/* [↓] same as: okD=left('0'd, t+1) */
/*define the legal digits to be used. */
okD=left(0 || d, t + 1) /*define the legal digits to be used. */
say; hdr=center(hdr" ", 60, '═'); say hdr /*display centered title for the output*/
say /*show a blank line (as a separator). */
do g=low to high /* [↑] generate the ordered partitions*/
if verify(g, okD) \==0 then iterate /*filter out unwanted partitions (digs)*/
p=1 /*P: is the position of a decimal dig.*/
$= /*$: will be the transformed numbers. */
do k=1 for #; _=substr(g, p, len.k) /*verify the partitions numbers. */
if verify(_, @.k) \==0 then iterate g /*is the decimal digit not valid ? */
!= /* [↓] validate the decimal number. */
if @.k\==0 then do j=1 for length(_); z=substr(_, j, 1) /*get a dig.*/
if pos(z, $)\==0 then iterate g /*previous ?*/
!=!','z /*add comma.*/
if j==1 then iterate /*is firstt?*/
if z<=substr(_, j-1, 1) then iterate g /*ordered ?*/
if pos(z, _, 1 +pos(z, _))\==0 then iterate g /*duplicate?*/
end /*j*/
p=p + len.k /*point to the next decimal digit (num)*/
$=$ ' {'strip(translate(!, ,0), ,",")'}' /*dress number up by suppessing LZ ··· */
end /*k*/
say center($, length(hdr) ) /*display numbers in ordered partition.*/
end /*g*/
return |
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
| #RapidQ | RapidQ | DEFINT values(100) = {0,1}
INPUT "Number of rows: "; nrows
PRINT SPACE$((nrows)*3);" 1"
FOR row = 2 TO nrows
PRINT SPACE$((nrows-row)*3+1);
FOR i = row TO 1 STEP -1
values(i) = values(i) + values(i-1)
PRINT FORMAT$("%5d ", values(i));
NEXT i
PRINT
NEXT row |
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.
| #AutoHotkey | AutoHotkey | data := ["Violet", "Red", "Green", "Indigo", "Blue", "Yellow", "Orange"]
result := [], num := 0, Questions :=""
for i, Color1 in data{
found :=false
if !result.count(){
result.Push(Color1)
continue
}
for j, Color2 in result {
if (color1 = color2)
continue
MsgBox, 262180,, % (Q := "Q" ++num " is " Color1 " > " Color2 "?")
ifMsgBox, Yes
Questions .= Q "`t`tYES`n"
else {
Questions .= Q "`t`tNO`n"
result.InsertAt(j, Color1)
found := true
break
}
}
if !found
result.Push(Color1)
}
for i, color in result
output .= color ", "
MsgBox % Questions "`nSorted Output :`n" Trim(output, ", ")
return |
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.
| #C | C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int interactiveCompare(const void *x1, const void *x2)
{
const char *s1 = *(const char * const *)x1;
const char *s2 = *(const char * const *)x2;
static int count = 0;
printf("(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: ", ++count, s1, s2);
int response;
scanf("%d", &response);
return response;
}
void printOrder(const char *items[], int len)
{
printf("{ ");
for (int i = 0; i < len; ++i) printf("%s ", items[i]);
printf("}\n");
}
int main(void)
{
const char *items[] =
{
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
};
qsort(items, sizeof(items)/sizeof(*items), sizeof(*items), interactiveCompare);
printOrder(items, sizeof(items)/sizeof(*items));
return 0;
} |
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
| #BaCon | BaCon | 'Ordered words - improved version
OPTION COLLAPSE TRUE
list$ = LOAD$("unixdict.txt")
FOR word$ IN list$ STEP NL$
term$ = EXTRACT$(SORT$(EXPLODE$(word$, 1)), " ")
IF word$ = term$ THEN
IF LEN(term$) > MaxLen THEN
MaxLen = LEN(term$)
result$ = word$
ELIF LEN(term$) = MaxLen THEN
result$ = APPEND$(result$, 0, word$, NL$)
END IF
END IF
NEXT
PRINT result$
|
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.
| #REXX | REXX | /*REXX pgm computes the Padovan seq. (using 2 methods), and also computes the L─strings.*/
numeric digits 40 /*better precision for Plastic ratio. */
parse arg n nF Ln cL . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 20 /*Not specified? Then use the default.*/
if nF=='' | nF=="," then nF= 64 /* " " " " " " */
if Ln=='' | Ln=="," then Ln= 10 /* " " " " " " */
if cL=='' | cL=="," then cL= 32 /* " " " " " " */
PR= 1.324717957244746025960908854 /*the plastic ratio (constant). */
s= 1.0453567932525329623 /*tge "s" constant. */
@.= .; @.0= 1; @.1= 1; @.2= 1 /*initialize 3 terms of the Padovan seq*/
!.= .; !.0= 1; !.1= 1; !.2= 1 /* " " " " " " " */
call req1; call req2; call req3; call req4 /*invoke the four task's requirements. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
floor: procedure; parse arg x; t= trunc(x); return t - (x<0) * (x\=t)
pF: procedure expose !. PR s; parse arg x; !.x= floor(PR**(x-1)/s + .5); return !.x
th: parse arg th; return th||word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4))
/*──────────────────────────────────────────────────────────────────────────────────────*/
L_sys: procedure: arg x; q=; a.A= 'B'; a.B= 'C'; a.C= 'AB'; if x=='' then return 'A'
do k=1 for length(x); _= substr(x, k, 1); q= q || a._
end /*k*/; return q
/*──────────────────────────────────────────────────────────────────────────────────────*/
p: procedure expose @.; parse arg x; if @.x\==. then return @.x /*@.X defined?*/
xm2= x - 2; xm3= x - 3; @.x= @.xm2 + @.xm3; return @.x
/*──────────────────────────────────────────────────────────────────────────────────────*/
req1: say 'The first ' n " terms of the Pandovan sequence:";
$= @.0; do j=1 for n-1; $= $ p(j)
end /*j*/
say $; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
req2: ok= 1; what= ' terms match for recurrence and floor─based functions.'
do j=0 for nF; if p(j)==pF(j) then iterate
say 'the ' th(j) " terms don't match:" p(j) pF(j); ok= 0
end /*j*/
say
if ok then say 'all ' nF what; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
req3: y=; $= 'A'
do j=1 for Ln-1; y= L_sys(y); $= $ L_sys(y)
end /*j*/
say
say 'L_sys:' $; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
req4: y=; what=' terms match for Padovan terms and lengths of L_sys terms.'
ok= 1; do j=1 for cL; y= L_sys(y); L= length(y)
if L==p(j-1) then iterate
say 'the ' th(j) " Padovan term doesn't match the length of the",
'L_sys term:' p(j-1) L; ok= 0
end /*j*/
say
if ok then say 'all ' cL what; return |
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
| #M4 | M4 | define(`palindrorev',`ifelse(`$1',invert(`$1'),`yes',`no')')dnl
palindrorev(`ingirumimusnocteetconsumimurigni')
palindrorev(`this is not 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.
| #REXX | REXX | /*REXX program finds & displays the next N palindromic dates starting after 2020─02─02*/
/* ───── */
parse arg n from . /*obtain optional argumets from the CL*/
if n=='' | n=="," then n= 15 /*Not specified? Then use the default.*/
if from=='' | from=="," then from= '2020-02-02' /* " " " " " " */
#= 0 /*the count of palindromic dates so far*/
do j=date('Base', from, "ISO")+1 until #==n /*find palindromic dates 'til N found*/
aDate= date('ISO', j, "Base") /*convert a "base" date to ISO format. */
$= space( translate(aDate, , '-'), 0) /*elide the dashes (-) in this date. */
if $\==reverse($) then iterate /*Not palindromic? Then skip this date*/
say 'a palindromic date: ' aDate /*display a palindromic date ──► term. */
#= # + 1 /*bump the counter of palindromic dates*/
end /*j*/ /*stick a fork in it, we're all done. */ |
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.
| #Ring | Ring |
load "stdlib.ring"
dt = 0
num = 0
limit = 15
? "First 15 palindromic dates:" + nl
while num < limit
dt++
dateStr = adddays(date(),dt)
newDate = substr(dateStr,7,4) + substr(dateStr,4,2) + substr(dateStr,1,2)
newDate2 = substr(dateStr,7,4) + "-" + substr(dateStr,4,2) + "-" + substr(dateStr,1,2)
if ispalindrome(newDate)
num++
? newDate2
ok
if num > limit
exit
ok
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.
| #Ruby | Ruby | def partition(mask)
return [[]] if mask.empty?
[*1..mask.inject(:+)].permutation.map {|perm|
mask.map {|num_elts| perm.shift(num_elts).sort }
}.uniq
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.
| #Rust | Rust |
use itertools::Itertools;
type NArray = Vec<Vec<Vec<usize>>>;
fn generate_partitions(args: &[usize]) -> NArray {
// calculate the sum of all partitions
let max = args.iter().sum();
// generate combinations with the given lengths
// for each partition
let c = args.iter().fold(vec![], |mut acc, arg| {
acc.push((1..=max).combinations(*arg).collect::<Vec<_>>());
acc
});
// create a cartesian product of all individual combinations
// filter/keep only where all the elements are there and exactly once
c.iter()
.map(|i| i.iter().cloned())
.multi_cartesian_product()
.unique()
.filter(|x| x.iter().cloned().flatten().unique().count() == max)
.collect::<Vec<_>>()
}
#[allow(clippy::clippy::ptr_arg)]
fn print_partitions(result: &NArray) {
println!("Partitions:");
for partition in result {
println!("{:?}", partition);
}
}
fn main() {
print_partitions(generate_partitions(&[2, 0, 2]).as_ref());
print_partitions(generate_partitions(&[1, 1, 1]).as_ref());
print_partitions(generate_partitions(&[2, 3]).as_ref());
print_partitions(generate_partitions(&[0]).as_ref());
}
|
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
| #Red | Red | Red[]
pascal-triangle: function [
n [ integer! ] "number of rows"
][
row: make vector! [ 1 ]
loop n [
print row
left: copy row
right: copy row
insert left 0
append right 0
row: left + right
]
] |
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.
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool InteractiveCompare(const string& s1, const string& s2)
{
if(s1 == s2) return false; // don't ask to compare items that are the same
static int count = 0;
string response;
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
getline(cin, response);
return !response.empty() && response.front() == 'y';
}
void PrintOrder(const vector<string>& items)
{
cout << "{ ";
for(auto& item : items) cout << item << " ";
cout << "}\n";
}
int main()
{
const vector<string> items
{
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
};
vector<string> sortedItems;
// Use a binary insertion sort to order the items. It should ask for
// close to the minimum number of questions required
for(auto& item : items)
{
cout << "Inserting '" << item << "' into ";
PrintOrder(sortedItems);
// lower_bound performs the binary search using InteractiveCompare to
// rank the items
auto spotToInsert = lower_bound(sortedItems.begin(),
sortedItems.end(), item, InteractiveCompare);
sortedItems.insert(spotToInsert, item);
}
PrintOrder(sortedItems);
return 0;
} |
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
| #BBC_BASIC | BBC BASIC | dict% = OPENIN("unixdict.txt")
IF dict%=0 ERROR 100, "Failed to open dictionary file"
max% = 2
REPEAT
A$ = GET$#dict%
IF LENA$ >= max% THEN
i% = 0
REPEAT i% += 1
UNTIL ASCMID$(A$,i%) > ASCMID$(A$,i%+1)
IF i% = LENA$ THEN
IF i% > max% max% = i% : list$ = ""
list$ += A$ + CHR$13 + CHR$10
ENDIF
ENDIF
UNTIL EOF#dict%
CLOSE #dict%
PRINT list$
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.
| #Ruby | Ruby | padovan = Enumerator.new do |y|
ar = [1, 1, 1]
loop do
ar << ar.first(2).sum
y << ar.shift
end
end
P, S = 1.324717957244746025960908854, 1.0453567932525329623
def padovan_f(n) = (P**(n-1) / S + 0.5).floor
puts "Recurrence Padovan: #{padovan.take(20)}"
puts "Floor function: #{(0...20).map{|n| padovan_f(n)}}"
n = 63
bool = (0...n).map{|n| padovan_f(n)} == padovan.take(n)
puts "Recurrence and floor function are equal upto #{n}: #{bool}."
puts
def l_system(axiom = "A", rules = {"A" => "B", "B" => "C", "C" => "AB"} )
return enum_for(__method__, axiom, rules) unless block_given?
loop do
yield axiom
axiom = axiom.chars.map{|c| rules[c] }.join
end
end
puts "First 10 elements of L-system: #{l_system.take(10).join(", ")} "
n = 32
bool = l_system.take(n).map(&:size) == padovan.take(n)
puts "Sizes of first #{n} l_system strings equal to recurrence padovan? #{bool}."
|
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
| #Maple | Maple |
with(StringTools):
IsPalindrome("ingirumimusnocteetconsumimurigni");
IsPalindrome("In girum imus nocte et consumimur igni");
IsPalindrome(LowerCase(DeleteSpace("In girum imus nocte et consumimur igni")));
|
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.
| #Ruby | Ruby | require 'date'
palindate = Enumerator.new do |yielder|
("2020"..).each do |y|
m, d = y.reverse.scan(/../) # let the Y10K kids handle 5 digit years
strings = [y, m, d]
yielder << strings.join("-") if Date.valid_date?( *strings.map( &:to_i ) )
end
end
puts palindate.take(15) |
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.
| #Rust | Rust | // [dependencies]
// chrono = "0.4"
fn is_palindrome(s: &str) -> bool {
s.chars().rev().eq(s.chars())
}
fn main() {
let mut date = chrono::Utc::today();
let mut count = 0;
while count < 15 {
if is_palindrome(&date.format("%Y%m%d").to_string()) {
println!("{}", date.format("%F"));
count += 1;
}
date = date.succ();
}
} |
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.
| #Sidef | Sidef | func part(_, {.is_empty}) { [[]] }
func partitions({.is_empty}) { [[]] }
func part(s, args) {
gather {
s.combinations(args[0], { |*c|
part(s - c, args.ft(1)).each{|r| take([c] + r) }
})
}
}
func partitions(args) {
part(@(1..args.sum), args)
}
[[],[0,0,0],[1,1,1],[2,0,2]].each { |test_case|
say "partitions #{test_case}:"
partitions(test_case).each{|part| say part }
print "\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
| #Retro | Retro | 2 elements i j
: pascalTriangle
cr dup
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop
;
13 pascalTriangle |
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.
| #Commodore_BASIC | Commodore BASIC | 100 REM SORT BY COMPARISON
110 DIM IN$(6), OU$(6)
120 FOR I=0 TO 6:READ IN$(I): NEXT I
130 DATA VIOLET,RED,GREEN,INDIGO,BLUE,YELLOW,ORANGE
140 OU$(0)=IN$(0):N=1
150 FOR I=1 TO 6
160 : IN$=IN$(I)
180 : GOSUB 390
190 : FOR J=0 TO N-1
200 : OU$ = OU$(J)
210 : GOSUB 340
220 : IF R>=0 THEN 280
230 : FOR K=N TO J+1 STEP -1
240 : OU$(K) = OU$(K-1)
250 : NEXT K
260 : OU$(J) = IN$
270 : GOTO 300
280 : NEXT J
290 : OU$(N) = IN$
300 : N=N+1
310 NEXT I
320 GOSUB 390
330 END
340 PRINT "IS "IN$" < "OU$"? (Y/N)";
350 GET K$: IF K$<>"Y" AND K$<>"N" THEN 350
360 PRINT K$
370 R = K$="Y"
380 RETURN
390 PRINT "(";
400 IF N=1 THEN 420
410 FOR Q=0 TO N-2:PRINT OU$(Q)",";:NEXT Q
420 PRINT OU$(N-1)")"
430 RETURN |
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.
| #F.23 | F# |
// Order by pair comparisons. Nigel Galloway: April 23rd., 2021
let clrs=let n=System.Random() in lN2p [|for g in 7..-1..2->n.Next(g)|] [|"Red";"Orange";"Yellow";"Green";"Blue";"Indigo";"Violet"|]
let rec fG n g=printfn "Is %s less than %s" n g; match System.Console.ReadLine() with "Yes"-> -1|"No"->1 |_->printfn "Enter Yes or No"; fG n g
let mutable z=0 in printfn "%A sorted to %A using %d questions" clrs (clrs|>Array.sortWith(fun n g->z<-z+1; fG n g)) z
|
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
| #Befunge | Befunge | 00p30p>_010p120p0>#v0~>>\$::48*\`\"~"`+!>>#v_$:#v_>30g:!#v_1-30p55+0>:30g3+g\1v
>0#v _$^#::\p04:<^+>#1^#\p01:p02*g02!`\g01:<@$ _ ,#!>#:<$<^<!:g03$<_^#!`\g00:+<
^<o>\30g2+p40g1+^0p00p03+1*g03!-g00 < < < < < <:>#$:#$00g#<\#<`#<!#<2#$0g#<*#<_ |
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.
| #Rust | Rust | fn padovan_recur() -> impl std::iter::Iterator<Item = usize> {
let mut p = vec![1, 1, 1];
let mut n = 0;
std::iter::from_fn(move || {
let pn = if n < 3 { p[n] } else { p[0] + p[1] };
p[0] = p[1];
p[1] = p[2];
p[2] = pn;
n += 1;
Some(pn)
})
}
fn padovan_floor() -> impl std::iter::Iterator<Item = usize> {
const P: f64 = 1.324717957244746025960908854;
const S: f64 = 1.0453567932525329623;
(0..).map(|x| (P.powf((x - 1) as f64) / S + 0.5).floor() as usize)
}
fn padovan_lsystem() -> impl std::iter::Iterator<Item = String> {
let mut str = String::from("A");
std::iter::from_fn(move || {
let result = str.clone();
let mut next = String::new();
for ch in str.chars() {
match ch {
'A' => next.push('B'),
'B' => next.push('C'),
_ => next.push_str("AB"),
}
}
str = next;
Some(result)
})
}
fn main() {
println!("First 20 terms of the Padovan sequence:");
for p in padovan_recur().take(20) {
print!("{} ", p);
}
println!();
println!(
"\nRecurrence and floor functions agree for first 64 terms? {}",
padovan_recur().take(64).eq(padovan_floor().take(64))
);
println!("\nFirst 10 strings produced from the L-system:");
for p in padovan_lsystem().take(10) {
print!("{} ", p);
}
println!();
println!(
"\nLength of first 32 strings produced from the L-system = Padovan sequence? {}",
padovan_lsystem()
.map(|x| x.len())
.take(32)
.eq(padovan_recur().take(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.
| #Swift | Swift | import Foundation
class PadovanRecurrence: Sequence, IteratorProtocol {
private var p = [1, 1, 1]
private var n = 0
func next() -> Int? {
let pn = n < 3 ? p[n] : p[0] + p[1]
p[0] = p[1]
p[1] = p[2]
p[2] = pn
n += 1
return pn
}
}
class PadovanFloor: Sequence, IteratorProtocol {
private let P = 1.324717957244746025960908854
private let S = 1.0453567932525329623
private var n = 0
func next() -> Int? {
let p = Int(floor(pow(P, Double(n - 1)) / S + 0.5))
n += 1
return p
}
}
class PadovanLSystem: Sequence, IteratorProtocol {
private var str = "A"
func next() -> String? {
let result = str
var next = ""
for ch in str {
switch (ch) {
case "A": next.append("B")
case "B": next.append("C")
default: next.append("AB")
}
}
str = next
return result
}
}
print("First 20 terms of the Padovan sequence:")
for p in PadovanRecurrence().prefix(20) {
print("\(p)", terminator: " ")
}
print()
var b = PadovanRecurrence().prefix(64)
.elementsEqual(PadovanFloor().prefix(64))
print("\nRecurrence and floor functions agree for first 64 terms? \(b)")
print("\nFirst 10 strings produced from the L-system:");
for p in PadovanLSystem().prefix(10) {
print(p, terminator: " ")
}
print()
b = PadovanLSystem().prefix(32).map{$0.count}
.elementsEqual(PadovanRecurrence().prefix(32))
print("\nLength of first 32 strings produced from the L-system = Padovan sequence? \(b)") |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | PalindromeQ |
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.
| #Sidef | Sidef | var palindates = gather {
for y in (2020 .. 9999) {
var (m, d) = Str(y).flip.last(4).split(2)...
with ([y,m,d].join('-')) {|t|
take(t) if Date.valid(t, "%Y-%m-%d")
}
}
}
say "Count of palindromic dates [2020..9999]: #{palindates.len}"
for a,b in ([
["First 15:", palindates.head(15)],
["Last 15:", palindates.tail(15)]
]) {
say ("\n#{a}\n", b.slices(5).map { .join(" ") }.join("\n"))
} |
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.
| #Swift | Swift | import Foundation
func isPalindrome(_ string: String) -> Bool {
let chars = string.lazy
return chars.elementsEqual(chars.reversed())
}
let format = DateFormatter()
format.dateFormat = "yyyyMMdd"
let outputFormat = DateFormatter()
outputFormat.dateFormat = "yyyy-MM-dd"
var count = 0
let limit = 15
let calendar = Calendar.current
var date = Date()
while count < limit {
if isPalindrome(format.string(from: date)) {
print(outputFormat.string(from: date))
count += 1
}
date = calendar.date(byAdding: .day, value: 1, to: 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.
| #Tcl | Tcl | package require Tcl 8.5
package require struct::set
# Selects all k-sized combinations from a list.
# "Borrowed" from elsewhere on RC
proc selectCombinationsFrom {k l} {
if {$k == 0} {return {}} elseif {$k == [llength $l]} {return [list $l]}
set all {}
set n [expr {[llength $l] - [incr k -1]}]
for {set i 0} {$i < $n} {} {
set first [lindex $l $i]
incr i
if {$k == 0} {
lappend all $first
} else {
foreach s [selectCombinationsFrom $k [lrange $l $i end]] {
lappend all [list $first {*}$s]
}
}
}
return $all
}
# Construct the partitioning of a given list
proc buildPartitions {lst n args} {
# Base case when we have no further partitions to process
if {[llength $args] == 0} {
return [list [list $lst]]
}
set result {}
set c [selectCombinationsFrom $n $lst]
if {[llength $c] == 0} {set c [list $c]}
foreach comb $c {
# Sort necessary for "nice" order
set rest [lsort -integer [struct::set difference $lst $comb]]
foreach p [buildPartitions $rest {*}$args] {
lappend result [list $comb {*}$p]
}
}
return $result
}
# Wrapper that assembles the initial list and calls the partitioner
proc partitions args {
set sum [tcl::mathop::+ {*}$args]
set startingSet {}
for {set i 1} {$i <= $sum} {incr i} {
lappend startingSet $i
}
return [buildPartitions $startingSet {*}$args]
} |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #11l | 11l | [1,2,1,3,2] < [1,2,0,4,4,0,0,0] |
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
| #REXX | REXX | /*REXX program displays (or writes to a file) Pascal's triangle (centered/formatted).*/
numeric digits 3000 /*be able to handle gihugeic triangles.*/
parse arg nn . /*obtain the optional argument from CL.*/
if nn=='' | nn=="," then nn= 10 /*Not specified? Then use the default.*/
n= abs(nn) /*N is the number of rows in triangle.*/
w= length( !(n-1) % !(n%2) % !(n - 1 - n%2)) /*W: the width of biggest integer. */
ww= (n-1) * (W + 1) + 1 /*WW: " " " triangle's last row.*/
@.= 1; $.= @.; unity= right(1, w) /*defaults rows & lines; aligned unity.*/
/* [↓] build rows of Pascals' triangle*/
do r=1 for n; rm= r-1 /*Note: the first column is always 1.*/
do c=2 to rm; cm= c-1 /*build the rest of the columns in row.*/
@.r.c= @.rm.cm + @.rm.c /*assign value to a specific row & col.*/
$.r = $.r right(@.r.c, w) /*and construct a line for output (row)*/
end /*c*/ /* [↑] C is the column being built.*/
if r\==1 then $.r= $.r unity /*for rows≥2, append a trailing "1".*/
end /*r*/ /* [↑] R is the row being built.*/
/* [↑] WIDTH: for nicely looking line.*/
do r=1 for n; $$= center($.r, ww) /*center this particular Pascals' row. */
if nn>0 then say $$ /*SAY if NN is positive, else */
else call lineout 'PASCALS.'n, $$ /*write this Pascal's row ───► a file.*/
end /*r*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; !=1; do j=2 to arg(1); != !*j; end /*j*/; return ! /*compute factorial*/ |
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.
| #Factor | Factor | USING: formatting io kernel math.order prettyprint qw sorting ;
qw{ violet red green indigo blue yellow orange }
[ "Is %s > %s? (y/n) " printf readln "y" = +gt+ +lt+ ? ] sort . |
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.
| #FreeBASIC | FreeBASIC |
Dim Shared As Byte r, n = 1
Dim Shared As String IN1, OU1
Dim Shared As String IN(6), OU(6)
Dim As Byte i, j, k
For i = 0 To 6 : Read IN(i) : Next i
Data "violet", "red", "green", "indigo", "blue", "yellow", "orange"
OU(0) = IN(0)
Sub PrintOrder
Print : Print "{";
If n = 1 Then Print OU(n-1);")" : Exit Sub
For q As Byte = 0 To n-2
Print OU(q);", ";
Next q
Print OU(n-1);"}"
End Sub
Sub InteractiveCompare
Dim As String*1 T
Print "Es "; IN1; " < "; OU1; "? (S/N) ";
Do: T = Inkey$: Loop Until T <> ""
If Instr("snSN", T) Then Print Ucase(T)
r = T = "S"
End Sub
For i = 1 To 6
IN1 = IN(i)
For j = 0 To n-1
OU1 = OU(j)
InteractiveCompare
If r < 0 Then
For k = n To j+1 Step -1
OU(k) = OU(k-1)
Next k
OU(j) = IN1
n += 1
Exit For, For
End If
Next j
OU(n) = IN1
n += 1
Next i
PrintOrder
Sleep
|
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
| #Bracmat | Bracmat | ( orderedWords
= bow result longestLength word character
. 0:?bow
& :?result
& 0:?longestLength
& @( get$(!arg,STR)
: ?
( [!bow %?word \n [?bow ?
& @( !word
: ( ? %@?character <%@!character ?
| ?
( [!longestLength
& !word !result:?result
| [>!longestLength:[?longestLength
& !word:?result
|
)
)
)
& ~`
)
)
| !result
)
& orderedWords$"unixdict.txt" |
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.
| #Wren | Wren | import "/big" for BigRat
import "/dynamic" for Struct
var padovanRecur = Fn.new { |n|
var p = List.filled(n, 1)
if (n < 3) return p
for (i in 3...n) p[i] = p[i-2] + p[i-3]
return p
}
var padovanFloor = Fn.new { |n|
var p = BigRat.fromDecimal("1.324717957244746025960908854")
var s = BigRat.fromDecimal("1.0453567932525329623")
var f = List.filled(n, 0)
var pow = BigRat.one
f[0] = (pow/p/s + 0.5).floor.toInt
for (i in 1...n) {
f[i] = (pow/s + 0.5).floor.toInt
pow = pow * p
}
return f
}
var LSystem = Struct.create("LSystem", ["rules", "init", "current"])
var step = Fn.new { |lsys|
var s = ""
if (lsys.current == "") {
lsys.current = lsys.init
} else {
for (c in lsys.current) s = s + lsys.rules[c]
lsys.current = s
}
return lsys.current
}
var padovanLSys = Fn.new { |n|
var rules = {"A": "B", "B": "C", "C": "AB"}
var lsys = LSystem.new(rules, "A", "")
var p = List.filled(n, null)
for (i in 0...n) p[i] = step.call(lsys)
return p
}
System.print("First 20 members of the Padovan sequence:")
System.print(padovanRecur.call(20))
var recur = padovanRecur.call(64)
var floor = padovanFloor.call(64)
var areSame = (0...64).all { |i| recur[i] == floor[i] }
var s = areSame ? "give" : "do not give"
System.print("\nThe recurrence and floor based functions %(s) the same results for 64 terms.")
var p = padovanLSys.call(32)
var lsyst = p.map { |e| e.count }.toList
System.print("\nFirst 10 members of the Padovan L-System:")
System.print(p.take(10).toList)
System.print("\nand their lengths:")
System.print(lsyst.take(10).toList)
recur = recur.take(32).toList
areSame = (0...32).all { |i| recur[i] == lsyst[i] }
s = areSame ? "give" : "do not give"
System.print("\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
| #MATLAB | MATLAB | function trueFalse = isPalindrome(string)
trueFalse = all(string == fliplr(string)); %See if flipping the string produces the original string
if not(trueFalse) %If not a palindrome
string = lower(string); %Lower case everything
trueFalse = all(string == fliplr(string)); %Test again
end
if not(trueFalse) %If still not a palindrome
string(isspace(string)) = []; %Strip all space characters out
trueFalse = all(string == fliplr(string)); %Test one last time
end
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.
| #UNIX_Shell | UNIX Shell | is_palyndrom_date() { date -d "$1" 1>/dev/null 2>&1 && echo "$1" ; }
for _H in {2..9}; do
for _I in {0..9}; do
for _J in {0..99}; do
is_palyndrom_date ${_H}${_I}`printf "%02d%s" ${_J}`-`printf "%02d%s" ${_J} | rev`-`printf "%02d%s" ${_H}${_I} | rev`
done
done
done
|
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.
| #VBA | VBA |
Sub MainPalindromeDates()
Const FirstDate As String = "2020-02-02"
Const NumberOfDates As Integer = 15
Dim D As String, temp As String, Cpt As Integer
temp = Format(DateAdd("d", 1, CDate(FirstDate)), "yyyy-mm-dd")
Do
D = Replace(temp, "-", "")
If IsDatePalindrome(D) Then
Debug.Print Left(D, 4) & "-" & Mid(D, 5, 2) & "-" & Right(D, 2)
Cpt = Cpt + 1
End If
temp = Format(DateAdd("d", 1, CDate(temp)), "yyyy-mm-dd")
Loop While Cpt < NumberOfDates
End Sub
Function IsDatePalindrome(strDate As String) As Boolean
IsDatePalindrome = StrReverse(Left(strDate, 4)) = Right(strDate, 4)
End Function
|
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.
| #Ursala | Ursala | #import std
#import nat
opart =
-+
~&art^?\~&alNCNC ^|JalSPfarSPMplrDSL/~& ^DrlPrrPlXXS/~&rt ^DrlrjXS/~&l choices@lrhPX,
^\~& nrange/1+ sum:-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.
| #Wren | Wren | import "os" for Process
var genPart // recursive so predeclare
genPart = Fn.new { |n, res, pos|
if (pos == res.count) {
var x = List.filled(n.count, null)
for (i in 0...x.count) x[i] = []
var i = 0
for (c in res) {
x[c].add(i+1)
i = i + 1
}
System.print(x)
return
}
for (i in 0...n.count) {
if (n[i] != 0) {
n[i] = n[i] - 1
res[pos] = i
genPart.call(n, res, pos+1)
n[i] = n[i] + 1
}
}
}
var orderedPart = Fn.new { |nParts|
System.print("Ordered %(nParts)")
var sum = 0
for (c in nParts) sum = sum + c
genPart.call(nParts, List.filled(sum, 0), 0)
}
var args = Process.arguments
if (args.count == 0) {
orderedPart.call([2, 0, 2])
return
}
var n = List.filled(args.count, 0)
var i = 0
for (a in args) {
n[i] = Num.fromString(a)
if (n[i] < 0) {
System.print("negative partition size not meaningful")
return
}
i = i + 1
}
orderedPart.call(n) |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program orderlist64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult1: .asciz "List1 < List2 \n" // message result
szMessResult2: .asciz "List1 => List2 \n" // message result
szCarriageReturn: .asciz "\n"
qTabList1: .quad 1,2,3,4,5
.equ NBELEMENTS1, (. - qTabList1) /8
qTabList2: .quad 1,2,1,5,2,2
.equ NBELEMENTS2, (. - qTabList2) /8
qTabList3: .quad 1,2,3,4,5
.equ NBELEMENTS3, (. - qTabList3) /8
qTabList4: .quad 1,2,3,4,5,6
.equ NBELEMENTS4, (. - qTabList4) /8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdriTabList1
mov x1,NBELEMENTS1
ldr x2,qAdriTabList2
mov x3,NBELEMENTS2
bl listeOrder
cmp x0,0 // false ?
beq 1f // yes
ldr x0,qAdrszMessResult1 // list 1 < list 2
bl affichageMess // display message
b 2f
1:
ldr x0,qAdrszMessResult2
bl affichageMess // display message
2:
ldr x0,qAdriTabList1
mov x1,NBELEMENTS1
ldr x2,qAdriTabList3
mov x3,NBELEMENTS3
bl listeOrder
cmp x0,0 // false ?
beq 3f // yes
ldr x0,qAdrszMessResult1 // list 1 < list 2
bl affichageMess // display message
b 4f
3:
ldr x0,qAdrszMessResult2
bl affichageMess // display message
4:
ldr x0,qAdriTabList1
mov x1,NBELEMENTS1
ldr x2,qAdriTabList4
mov x3,NBELEMENTS4
bl listeOrder
cmp x0,0 // false ?
beq 5f // yes
ldr x0,qAdrszMessResult1 // list 1 < list 2
bl affichageMess // display message
b 6f
5:
ldr x0,qAdrszMessResult2
bl affichageMess // display message
6:
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdriTabList1: .quad qTabList1
qAdriTabList2: .quad qTabList2
qAdriTabList3: .quad qTabList3
qAdriTabList4: .quad qTabList4
qAdrszMessResult1: .quad szMessResult1
qAdrszMessResult2: .quad szMessResult2
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* liste order */
/******************************************************************/
/* x0 contains the address of list 1 */
/* x1 contains list 1 size */
/* x2 contains the address of list 2 */
/* x3 contains list 2 size */
/* x0 returns 1 if list1 < list2 */
/* x0 returns 0 else */
listeOrder:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
cbz x1,99f // list 1 size = zero ?
cbz x3,98f // list 2 size = zero ?
mov x4,#0 // index list 1
mov x5,#0 // index list 2
1:
ldr x6,[x0,x4,lsl #3] // load list 1 element
ldr x8,[x2,x5,lsl #3] // load list 2 element
cmp x6,x8 // compar
bgt 4f
beq 2f // list 1 = list 2
add x4,x4,1 // increment index 1
cmp x4,x1 // end list ?
bge 5f
b 1b // else loop
2:
add x4,x4,1 // increment index 1
cmp x4,x1 // end list ?
bge 3f // yes -> verif size
add x5,x5,1 // else increment index 2
cmp x5,x3 // end list 2 ?
bge 4f
b 1b // else loop
3:
cmp x1,x3 // compar size
bge 4f // list 2 < list 1
blt 5f // list 1 < list 2
b 100f
4:
mov x0,#0 // list 1 > list 2
b 100f
5:
mov x0,#1 // list 1 < list 2
b 100f
98: // error
mov x0,-2
b 100f
99: // error
mov x0,-1
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #Ring | Ring |
row = 5
for i = 0 to row - 1
col = 1
see left(" ",row-i)
for k = 0 to i
see "" + col + " "
col = col*(i-k)/(k+1)
next
see nl
next
|
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.
| #Go | Go | package main
import (
"fmt"
"sort"
"strings"
)
var count int = 0
func interactiveCompare(s1, s2 string) bool {
count++
fmt.Printf("(%d) Is %s < %s? ", count, s1, s2)
var response string
_, err := fmt.Scanln(&response)
return err == nil && strings.HasPrefix(response, "y")
}
func main() {
items := []string{"violet", "red", "green", "indigo", "blue", "yellow", "orange"}
var sortedItems []string
// Use a binary insertion sort to order the items. It should ask for
// close to the minimum number of questions required
for _, item := range items {
fmt.Printf("Inserting '%s' into %s\n", item, sortedItems)
// sort.Search performs the binary search using interactiveCompare to
// rank the items
spotToInsert := sort.Search(len(sortedItems), func(i int) bool {
return interactiveCompare(item, sortedItems[i])
})
sortedItems = append(sortedItems[:spotToInsert],
append([]string{item}, sortedItems[spotToInsert:]...)...)
}
fmt.Println(sortedItems)
} |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #11l | 11l | LDX #$02
LDY #$03
LDA ($20,x) ;uses the values stored at $20+x and $21+x as a memory address, and reads the byte at that address.
LDA ($20),y ;uses the values store at $20 and $21 as a memory address, and reads the byte at that address + Y. |
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
| #Burlesque | Burlesque | ln{so}f[^^{L[}>mL[bx(==)[+(L[)+]f[uN |
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
| #Maxima | Maxima | palindromep(s) := block([t], t: sremove(" ", sdowncase(s)), sequal(t, sreverse(t)))$
palindromep("Sator arepo tenet opera rotas"); /* true */ |
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.
| #Wren | Wren | import "/fmt" for Fmt
import "/date" for Date
var isPalDate = Fn.new { |date|
date = date.format(Date.rawDate)
return date == date[-1..0]
}
Date.default = Date.isoDate
System.print("The next 15 palindromic dates in yyyy-mm-dd format after 2020-02-02 are:")
var date = Date.new(2020, 2, 2)
var count = 0
while (count < 15) {
date = date.addDays(1)
if (isPalDate.call(date)) {
System.print(date)
count = count + 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.
| #zkl | zkl | fcn partitions(args){
args=vm.arglist;
s:=(1).pump(args.sum(0),List); // (1,2,3,...)
fcn(s,args,p){
if(not args) return(T(T));
res:=List();
foreach c in (Utils.Helpers.pickNFrom(args[0],s)){
s0:=s.copy().removeEach(c);
foreach r in (self.fcn(s0,args[1,*])){ res.append(T(c).extend(r)) }
}
res
}(s,args)
} |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Ada | Ada | package Tables is
type Table is private;
type Ordering is (Lexicographic, Psionic, ...); -- add others
procedure Sort (It : in out Table;
Order_By : in Ordering := Lexicographic;
Column : in Positive := 1;
Reverse_Ordering : in Boolean := False);
private
... -- implementation specific
end Tables; |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #ACL2 | ACL2 | ACL2 !>(lexorder '(1 2 3) '(1 2 3 4))
T
ACL2 !>(lexorder '(1 2 4) '(1 2 3))
NIL |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Action.21 | Action! | INT FUNC Compare(INT ARRAY x INT xLen INT ARRAY y INT yLen)
INT i,len
len=xLen
IF len>yLen THEN
len=yLen
FI
FOR i=0 TO len-1
DO
IF x(i)>y(i) THEN
RETURN (1)
ELSEIF x(i)<y(i) THEN
RETURN (-1)
FI
OD
IF xLen>yLen THEN
RETURN (1)
ELSEIF xLen<yLen THEN
RETURN (-1)
FI
RETURN (0)
BYTE FUNC Less(INT ARRAY x INT xLen INT ARRAY y INT yLen)
IF Compare(x,xLen,y,yLen)<0 THEN
RETURN (1)
FI
RETURN (0)
PROC PrintArray(INT ARRAY x INT len)
INT i
Put('[)
FOR i=0 TO len-1
DO
PrintI(x(i))
IF i<len-1 THEN
Put(' )
FI
OD
Put('])
RETURN
PROC Test(INT ARRAY x INT xLen INT ARRAY y INT yLen)
PrintArray(x,xLen)
IF Less(x,xLen,y,yLen) THEN
Print(" < ")
ELSE
Print(" >= ")
FI
PrintArray(y,yLen) PutE()
RETURN
PROC Main()
INT ARRAY a=[1 2 1 5 2]
INT ARRAY b=[1 2 1 5 2 2]
INT ARRAY c=[1 2 3 4 5]
INT ARRAY d=[1 2 3 4 5]
Test(a,5,b,6)
Test(b,6,a,5)
Test(b,6,c,5)
Test(c,5,b,6)
Test(c,5,d,5)
RETURN |
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
| #Ruby | Ruby | def pascal(n)
raise ArgumentError, "must be positive." if n < 1
yield ar = [1]
(n-1).times do
ar.unshift(0).push(0) # tack a zero on both ends
yield ar = ar.each_cons(2).map(&:sum)
end
end
pascal(8){|row| puts row.join(" ").center(20)} |
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.
| #Haskell | Haskell | import Control.Monad
import Control.Monad.ListM (sortByM, insertByM, partitionM, minimumByM)
import Data.Bool (bool)
import Data.Monoid
import Data.List
--------------------------------------------------------------------------------
isortM, msortM, tsortM :: Monad m => (a -> a -> m Ordering) -> [a] -> m [a]
-- merge sort from the Control.Monad.ListM library
msortM = sortByM
-- insertion sort
isortM cmp = foldM (flip (insertByM cmp)) []
-- tree sort aka qsort (which is not)
tsortM cmp = go
where
go [] = pure []
go (h:t) = do (l, g) <- partitionM (fmap (LT /=) . cmp h) t
go l <+> pure [h] <+> go g
(<+>) = liftM2 (++) |
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.
| #Java | Java | import java.util.*;
public class SortComp1 {
public static void main(String[] args) {
List<String> items = Arrays.asList("violet", "red", "green", "indigo", "blue", "yellow", "orange");
List<String> sortedItems = new ArrayList<>();
Comparator<String> interactiveCompare = new Comparator<String>() {
int count = 0;
Scanner s = new Scanner(System.in);
public int compare(String s1, String s2) {
System.out.printf("(%d) Is %s <, =, or > %s. Answer -1, 0, or 1: ", ++count, s1, s2);
return s.nextInt();
}
};
for (String item : items) {
System.out.printf("Inserting '%s' into %s\n", item, sortedItems);
int spotToInsert = Collections.binarySearch(sortedItems, item, interactiveCompare);
// when item does not equal an element in sortedItems,
// it returns bitwise complement of insertion point
if (spotToInsert < 0) spotToInsert = ~spotToInsert;
sortedItems.add(spotToInsert, item);
}
System.out.println(sortedItems);
}
} |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #8th | 8th | LDX #$02
LDY #$03
LDA ($20,x) ;uses the values stored at $20+x and $21+x as a memory address, and reads the byte at that address.
LDA ($20),y ;uses the values store at $20 and $21 as a memory address, and reads the byte at that address + Y. |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #6502_Assembly | 6502 Assembly | LDX #$02
LDY #$03
LDA ($20,x) ;uses the values stored at $20+x and $21+x as a memory address, and reads the byte at that address.
LDA ($20),y ;uses the values store at $20 and $21 as a memory address, and reads the byte at that address + Y. |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #Ada | Ada | print 2 + 3 * 5 ; same as 2 + (3 * 5)
print 3 * 5 + 2 ; same as 3 * (5 + 2) |
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
| #C | C | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#define MAXLEN 100
typedef char TWord[MAXLEN];
typedef struct Node {
TWord word;
struct Node *next;
} Node;
int is_ordered_word(const TWord word) {
assert(word != NULL);
int i;
for (i = 0; word[i] != '\0'; i++)
if (word[i] > word[i + 1] && word[i + 1] != '\0')
return 0;
return 1;
}
Node* list_prepend(Node* words_list, const TWord new_word) {
assert(new_word != NULL);
Node *new_node = malloc(sizeof(Node));
if (new_node == NULL)
exit(EXIT_FAILURE);
strcpy(new_node->word, new_word);
new_node->next = words_list;
return new_node;
}
Node* list_destroy(Node *words_list) {
while (words_list != NULL) {
Node *temp = words_list;
words_list = words_list->next;
free(temp);
}
return words_list;
}
void list_print(Node *words_list) {
while (words_list != NULL) {
printf("\n%s", words_list->word);
words_list = words_list->next;
}
}
int main() {
FILE *fp = fopen("unixdict.txt", "r");
if (fp == NULL)
return EXIT_FAILURE;
Node *words = NULL;
TWord line;
unsigned int max_len = 0;
while (fscanf(fp, "%99s\n", line) != EOF) {
if (strlen(line) > max_len && is_ordered_word(line)) {
max_len = strlen(line);
words = list_destroy(words);
words = list_prepend(words, line);
} else if (strlen(line) == max_len && is_ordered_word(line)) {
words = list_prepend(words, line);
}
}
fclose(fp);
list_print(words);
return EXIT_SUCCESS;
} |
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
| #MAXScript | MAXScript | fn isPalindrome s =
(
local reversed = ""
for i in s.count to 1 by -1 do reversed += s[i]
return reversed == 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.
| #XPL0 | XPL0 | func Rev(N);
int N;
[N:= N/10;
return rem(0)*10 + N;
];
proc NumOut(N);
int N;
[if N < 10 then ChOut(0, ^0);
IntOut(0, N);
];
int C, Y, M, D, Q, R;
[C:= 0;
for Y:= 2021 to -1>>1 do
for M:= 1 to 12 do
for D:= 1 to 28 do
[Q:= Y/100;
R:= rem(0);
if Q = Rev(D) and R = Rev(M) then
[IntOut(0, Y); ChOut(0, ^-);
NumOut(M); ChOut(0, ^-);
NumOut(D); CrLf(0);
C:= C+1;
if C >= 15 then return;
];
];
] |
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.
| #Yabasic | Yabasic |
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" : fi
dateTest$ = dateTest$ + ltrim$(str$(mes))
for dia = 1 to 31
if mes = 2 and dia > 28 then break : fi
if (mes = 4 or mes = 6 or mes = 9 or mes = 11) and dia > 30 then break : fi
if dia < 10 then dateTest$ = dateTest$ + "0" : fi
dateTest$ = dateTest$ + ltrim$(str$(dia))
for Pal = 1 to 4
if mid$(dateTest$, Pal, 1) <> mid$(dateTest$, 9 - Pal, 1) then break : fi
next Pal
if Pal = 5 then
total = total + 1
if total <= 15 then print left$(dateTest$,4),"-",mid$(dateTest$,5,2),"-",right$(dateTest$,2) : fi
end if
if total > 15 then break : break : break : fi
dateTest$ = left$(dateTest$, 6)
next dia
dateTest$ = left$(dateTest$, 4)
next mes
dateTest$ = ""
next anno
end
|
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #ALGOL_68 | ALGOL 68 | # as the options have distinct types (INT, BOOL and PROC( STRING, STRING )INT) the #
# easiest way to support these optional parameters in Algol 68 would be to have an array #
# with elements of these types #
# See the Named Arguments sample for cases where the option types are not distinct #
# default comparison function #
PROC default compare = ( STRING a, b )INT: IF a < b THEN -1 ELIF a = b THEN 0 ELSE 1 FI;
# sorting procedure #
PROC configurable sort = ( [,]STRING data, []UNION( INT, BOOL, PROC( STRING, STRING )INT ) options )VOID:
BEGIN
# set initial values for the options #
INT sort column := 2 LWB data;
BOOL reverse sort := FALSE;
PROC( STRING, STRING )INT comparator := default compare;
# overide from the supplied options #
FOR opt pos FROM LWB options TO UPB options DO
CASE options[ opt pos ]
IN ( PROC( STRING, STRING )INT p ): comparator := p
, ( INT c ): sort column := c
, ( BOOL r ): reverse sort := r
ESAC
OD
# do the sort .... #
END # configurable sort # ;
# example calls #
[ 1 : 2, 1 : 3 ]STRING data := ( ( "a", "bb", "cde" ), ( "x", "abcdef", "Q" ) );
# sort data, default comparison, first column, reverse order #
configurable sort( data, ( TRUE ) );
# sort data, second column, ignore first chaacter when sorting, normal order #
configurable sort( data, ( 2, ( STRING a, STRING b )INT: default compare( a[ LWB a + 1 : ], b[ LWB b + 1 : ] ) ) );
# default sort #
configurable sort( data, () ) |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
procedure Order is
type IntArray is array (Positive range <>) of Integer;
List1 : IntArray := (1, 2, 3, 4, 5);
List2 : IntArray := (1, 2, 1, 5, 2, 2);
List3 : IntArray := (1, 2, 1, 5, 2);
List4 : IntArray := (1, 2, 1, 5, 2);
type Animal is (Rat, Cat, Elephant);
type AnimalArray is array (Positive range <>) of Animal;
List5 : AnimalArray := (Cat, Elephant, Rat, Cat);
List6 : AnimalArray := (Cat, Elephant, Rat);
List7 : AnimalArray := (Cat, Cat, Elephant);
begin
Put_Line (Boolean'Image (List1 > List2)); -- True
Put_Line (Boolean'Image (List2 > List3)); -- True
Put_Line (Boolean'Image (List3 > List4)); -- False, equal
Put_Line (Boolean'Image (List5 > List6)); -- True
Put_Line (Boolean'Image (List6 > List7)); -- True
end Order;
|
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
| #Run_BASIC | Run BASIC | input "number of rows? ";r
for i = 0 to r - 1
c = 1
print left$(" ",(r*2)-(i*2));
for k = 0 to i
print using("####",c);
c = c*(i-k)/(k+1)
next
print
next |
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.
| #jq | jq | def inputOption($prompt; $options):
def r:
$prompt | stderr
| input as $in
| if $in|test($options) then $in else r end;
r;
# Inserts item $x in the array input, which is kept sorted as per user input
# assuming it is already sorted. $q is the prompt number.
# Input: [$q; $a]
# Output: [$qPrime, $aPrime]
def insortRight($x):
. as [$q, $a]
| { lo: 0, hi: ($a|length), $q }
| until( .lo >= .hi;
( ((.lo + .hi)/2)|floor) as $mid
| .q += 1
| "\(.q): Is \($x) less than \($a[$mid])? y/n: " as $prompt
| (inputOption($prompt; "[yn]") == "y") as $less
| if ($less) then .hi = $mid
else .lo = $mid + 1
end)
# insert at position .lo
| [ .q, ($a[: .lo] + [x] + $a[.lo :]) ];
def order:
reduce .[] as $item ( [0, []]; insortRight($item) )
| .[1];
["violet red green indigo blue yellow orange"|splits(" ")]
| order as $ordered
| ("\nThe colors of the rainbow, in sorted order, are:",
$ordered ) |
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.
| #Julia | Julia | const nrequests = [0]
const ordering = Dict("violet" => 7, "red" => 1, "green" => 4, "indigo" => 6, "blue" => 5,
"yellow" => 3, "orange" => 2)
function tellmeifgt(x, y)
nrequests[1] += 1
while true
print("Is $x greater than $y? (Y/N) => ")
s = strip(readline())
if length(s) > 0
(s[1] == 'Y' || s[1] == 'y') && return true
(s[1] == 'N' || s[1] == 'n') && return false
end
end
end
function orderbypair!(a::Vector)
incr = div(length(a), 2)
while incr > 0
for i in incr+1:length(a)
j = i
tmp = a[i]
while j > incr && tellmeifgt(a[j - incr], tmp)
a[j] = a[j-incr]
j -= incr
end
a[j] = tmp
end
if incr == 2
incr = 1
else
incr = floor(Int, incr * 5.0 / 11)
end
end
return a
end
const words = String.(split("violet red green indigo blue yellow orange", r"\s+"))
println("Unsorted: $words")
println("Sorted: $(orderbypair!(words)). Total requests: $(nrequests[1]).")
|
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #ALGOL_60 | ALGOL 60 | print 2 + 3 * 5 ; same as 2 + (3 * 5)
print 3 * 5 + 2 ; same as 3 * (5 + 2) |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #ALGOL_68 | ALGOL 68 | print 2 + 3 * 5 ; same as 2 + (3 * 5)
print 3 * 5 + 2 ; same as 3 * (5 + 2) |
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
| #C.23 | C# | using System;
using System.Linq;
using System.Net;
static class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
string text = client.DownloadString("http://www.puzzlers.org/pub/wordlists/unixdict.txt");
string[] words = text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var query = from w in words
where IsOrderedWord(w)
group w by w.Length into ows
orderby ows.Key descending
select ows;
Console.WriteLine(string.Join(", ", query.First().ToArray()));
}
private static bool IsOrderedWord(string w)
{
for (int i = 1; i < w.Length; i++)
if (w[i] < w[i - 1])
return false;
return true;
}
} |
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
| #min | min | (dup reverse ==) :palindrome?
(dup "" split reverse "" join ==) :str-palindrome?
"apple" str-palindrome? puts
"racecar" str-palindrome? puts
(a b c) palindrome? puts
(a b b a) palindrome? puts |
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.
| #zkl | zkl | TD,date,n := Time.Date, T(2020,02,02), 15;
while(n){
ds:=TD.toYMDString(date.xplode()) - "-";
if(ds==ds.reverse()){ n-=1; println(TD.toYMDString(date.xplode())); }
date=TD.addYMD(date,0,0,1);
} |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q-values".
Task
Given one list of p-values, return the p-values correcting for multiple comparisons
p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}
There are several methods to do this, see:
Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101
Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075
Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733
Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325
Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190
Each method has its own advantages and disadvantages.
| #C | C | #include <stdio.h>//printf
#include <stdlib.h>//qsort
#include <math.h>//fabs
#include <stdbool.h>//bool data type
#include <strings.h>//strcasecmp
#include <assert.h>//assert, necessary for random integer selection
unsigned int * seq_len(const unsigned int START, const unsigned int END) {
//named after R function of same name, but simpler function
unsigned start = (unsigned)START;
unsigned end = (unsigned)END;
if (START == END) {
unsigned int *restrict sequence = malloc( (end+1) * sizeof(unsigned int));
if (sequence == NULL) {
printf("malloc failed at %s line %u\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
for (unsigned i = 0; i < end; i++) {
sequence[i] = i+1;
}
return sequence;
}
if (START > END) {
end = (unsigned)START;
start = (unsigned)END;
}
const unsigned LENGTH = end - start ;
unsigned int *restrict sequence = malloc( (1+LENGTH) * sizeof(unsigned int));
if (sequence == NULL) {
printf("malloc failed at %s line %u\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
if (START < END) {
for (unsigned index = 0; index <= LENGTH; index++) {
sequence[index] = start + index;
}
} else {
for (unsigned index = 0; index <= LENGTH; index++) {
sequence[index] = end - index;
}
}
return sequence;
}
//modified from https://phoxis.org/2012/07/12/get-sorted-index-orderting-of-an-array/
double *restrict base_arr = NULL;
static int compar_increase (const void *restrict a, const void *restrict b) {
int aa = *((int *restrict ) a), bb = *((int *restrict) b);
if (base_arr[aa] < base_arr[bb]) {
return 1;
} else if (base_arr[aa] == base_arr[bb]) {
return 0;
} else {
return -1;
}
}
static int compar_decrease (const void *restrict a, const void *restrict b) {
int aa = *((int *restrict ) a), bb = *((int *restrict) b);
if (base_arr[aa] < base_arr[bb]) {
return -1;
} else if (base_arr[aa] == base_arr[bb]) {
return 0;
} else {
return 1;
}
}
unsigned int * order (const double *restrict ARRAY, const unsigned int SIZE, const bool DECREASING) {
//this has the same name as the same R function
unsigned int *restrict idx = malloc(SIZE * sizeof(unsigned int));
if (idx == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
base_arr = malloc(sizeof(double) * SIZE);
if (base_arr == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
for (unsigned int i = 0; i < SIZE; i++) {
base_arr[i] = ARRAY[i];
idx[i] = i;
}
if (DECREASING == false) {
qsort(idx, SIZE, sizeof(unsigned int), compar_decrease);
} else if (DECREASING == true) {
qsort(idx, SIZE, sizeof(unsigned int), compar_increase);
}
free(base_arr); base_arr = NULL;
return idx;
}
double * cummin(const double *restrict ARRAY, const unsigned int NO_OF_ARRAY_ELEMENTS) {
//this takes the same name of the R function which it copies
//this requires a free() afterward where it is used
if (NO_OF_ARRAY_ELEMENTS < 1) {
puts("cummin function requires at least one element.\n");
printf("Failed at %s line %u\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
double *restrict output = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (output == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
double cumulative_min = ARRAY[0];
for (unsigned int i = 0; i < NO_OF_ARRAY_ELEMENTS; i++) {
if (ARRAY[i] < cumulative_min) {
cumulative_min = ARRAY[i];
}
output[i] = cumulative_min;
}
return output;
}
double * cummax(const double *restrict ARRAY, const unsigned int NO_OF_ARRAY_ELEMENTS) {
//this takes the same name of the R function which it copies
//this requires a free() afterward where it is used
if (NO_OF_ARRAY_ELEMENTS < 1) {
puts("function requires at least one element.\n");
printf("Failed at %s line %u\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
double *restrict output = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (output == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
double cumulative_max = ARRAY[0];
for (unsigned int i = 0; i < NO_OF_ARRAY_ELEMENTS; i++) {
if (ARRAY[i] > cumulative_max) {
cumulative_max = ARRAY[i];
}
output[i] = cumulative_max;
}
return output;
}
double * pminx(const double *restrict ARRAY, const unsigned int NO_OF_ARRAY_ELEMENTS, const double X) {
//named after the R function pmin
if (NO_OF_ARRAY_ELEMENTS < 1) {
puts("pmin requires at least one element.\n");
printf("Failed at %s line %u\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
double *restrict pmin_array = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (pmin_array == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
if (ARRAY[index] < X) {
pmin_array[index] = ARRAY[index];
} else {
pmin_array[index] = X;
}
}
return pmin_array;
}
void double_say (const double *restrict ARRAY, const size_t NO_OF_ARRAY_ELEMENTS) {
printf("[1] %e", ARRAY[0]);
for (unsigned int i = 1; i < NO_OF_ARRAY_ELEMENTS; i++) {
printf(" %.10f", ARRAY[i]);
if (((i+1) % 5) == 0) {
printf("\n[%u]", i+1);
}
}
puts("\n");
}
/*void uint_say (const unsigned int *restrict ARRAY, const size_t NO_OF_ARRAY_ELEMENTS) {
//for debugging
printf("%u", ARRAY[0]);
for (size_t i = 1; i < NO_OF_ARRAY_ELEMENTS; i++) {
printf(",%u", ARRAY[i]);
}
puts("\n");
}*/
double * uint2double (const unsigned int *restrict ARRAY, const unsigned int NO_OF_ARRAY_ELEMENTS) {
double *restrict doubleArray = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (doubleArray == NULL) {
printf("Failure to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
doubleArray[index] = (double)ARRAY[index];
}
return doubleArray;
}
double min2 (const double N1, const double N2) {
if (N1 < N2) {
return N1;
} else {
return N2;
}
}
double * p_adjust (const double *restrict PVALUES, const unsigned int NO_OF_ARRAY_ELEMENTS, const char *restrict STRING) {
//this function is a translation of R's p.adjust "BH" method
// i is always i[index] = NO_OF_ARRAY_ELEMENTS - index - 1
if (NO_OF_ARRAY_ELEMENTS < 1) {
puts("p_adjust requires at least one element.\n");
printf("Failed at %s line %u\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
short int TYPE = -1;
if (STRING == NULL) {
TYPE = 0;
} else if (strcasecmp(STRING, "BH") == 0) {
TYPE = 0;
} else if (strcasecmp(STRING, "fdr") == 0) {
TYPE = 0;
} else if (strcasecmp(STRING, "by") == 0) {
TYPE = 1;
} else if (strcasecmp(STRING, "Bonferroni") == 0) {
TYPE = 2;
} else if (strcasecmp(STRING, "hochberg") == 0) {
TYPE = 3;
} else if (strcasecmp(STRING, "holm") == 0) {
TYPE = 4;
} else if (strcasecmp(STRING, "hommel") == 0) {
TYPE = 5;
} else {
printf("%s doesn't match any accepted FDR methods.\n", STRING);
printf("Failed at %s line %u\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
if (TYPE == 2) {//Bonferroni method
double *restrict bonferroni = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (bonferroni == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
const double BONFERRONI = PVALUES[index] * NO_OF_ARRAY_ELEMENTS;
if (BONFERRONI >= 1.0) {
bonferroni[index] = 1.0;
} else if ((0.0 <= BONFERRONI) && (BONFERRONI < 1.0)) {
bonferroni[index] = BONFERRONI;
} else {
printf("%g is outside of the interval I planned.\n", BONFERRONI);
printf("Failure at %s line %u\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
}
return bonferroni;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
} else if (TYPE == 4) {//Holm method
/*these values are computed separately from BH, BY, and Hochberg because they are
computed differently*/
unsigned int *restrict o = order(PVALUES, NO_OF_ARRAY_ELEMENTS, false);
//sorted in reverse of methods 0-3
double *restrict o2double = uint2double(o, NO_OF_ARRAY_ELEMENTS);
double *restrict cummax_input = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
for (unsigned index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
cummax_input[index] = (NO_OF_ARRAY_ELEMENTS - index ) * (double)PVALUES[o[index]];
// printf("cummax_input[%zu] = %e\n", index, cummax_input[index]);
}
free(o); o = NULL;
unsigned int *restrict ro = order(o2double, NO_OF_ARRAY_ELEMENTS, false);
free(o2double); o2double = NULL;
double *restrict cummax_output = cummax(cummax_input, NO_OF_ARRAY_ELEMENTS);
free(cummax_input); cummax_input = NULL;
double *restrict pmin = pminx(cummax_output, NO_OF_ARRAY_ELEMENTS, 1);
free(cummax_output); cummax_output = NULL;
double *restrict qvalues = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
qvalues[index] = pmin[ro[index]];
}
free(pmin); pmin = NULL;
free(ro); ro = NULL;
return qvalues;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
} else if (TYPE == 5) {//Hommel method
//i <- seq_len(n)
//o <- order(p)
unsigned int *restrict o = order(PVALUES, NO_OF_ARRAY_ELEMENTS, false);//false is R's default
//p <- p[o]
double *restrict p = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (p == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
p[index] = PVALUES[o[index]];
}
//ro <- order(o)
double *restrict o2double = uint2double(o, NO_OF_ARRAY_ELEMENTS);
free(o); o = NULL;
unsigned int *restrict ro = order(o2double, NO_OF_ARRAY_ELEMENTS, false);
free(o2double); o2double = NULL;
// puts("ro");
//q <- pa <- rep.int(min(n * p/i), n)
double *restrict q = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (q == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
double *restrict pa = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (pa == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
double min = (double)NO_OF_ARRAY_ELEMENTS * p[0];
for (unsigned index = 1; index < NO_OF_ARRAY_ELEMENTS; index++) {
const double TEMP = (double)NO_OF_ARRAY_ELEMENTS * p[index] / (double)(1+index);
if (TEMP < min) {
min = TEMP;
}
}
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
pa[index] = min;
q[index] = min;
}
// puts("q & pa");
// double_say(q, NO_OF_ARRAY_ELEMENTS);
/*for (j in (n - 1):2) {
ij <- seq_len(n - j + 1)
i2 <- (n - j + 2):n
q1 <- min(j * p[i2]/(2:j))
q[ij] <- pmin(j * p[ij], q1)
q[i2] <- q[n - j + 1]
pa <- pmax(pa, q)
}
*/
for (unsigned j = (NO_OF_ARRAY_ELEMENTS-1); j >= 2; j--) {
// printf("j = %zu\n", j);
unsigned int *restrict ij = seq_len(0,NO_OF_ARRAY_ELEMENTS - j);
const size_t I2_LENGTH = j - 1;
unsigned int *restrict i2 = malloc(I2_LENGTH * sizeof(unsigned int));
for (unsigned i = 0; i < I2_LENGTH; i++) {
i2[i] = NO_OF_ARRAY_ELEMENTS-j+2+i-1;
//R's indices are 1-based, C's are 0-based, I added the -1
}
double q1 = (double)j * p[i2[0]] / 2.0;
for (unsigned int i = 1; i < I2_LENGTH; i++) {//loop through 2:j
const double TEMP_Q1 = (double)j * p[i2[i]] / (double)(2 + i);
if (TEMP_Q1 < q1) {
q1 = TEMP_Q1;
}
}
for (unsigned int i = 0; i < (NO_OF_ARRAY_ELEMENTS - j + 1); i++) {//q[ij] <- pmin(j * p[ij], q1)
q[ij[i]] = min2( (double)j*p[ij[i]], q1);
}
free(ij); ij = NULL;
for (unsigned int i = 0; i < I2_LENGTH; i++) {//q[i2] <- q[n - j + 1]
q[i2[i]] = q[NO_OF_ARRAY_ELEMENTS - j];//subtract 1 because of starting index difference
}
free(i2); i2 = NULL;
for (unsigned int i = 0; i < NO_OF_ARRAY_ELEMENTS; i++) {//pa <- pmax(pa, q)
if (pa[i] < q[i]) {
pa[i] = q[i];
}
}
// printf("j = %zu, pa = \n", j);
// double_say(pa, N);
}//end j loop
free(p); p = NULL;
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
q[index] = pa[ro[index]];//Hommel q-values
}
//now free memory
free(ro); ro = NULL;
free(pa); pa = NULL;
return q;
}
//The methods are similarly computed and thus can be combined for clarity
unsigned int *restrict o = order(PVALUES, NO_OF_ARRAY_ELEMENTS, true);
if (o == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
double *restrict o_double = uint2double(o, NO_OF_ARRAY_ELEMENTS);
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
if ((PVALUES[index] < 0) || (PVALUES[index] > 1)) {
printf("array[%u] = %lf, which is outside the interval [0,1]\n", index, PVALUES[index]);
printf("died at %s line %u\n", __FILE__, __LINE__);
exit(EXIT_FAILURE);
}
}
unsigned int *restrict ro = order(o_double, NO_OF_ARRAY_ELEMENTS, false);
if (ro == NULL) {
printf("failed to malloc at %s line %u.\n", __FILE__, __LINE__);
perror("");
exit(EXIT_FAILURE);
}
free(o_double); o_double = NULL;
double *restrict cummin_input = malloc(sizeof(double) * NO_OF_ARRAY_ELEMENTS);
if (TYPE == 0) {//BH method
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
const double NI = (double)NO_OF_ARRAY_ELEMENTS / (double)(NO_OF_ARRAY_ELEMENTS - index);// n/i simplified
cummin_input[index] = NI * PVALUES[o[index]];//PVALUES[o[index]] is p[o]
}
} else if (TYPE == 1) {//BY method
double q = 1.0;
for (unsigned int index = 2; index < (1+NO_OF_ARRAY_ELEMENTS); index++) {
q += 1.0/(double)index;
}
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
const double NI = (double)NO_OF_ARRAY_ELEMENTS / (double)(NO_OF_ARRAY_ELEMENTS - index);// n/i simplified
cummin_input[index] = q * NI * PVALUES[o[index]];//PVALUES[o[index]] is p[o]
}
} else if (TYPE == 3) {//Hochberg method
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
// pmin(1, cummin((n - i + 1L) * p[o]))[ro]
cummin_input[index] = (double)(index + 1) * PVALUES[o[index]];
}
}
free(o); o = NULL;
double *restrict cummin_array = NULL;
cummin_array = cummin(cummin_input, NO_OF_ARRAY_ELEMENTS);
free(cummin_input); cummin_input = NULL;//I don't need this anymore
double *restrict pmin = pminx(cummin_array, NO_OF_ARRAY_ELEMENTS, 1);
free(cummin_array); cummin_array = NULL;
double *restrict q_array = malloc(NO_OF_ARRAY_ELEMENTS*sizeof(double));
for (unsigned int index = 0; index < NO_OF_ARRAY_ELEMENTS; index++) {
q_array[index] = pmin[ro[index]];
}
free(ro); ro = NULL;
free(pmin); pmin = NULL;
return q_array;
}
int main(void) {
const double PVALUES[] = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03};//just the pvalues
const double CORRECT_ANSWERS[6][50] = {//each first index is type
{6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01,
9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01,
6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01,
9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01,
4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01,
2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01,
1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03,
2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03,
4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03,
2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02},//Benjamini-Hochberg
{1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01,
7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02,
1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02,
2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02,
1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02},//Benjamini & Yekutieli
{1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00,
2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02,
1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02,
9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02,
1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01},//Bonferroni
{9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01,
1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02,
1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02,
8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02,
1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01},//Hochberg
{1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00,
1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02,
1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02,
8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02,
1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01},//Holm
{ 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01,
1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02,
1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02,
8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02,
9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01}//Hommel
};
//the following loop checks each type with R's answers
const char *restrict TYPES[] = {"bh", "by", "bonferroni", "hochberg", "holm", "hommel"};
for (unsigned short int type = 0; type <= 5; type++) {
double *restrict q = p_adjust(PVALUES, sizeof(PVALUES) / sizeof(*PVALUES), TYPES[type]);
double error = fabs(q[0] - CORRECT_ANSWERS[type][0]);
// printf("%e - %e = %g\n", q[0], CORRECT_ANSWERS[type][0], error);
// puts("p q");
// printf("%g\t%g\n", pvalues[0], q[0]);
for (unsigned int i = 1; i < sizeof(PVALUES) / sizeof(*PVALUES); i++) {
const double this_error = fabs(q[i] - CORRECT_ANSWERS[type][i]);
// printf("%e - %e = %g\n", q[i], CORRECT_ANSWERS[type][i], error);
error += this_error;
}
double_say(q, sizeof(PVALUES) / sizeof(*PVALUES));
free(q); q = NULL;
printf("\ntype %u = '%s' has cumulative error of %g\n", type, TYPES[type], error);
}
return 0;
}
|
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #11l | 11l | F order_disjoint_list_items(&data, items)
[Int] itemindices
L(item) Set(items)
V itemcount = items.count(item)
V lastindex = [-1]
L(i) 0 .< itemcount
lastindex.append(data.index(item, lastindex.last + 1))
itemindices [+]= lastindex[1..]
itemindices.sort()
L(index, item) zip(itemindices, items)
data[index] = item
F slist(s)
R Array(s).map(String)
F tostring(l)
R ‘'’l.join(‘ ’)‘'’
L(data, items) [(‘the cat sat on the mat’.split(‘ ’), (‘mat cat’).split(‘ ’)),
(‘the cat sat on the mat’.split(‘ ’), (‘cat mat’).split(‘ ’)),
(slist(‘ABCABCABC’), slist(‘CACA’)),
(slist(‘ABCABDABE’), slist(‘EADA’)),
(slist(‘AB’), slist(‘B’)),
(slist(‘AB’), slist(‘BA’)),
(slist(‘ABBA’), slist(‘BA’)),
(slist(‘’), slist(‘’)),
(slist(‘A’), slist(‘A’)),
(slist(‘AB’), slist(‘’)),
(slist(‘ABBA’), slist(‘AB’)),
(slist(‘ABAB’), slist(‘AB’)),
(slist(‘ABAB’), slist(‘BABA’)),
(slist(‘ABCCBA’), slist(‘ACAC’)),
(slist(‘ABCCBA’), slist(‘CACA’))]
print(‘Data M: #<24 Order N: #<9’.format(tostring(data), tostring(items)), end' ‘ ’)
order_disjoint_list_items(&data, items)
print(‘-> M' #.’.format(tostring(data))) |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #AppleScript | AppleScript | on sortTable(x)
set {sortOrdering, sortColumn, sortReverse} to {sort_lexicographic, 1, false}
try
set sortOrdering to x's ordering
end try
try
set sortColumn to x's column
end try
try
set sortReverse to x's reverse
end try
return sortOrdering's sort(x's sequence, sortColumn, sortReverse)
end sortTable
script sort_lexicographic
on sort(table, column, reverse)
-- Implement lexicographic Sorting process here.
return table
end sort
end script |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
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
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #ALGOL_68 | ALGOL 68 | BEGIN # compare lists (rows) of integers #
# returns TRUE if there is an element in a that is < the corresponding #
# element in b and all previous elements are equal; FALSE otherwise #
OP < = ( []INT a, b )BOOL:
IF INT a pos := LWB a;
INT b pos := LWB b;
BOOL equal := TRUE;
WHILE a pos <= UPB a AND b pos <= UPB b AND equal DO
equal := a[ a pos ] = b[ b pos ];
IF equal THEN
a pos +:= 1;
b pos +:= 1
FI
OD;
NOT equal
THEN
# there is an element in a and b that is not equal #
a[ a pos ] < b[ b pos ]
ELSE
# all elements are equal or one list is shorter #
# a is < b if a has fewer elements #
a pos > UPB a AND b pos <= UPB b
FI # < # ;
# tests a < b has the expected result #
PROC test = ( STRING a name, []INT a, STRING b name, []INT b, BOOL expected )VOID:
BEGIN
BOOL result = a < b;
print( ( a name, IF result THEN " < " ELSE " >= " FI, b name
, IF result = expected THEN "" ELSE ", NOT as expected" FI
, newline
)
)
END # test # ;
# test cases as in the BBC basic sample #
[]INT list1 = ( 1, 2, 1, 5, 2 );
[]INT list2 = ( 1, 2, 1, 5, 2, 2 );
[]INT list3 = ( 1, 2, 3, 4, 5 );
[]INT list4 = ( 1, 2, 3, 4, 5 );
test( "list1", list1, "list2", list2, TRUE );
test( "list2", list2, "list3", list3, TRUE );
test( "list3", list3, "list4", list4, FALSE );
# additional test cases #
[]INT list5 = ( 9, 0, 2, 1, 0 );
[]INT list6 = ( 4, 0, 7, 7 );
[]INT list7 = ( 4, 0, 7 );
[]INT list8 = ( );
test( "list5", list5, "list6", list6, FALSE );
test( "list6", list6, "list7", list7, FALSE );
test( "list7", list7, "list8", list8, FALSE );
test( "list8", list8, "list7", list7, TRUE )
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
| #Rust | Rust |
fn pascal_triangle(n: u64)
{
for i in 0..n {
let mut c = 1;
for _j in 1..2*(n-1-i)+1 {
print!(" ");
}
for k in 0..i+1 {
print!("{:2} ", c);
c = c * (i-k)/(k+1);
}
println!();
}
}
|
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[HumanOrderCheck]
HumanOrderCheck[opt1_,opt2_]:=ChoiceDialog[Row@{"Is {",opt1,", ", opt2, "} ordered?"},{"Yes"->True,"No"->False}]
Sort[{"violet","red","green","indigo","blue","yellow","orange"},HumanOrderCheck] |
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.
| #Nim | Nim | import algorithm, strformat, strutils
let list = ["violet", "red", "green", "indigo", "blue", "yellow", "orange"]
var count = 0
proc comp(x, y: string): int =
if x == y: return 0
inc count
while true:
stdout.write &"{count:>2}) Is {x} less than {y} (y/n)? "
let answer = stdin.readLine()[0]
case answer
of 'y': return -1
of 'n': return 1
else: echo "Incorrect answer."
var sortedList: seq[string]
for elem in list:
sortedList.insert(elem, sortedList.upperBound(elem, comp))
echo "Sorted list: ", sortedList.join(", ") |
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.
| #OCaml | OCaml | let () =
let count = ref 0 in
let mycmp s1 s2 = (
incr count;
Printf.printf "(%d) Is %s <, ==, or > %s? Answer -1, 0, or 1: " (!count) s1 s2;
read_int ()
) in
let items = ["violet"; "red"; "green"; "indigo"; "blue"; "yellow"; "orange"] in
let sorted = List.sort mycmp items in
List.iter (Printf.printf "%s ") sorted;
print_newline () |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #ALGOL_W | ALGOL W | print 2 + 3 * 5 ; same as 2 + (3 * 5)
print 3 * 5 + 2 ; same as 3 * (5 + 2) |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #AppleScript | AppleScript | print 2 + 3 * 5 ; same as 2 + (3 * 5)
print 3 * 5 + 2 ; same as 3 * (5 + 2) |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #Arturo | Arturo | print 2 + 3 * 5 ; same as 2 + (3 * 5)
print 3 * 5 + 2 ; same as 3 * (5 + 2) |
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
| #C.2B.2B | C++ | #include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
bool ordered(const std::string &word)
{
return std::is_sorted(word.begin(), word.end()); // C++11
}
int main()
{
std::ifstream infile("unixdict.txt");
if (!infile) {
std::cerr << "Can't open word file\n";
return -1;
}
std::vector<std::string> words;
std::string word;
int longest = 0;
while (std::getline(infile, word)) {
int length = word.length();
if (length < longest) continue; // don't test short words
if (ordered(word)) {
if (longest < length) {
longest = length; // set new minimum length
words.clear(); // reset the container
}
words.push_back(word);
}
}
std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\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
| #MiniScript | MiniScript | isPalindrome = function(s)
// convert to lowercase, and strip non-letters
stripped = ""
for c in s.lower
if c >= "a" and c <= "z" then stripped = stripped + c
end for
// check palindromity
mid = floor(stripped.len/2)
for i in range(0, mid)
if stripped[i] != stripped[-i - 1] then return false
end for
return true
end function
testStr = "Madam, I'm Adam"
answer = [testStr, "is"]
if not isPalindrome(testStr) then answer.push "NOT"
answer.push "a palindrome"
print answer.join |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q-values".
Task
Given one list of p-values, return the p-values correcting for multiple comparisons
p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}
There are several methods to do this, see:
Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101
Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075
Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733
Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325
Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190
Each method has its own advantages and disadvantages.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace PValueCorrection {
class Program {
static List<int> SeqLen(int start, int end) {
var result = new List<int>();
if (start == end) {
for (int i = 0; i < end + 1; ++i) {
result.Add(i + 1);
}
} else if (start < end) {
for (int i = 0; i < end - start + 1; ++i) {
result.Add(start + i);
}
} else {
for (int i = 0; i < start - end + 1; ++i) {
result.Add(start - i);
}
}
return result;
}
static List<int> Order(List<double> array, bool decreasing) {
List<int> idx = new List<int>();
for (int i = 0; i < array.Count; ++i) {
idx.Add(i);
}
IComparer<int> cmp;
if (decreasing) {
cmp = Comparer<int>.Create((a, b) => array[a] < array[b] ? 1 : array[b] < array[a] ? -1 : 0);
} else {
cmp = Comparer<int>.Create((a, b) => array[b] < array[a] ? 1 : array[a] < array[b] ? -1 : 0);
}
idx.Sort(cmp);
return idx;
}
static List<double> Cummin(List<double> array) {
if (array.Count < 1) throw new ArgumentOutOfRangeException("cummin requires at least one element");
var output = new List<double>();
double cumulativeMin = array[0];
for (int i = 0; i < array.Count; ++i) {
if (array[i] < cumulativeMin) cumulativeMin = array[i];
output.Add(cumulativeMin);
}
return output;
}
static List<double> Cummax(List<double> array) {
if (array.Count < 1) throw new ArgumentOutOfRangeException("cummax requires at least one element");
var output = new List<double>();
double cumulativeMax = array[0];
for (int i = 0; i < array.Count; ++i) {
if (array[i] > cumulativeMax) cumulativeMax = array[i];
output.Add(cumulativeMax);
}
return output;
}
static List<double> Pminx(List<double> array, double x) {
if (array.Count < 1) throw new ArgumentOutOfRangeException("pmin requires at least one element");
var result = new List<double>();
for (int i = 0; i < array.Count; ++i) {
if (array[i] < x) {
result.Add(array[i]);
} else {
result.Add(x);
}
}
return result;
}
static void Say(List<double> array) {
Console.Write("[ 1] {0:E}", array[0]);
for (int i = 1; i < array.Count; ++i) {
Console.Write(" {0:E}", array[i]);
if ((i + 1) % 5 == 0) Console.Write("\n[{0,2}]", i + 1);
}
Console.WriteLine();
}
static List<double> PAdjust(List<double> pvalues, string str) {
var size = pvalues.Count;
if (size < 1) throw new ArgumentOutOfRangeException("pAdjust requires at least one element");
int type;
switch (str.ToLower()) {
case "bh":
case "fdr":
type = 0;
break;
case "by":
type = 1;
break;
case "bonferroni":
type = 2;
break;
case "hochberg":
type = 3;
break;
case "holm":
type = 4;
break;
case "hommel":
type = 5;
break;
default:
throw new ArgumentException(str + " doesn't match any accepted FDR types");
}
if (2 == type) { // Bonferroni method
var result2 = new List<double>();
for (int i = 0; i < size; ++i) {
double b = pvalues[i] * size;
if (b >= 1) {
result2.Add(1);
} else if (0 <= b && b < 1) {
result2.Add(b);
} else {
throw new Exception(b + " is outside [0, 1)");
}
}
return result2;
} else if (4 == type) { // Holm method
var o4 = Order(pvalues, false);
var o4d = o4.ConvertAll(x => (double)x);
var cummaxInput = new List<double>();
for (int i = 0; i < size; ++i) {
cummaxInput.Add((size - i) * pvalues[o4[i]]);
}
var ro4 = Order(o4d, false);
var cummaxOutput = Cummax(cummaxInput);
var pmin4 = Pminx(cummaxOutput, 1.0);
var hr = new List<double>();
for (int i = 0; i < size; ++i) {
hr.Add(pmin4[ro4[i]]);
}
return hr;
} else if (5 == type) { // Hommel method
var indices = SeqLen(size, size);
var o5 = Order(pvalues, false);
var p = new List<double>();
for (int i = 0; i < size; ++i) {
p.Add(pvalues[o5[i]]);
}
var o5d = o5.ConvertAll(x => (double)x);
var ro5 = Order(o5d, false);
var q = new List<double>();
var pa = new List<double>();
var npi = new List<double>();
for (int i = 0; i < size; ++i) {
npi.Add(p[i] * size / indices[i]);
}
double min = npi.Min();
q.AddRange(Enumerable.Repeat(min, size));
pa.AddRange(Enumerable.Repeat(min, size));
for (int j = size; j >= 2; --j) {
var ij = SeqLen(1, size - j + 1);
for (int i = 0; i < size - j + 1; ++i) {
ij[i]--;
}
int i2Length = j - 1;
var i2 = new List<int>();
for (int i = 0; i < i2Length; ++i) {
i2.Add(size - j + 2 + i - 1);
}
double q1 = j * p[i2[0]] / 2.0;
for (int i = 1; i < i2Length; ++i) {
double temp_q1 = p[i2[i]] * j / (2.0 + i);
if (temp_q1 < q1) q1 = temp_q1;
}
for (int i = 0; i < size - j + 1; ++i) {
q[ij[i]] = Math.Min(p[ij[i]] * j, q1);
}
for (int i = 0; i < i2Length; ++i) {
q[i2[i]] = q[size - j];
}
for (int i = 0; i < size; ++i) {
if (pa[i] < q[i]) {
pa[i] = q[i];
}
}
}
for (int i = 0; i < size; ++i) {
q[i] = pa[ro5[i]];
}
return q;
}
var ni = new List<double>();
var o = Order(pvalues, true);
var od = o.ConvertAll(x => (double)x);
for (int i = 0; i < size; ++i) {
if (pvalues[i] < 0 || pvalues[i] > 1) {
throw new Exception("array[" + i + "] = " + pvalues[i] + " is outside [0, 1]");
}
ni.Add((double)size / (size - i));
}
var ro = Order(od, false);
var cumminInput = new List<double>();
if (0 == type) { // BH method
for (int i = 0; i < size; ++i) {
cumminInput.Add(ni[i] * pvalues[o[i]]);
}
} else if (1 == type) { // BY method
double q = 0;
for (int i = 1; i < size + 1; ++i) {
q += 1.0 / i;
}
for (int i = 0; i < size; ++i) {
cumminInput.Add(q * ni[i] * pvalues[o[i]]);
}
} else if (3 == type) { // Hochberg method
for (int i = 0; i < size; ++i) {
cumminInput.Add((i + 1) * pvalues[o[i]]);
}
}
var cumminArray = Cummin(cumminInput);
var pmin = Pminx(cumminArray, 1.0);
var result = new List<double>();
for (int i = 0; i < size; ++i) {
result.Add(pmin[ro[i]]);
}
return result;
}
static void Main(string[] args) {
var pvalues = new List<double> {
4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03
};
var correctAnswers = new List<List<double>> {
new List<double> { // Benjamini-Hochberg
6.126681e-01, 8.521710e-01, 1.987205e-01, 1.891595e-01, 3.217789e-01,
9.301450e-01, 4.870370e-01, 9.301450e-01, 6.049731e-01, 6.826753e-01,
6.482629e-01, 7.253722e-01, 5.280973e-01, 8.769926e-01, 4.705703e-01,
9.241867e-01, 6.049731e-01, 7.856107e-01, 4.887526e-01, 1.136717e-01,
4.991891e-01, 8.769926e-01, 9.991834e-01, 3.217789e-01, 9.301450e-01,
2.304958e-01, 5.832475e-01, 3.899547e-02, 8.521710e-01, 1.476843e-01,
1.683638e-02, 2.562902e-03, 3.516084e-02, 6.250189e-02, 3.636589e-03,
2.562902e-03, 2.946883e-02, 6.166064e-03, 3.899547e-02, 2.688991e-03,
4.502862e-04, 1.252228e-05, 7.881555e-02, 3.142613e-02, 4.846527e-03,
2.562902e-03, 4.846527e-03, 1.101708e-03, 7.252032e-02, 2.205958e-02
},
new List<double> { // Benjamini & Yekutieli
1.000000e+00, 1.000000e+00, 8.940844e-01, 8.510676e-01, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 5.114323e-01,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.754486e-01, 1.000000e+00, 6.644618e-01,
7.575031e-02, 1.153102e-02, 1.581959e-01, 2.812089e-01, 1.636176e-02,
1.153102e-02, 1.325863e-01, 2.774239e-02, 1.754486e-01, 1.209832e-02,
2.025930e-03, 5.634031e-05, 3.546073e-01, 1.413926e-01, 2.180552e-02,
1.153102e-02, 2.180552e-02, 4.956812e-03, 3.262838e-01, 9.925057e-02
},
new List<double> { // Bonferroni
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 7.019185e-01, 1.000000e+00, 1.000000e+00,
2.020365e-01, 1.516674e-02, 5.625735e-01, 1.000000e+00, 2.909271e-02,
1.537741e-02, 4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02,
9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01, 4.395577e-02,
1.088915e-02, 4.846527e-02, 3.305125e-03, 1.000000e+00, 2.867745e-01
},
new List<double> { // Hochberg
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 4.632662e-01, 9.991834e-01, 9.991834e-01,
1.575885e-01, 1.383967e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02,
1.383967e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02,
8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02,
1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01
},
new List<double> { // Holm
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 4.632662e-01, 1.000000e+00, 1.000000e+00,
1.575885e-01, 1.395341e-02, 3.938014e-01, 7.600230e-01, 2.501973e-02,
1.395341e-02, 3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02,
8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01, 3.692284e-02,
1.023581e-02, 3.974152e-02, 3.172920e-03, 8.992520e-01, 2.179486e-01
},
new List<double> { // Hommel
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 4.351895e-01, 9.991834e-01, 9.766522e-01,
1.414256e-01, 1.304340e-02, 3.530937e-01, 6.887709e-01, 2.385602e-02,
1.322457e-02, 2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02,
8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01, 3.516461e-02,
9.582456e-03, 3.877222e-02, 3.172920e-03, 8.122276e-01, 1.950067e-01
}
};
string[] types = { "bh", "by", "bonferroni", "hochberg", "holm", "hommel" };
for (int type = 0; type < types.Length; ++type) {
var q = PAdjust(pvalues, types[type]);
double error = 0.0;
for (int i = 0; i < pvalues.Count; ++i) {
error += Math.Abs(q[i] - correctAnswers[type][i]);
}
Say(q);
Console.WriteLine("type {0} = '{1}' has a cumulative error of {2:E}", type, types[type], error);
Console.WriteLine();
}
}
}
} |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #Aime | Aime | order(list a, b)
{
integer j;
record r;
text s;
a.ucall(o_, 0, " ");
o_("| ");
for (, s in b) {
r[s] += 1;
o_(s, " ");
}
o_("->");
j = -1;
for (, s in a) {
if ((r[s] -= 1) < 0) {
o_(" ", s);
} else {
o_(" ", b[j += 1]);
}
}
o_newline();
}
main(void)
{
order(list("the", "cat", "sat", "on", "the", "mat"), list("mat", "cat"));
order(list("the", "cat", "sat", "on", "the", "mat"), list("cat", "mat"));
order(list("A", "B", "C", "A", "B", "C", "A", "B", "C"), list("C", "A", "C", "A"));
order(list("A", "B", "C", "A", "B", "D", "A", "B", "E"), list("E", "A", "D", "A"));
order(list("A", "B"), list("B"));
order(list("A", "B"), list("B", "A"));
order(list("A", "B", "B", "A"), list("B", "A"));
0;
} |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
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
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #AppleScript | AppleScript | ---------------------- DISJOINT ORDER --------------------
-- disjointOrder :: String -> String -> String
on disjointOrder(m, n)
set {ms, ns} to map(my |words|, {m, n})
unwords(flatten(zip(segments(ms, ns), ns & "")))
end disjointOrder
-- segments :: [String] -> [String] -> [String]
on segments(ms, ns)
script segmentation
on |λ|(a, x)
set wds to |words| of a
if wds contains x then
{parts:(parts of a) & ¬
[current of a], current:[], |words|:deleteFirst(x, wds)} ¬
else
{parts:(parts of a), current:(current of a) & x, |words|:wds}
end if
end |λ|
end script
tell foldl(segmentation, {|words|:ns, parts:[], current:[]}, ms)
(parts of it) & [current of it]
end tell
end segments
--------------------------- TEST -------------------------
on run
script order
on |λ|(rec)
tell rec
[its m, its n, my disjointOrder(its m, its n)]
end tell
end |λ|
end script
arrowTable(map(order, [¬
{m:"the cat sat on the mat", n:"mat cat"}, ¬
{m:"the cat sat on the mat", n:"cat mat"}, ¬
{m:"A B C A B C A B C", n:"C A C A"}, ¬
{m:"A B C A B D A B E", n:"E A D A"}, ¬
{m:"A B", n:"B"}, {m:"A B", n:"B A"}, ¬
{m:"A B B A", n:"B A"}]))
-- the cat sat on the mat -> mat cat -> the mat sat on the cat
-- the cat sat on the mat -> cat mat -> the cat sat on the mat
-- A B C A B C A B C -> C A C A -> C B A C B A A B C
-- A B C A B D A B E -> E A D A -> E B C A B D A B A
-- A B -> B -> A B
-- A B -> B A -> B A
-- A B B A -> B A -> B A B A
end run
------------------------ FORMATTING ----------------------
-- arrowTable :: [[String]] -> String
on arrowTable(rows)
script leftAligned
script width
on |λ|(a, b)
(length of a) - (length of b)
end |λ|
end script
on |λ|(col)
set widest to length of maximumBy(width, col)
script padding
on |λ|(s)
justifyLeft(widest, space, s)
end |λ|
end script
map(padding, col)
end |λ|
end script
script arrows
on |λ|(row)
intercalate(" -> ", row)
end |λ|
end script
intercalate(linefeed, ¬
map(arrows, ¬
transpose(map(leftAligned, transpose(rows)))))
end arrowTable
-------------------- GENERIC FUNCTIONS -------------------
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
script append
on |λ|(a, b)
a & b
end |λ|
end script
foldl(append, {}, map(f, xs))
end concatMap
-- deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
on deleteBy(fnEq, x, xs)
if length of xs > 0 then
set {h, t} to uncons(xs)
if |λ|(x, h) of mReturn(fnEq) then
t
else
{h} & deleteBy(fnEq, x, t)
end if
else
{}
end if
end deleteBy
-- deleteFirst :: a -> [a] -> [a]
on deleteFirst(x, xs)
script Eq
on |λ|(a, b)
a = b
end |λ|
end script
deleteBy(Eq, x, xs)
end deleteFirst
-- flatten :: Tree a -> [a]
on flatten(t)
if class of t is list then
concatMap(my flatten, t)
else
t
end if
end flatten
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- justifyLeft :: Int -> Char -> Text -> Text
on justifyLeft(n, cFiller, strText)
if n > length of strText then
text 1 thru n of (strText & replicate(n, cFiller))
else
strText
end if
end justifyLeft
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- maximumBy :: (a -> a -> Ordering) -> [a] -> a
on maximumBy(f, xs)
set cmp to mReturn(f)
script max
on |λ|(a, b)
if a is missing value or cmp's |λ|(a, b) < 0 then
b
else
a
end if
end |λ|
end script
foldl(max, missing value, xs)
end maximumBy
-- minimum :: [a] -> a
on minimum(xs)
script min
on |λ|(a, x)
if x < a or a is missing value then
x
else
a
end if
end |λ|
end script
foldl(min, missing value, xs)
end minimum
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- transpose :: [[a]] -> [[a]]
on transpose(xss)
script column
on |λ|(_, iCol)
script row
on |λ|(xs)
item iCol of xs
end |λ|
end script
map(row, xss)
end |λ|
end script
map(column, item 1 of xss)
end transpose
-- uncons :: [a] -> Maybe (a, [a])
on uncons(xs)
if length of xs > 0 then
{item 1 of xs, rest of xs}
else
missing value
end if
end uncons
-- unwords :: [String] -> String
on unwords(xs)
intercalate(space, xs)
end unwords
-- words :: String -> [String]
on |words|(s)
words of s
end |words|
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
script pair
on |λ|(x, i)
[x, item i of ys]
end |λ|
end script
map(pair, items 1 thru minimum([length of xs, length of ys]) of xs)
end zip |
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.