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/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #AutoHotkey | AutoHotkey | str := "what,is,the;meaning,of:life."
loop, parse, str
if (A_LoopField ~= "[[:punct:]]")
res .= A_LoopField, toggle:=!toggle
else
res := toggle ? RegExReplace(res, ".*[[:punct:]]\K", A_LoopField ) : res A_LoopField
MsgBox % res |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #BaCon | BaCon | OPEN "/dev/stdin" FOR DEVICE AS in
FUNCTION get_odd()
LOCAL ch, letter
ch = MEMORY(1)
GETBYTE ch FROM in
IF NOT(REGEX(CHR$(PEEK(ch)), "[[:punct:]]")) THEN
letter = get_odd()
PRINT CHR$(PEEK(ch));
ELSE
letter = PEEK(ch)
END IF
FREE ch
RETURN letter
END FUNCTION
mem = MEMORY(1)
PRINT "Enter string: ";
WHILE TRUE
GETBYTE mem FROM in
PRINT CHR$(PEEK(mem));
IF REGEX(CHR$(PEEK(mem)), "[[:punct:]]") THEN
IF PEEK(mem) <> 46 THEN
POKE mem, get_odd()
PRINT CHR$(PEEK(mem));
END IF
IF PEEK(mem) = 46 THEN BREAK
END IF
WEND
FREE mem
CLOSE DEVICE in
PRINT |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Cellular_Automata is
type Petri_Dish is array (Positive range <>) of Boolean;
procedure Step (Culture : in out Petri_Dish) is
Left : Boolean := False;
This : Boolean;
Right : Boolean;
begin
for Index in Culture'First..Culture'Last - 1 loop
Right := Culture (Index + 1);
This := Culture (Index);
Culture (Index) := (This and (Left xor Right)) or (not This and Left and Right);
Left := This;
end loop;
Culture (Culture'Last) := Culture (Culture'Last) and not Left;
end Step;
procedure Put (Culture : Petri_Dish) is
begin
for Index in Culture'Range loop
if Culture (Index) then
Put ('#');
else
Put ('_');
end if;
end loop;
end Put;
Culture : Petri_Dish :=
( False, True, True, True, False, True, True, False, True, False, True,
False, True, False, True, False, False, True, False, False
);
begin
for Generation in 0..9 loop
Put ("Generation" & Integer'Image (Generation) & ' ');
Put (Culture);
New_Line;
Step (Culture);
end loop;
end Cellular_Automata; |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Axiom | Axiom | NNI ==> NonNegativeInteger
RECORD ==> Record(x : List Fraction Integer, w : List Fraction Integer)
gaussCoefficients(n : NNI, eps : Fraction Integer) : RECORD ==
p := legendreP(n,z)
q := n/2*D(p, z)*legendreP(subtractIfCan(n,1)::NNI, z)
x := map(rhs,solve(p,eps))
w := [subst(1/q, z=xi) for xi in x]
[x,w]
gaussIntegrate(e : Expression Float, segbind : SegmentBinding(Float), n : NNI) : Float ==
eps := 1/10^100
u := gaussCoefficients(n,eps)
interval := segment segbind
var := variable segbind
a := lo interval
b := hi interval
c := (a+b)/2
h := (b-a)/2
h*reduce(+,[wi*subst(e,var=c+xi*h) for xi in u.x for wi in u.w]) |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #C.2B.2B | C++ | #include <string>
#include <fstream>
#include <boost/serialization/string.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <iostream>
class Employee {
public :
Employee( ) { }
Employee ( const std::string &dep , const std::string &namen )
: department( dep ) , name( namen ) {
my_id = count++ ;
}
std::string getName( ) const {
return name ;
}
std::string getDepartment( ) const {
return department ;
}
int getId( ) const {
return my_id ;
}
void setDepartment( const std::string &dep ) {
department.assign( dep ) ;
}
virtual void print( ) {
std::cout << "Name: " << name << '\n' ;
std::cout << "Id: " << my_id << '\n' ;
std::cout << "Department: " << department << '\n' ;
}
virtual ~Employee( ) { }
static int count ;
private :
std::string name ;
std::string department ;
int my_id ;
friend class boost::serialization::access ;
template <class Archive>
void serialize( Archive &ar, const unsigned int version ) {
ar & my_id ;
ar & name ;
ar & department ;
}
} ;
class Worker : public Employee {
public :
Worker( const std::string & dep, const std::string &namen ,
double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }
Worker( ) { }
double getSalary( ) {
return salary ;
}
void setSalary( double pay ) {
if ( pay > 0 )
salary = pay ;
}
virtual void print( ) {
Employee::print( ) ;
std::cout << "wage per hour: " << salary << '\n' ;
}
private :
double salary ;
friend class boost::serialization::access ;
template <class Archive>
void serialize ( Archive & ar, const unsigned int version ) {
ar & boost::serialization::base_object<Employee>( *this ) ;
ar & salary ;
}
} ;
int Employee::count = 0 ;
int main( ) {
std::ofstream storefile( "/home/ulrich/objects.dat" ) ; //creating objects of base class
const Employee emp1( "maintenance" , "Fritz Schmalstieg" ) ;
const Employee emp2( "maintenance" , "John Berry" ) ;
const Employee emp3( "repair" , "Pawel Lichatschow" ) ;
const Employee emp4( "IT" , "Marian Niculescu" ) ;
const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ;//creating objects of derived class
const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ;
boost::archive::text_oarchive oar ( storefile ) ;//starting serialization into designated file
oar << emp1 ;
oar << emp2 ;
oar << emp3 ;
oar << emp4 ;
oar << worker1 ;
oar << worker2 ;
storefile.close( ) ;
std::cout << "Reading out the data again\n" ;
Employee e1 , e2 , e3 , e4 ; //creating instances of base class objects for deserialization
Worker w1, w2 ; // same for objects of derived class
std::ifstream sourcefile( "/home/ulrich/objects.dat" ) ;
boost::archive::text_iarchive iar( sourcefile ) ;//starting deserialization
iar >> e1 >> e2 >> e3 >> e4 ;
iar >> w1 >> w2 ;
sourcefile.close( ) ;
std::cout << "And here are the data after deserialization!( abridged):\n" ;
e1.print( ) ;
e3.print( ) ;
w2.print( ) ;
return 0 ;
} |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #APL | APL | oldLady←{
N←⎕TC[3]
a←'fly' 'spider' 'bird' 'cat' 'dog' 'goat' 'cow' 'horse'
v←⊂'I don''t know why she swallowed that fly - Perhaps she''ll die',N
v←v,⊂'That wiggled and jiggled and tickled inside her!'
v←v,⊂'How absurd to swallow a bird'
v←v,⊂'Imagine that! She swallowed a cat!'
v←v,⊂'What a hog to swallow a dog'
v←v,⊂'She just opened her throat and swallowed that goat'
v←v,⊂'I don''t know how she swallowed that cow'
v←v,⊂'She''s dead, of course.'
l←'There was an old lady who swallowed a '
∊{
∊l,a[⍵],N,v[⍵],N,(⍵<8)/{
⍵=0:''
r←'She swallowed the ',a[⍵],' to catch the ',a[⍵-1],N
r,(⍵≤3)/v[⍵-1],N
}¨⌽1↓⍳⍵
}¨⍳8
} |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #ARM_Assembly | ARM Assembly | .global _start
_start: eor r8,r8,r8 @ Verse counter
verse: add r8,r8,#1 @ Next verse
ldr r1,=lady @ There was an old lady who swallowed...
bl pstr
mov r2,r8
bl pbeast @ <an animal>
ldr r1,=comma
bl pstr
mov r2,r8
bl pverse @ Print the corresponding verse
cmp r8,#1 @ First verse?
beq verse @ Then we're not swallowing anything yet
cmp r8,#8 @ Otherwise, is the lady dead yet?
moveq r7,#1 @ If so, stop.
swieq #0
mov r9,r8 @ Otherwise, start swallowing
swallo: ldr r1,=swa1 @ She swallowed the ...
bl pstr
mov r2,r9 @ <current animal>
bl pbeast
ldr r1,=swa2 @ ...to catch the...
bl pstr
sub r9,r9,#1
mov r2,r9 @ <previous animal>
bl pbeast
ldr r1,=comma
bl pstr
cmp r9,#2 @ Print the associated verse for 2 and 1
movle r2,r9
blle pverse
cmp r9,#1 @ Last animal?
bgt swallo @ If not, keep swallowing
b verse @ But if so, next verse
pverse: ldr r1,=verses @ Print verse R2
b pstrn
pbeast: ldr r1,=beasts @ Print animal R2
pstrn: ldrb r0,[r1],#1 @ R2'th string from R1 - get byte
tst r0,r0 @ Zero yet?
bne pstrn @ If not keep going
subs r2,r2,#1 @ Is this the right string?
bne pstrn @ If not keep going
@ Print 0-terminated string starting at R1 using Linux.
pstr: mov r2,r1 @ Find end
1: ldrb r0,[r2],#1 @ Get current byte
tst r0,r0 @ Zero yet?
bne 1b @ If not keep scanning
sub r2,r2,r1 @ Calculate string length
mov r0,#1 @ 1 = Linux stdout
mov r7,#4 @ 4 = Linux write syscall
push {lr} @ Keep link register
swi #0 @ Do syscall
pop {lr} @ Restore link register
bx lr
lady: .ascii "There was an old lady who swallowed a "
beasts: .ascii "\0fly\0spider\0bird\0cat\0dog\0goat\0cow\0horse"
verses: .ascii "\0I don't know why she swallowed that fly - "
.ascii "Perhaps she'll die.\n\n"
.ascii "\0That wiggled and jiggled and tickled inside her!\n"
.ascii "\0How absurd to swallow a bird\n"
.ascii "\0Imagine that! She swallowed a cat!\n"
.ascii "\0What a hog to swallow a dog\n"
.ascii "\0She just opened her throat and swallowed that goat\n"
.ascii "\0I don't know how she swallowed that cow\n"
.asciz "\0She's dead, of course.\n"
swa1: .asciz "She swallowed the "
swa2: .asciz " to catch the "
comma: .asciz ",\n" |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
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
| #Python | Python |
from functools import reduce
from operator import mul
from decimal import *
getcontext().prec = MAX_PREC
def expand(num):
suffixes = [
# (name, min_abbreviation_length, base, exponent)
('greatgross', 7, 12, 3),
('gross', 2, 12, 2),
('dozens', 3, 12, 1),
('pairs', 4, 2, 1),
('scores', 3, 20, 1),
('googols', 6, 10, 100),
('ki', 2, 2, 10),
('mi', 2, 2, 20),
('gi', 2, 2, 30),
('ti', 2, 2, 40),
('pi', 2, 2, 50),
('ei', 2, 2, 60),
('zi', 2, 2, 70),
('yi', 2, 2, 80),
('xi', 2, 2, 90),
('wi', 2, 2, 100),
('vi', 2, 2, 110),
('ui', 2, 2, 120),
('k', 1, 10, 3),
('m', 1, 10, 6),
('g', 1, 10, 9),
('t', 1, 10, 12),
('p', 1, 10, 15),
('e', 1, 10, 18),
('z', 1, 10, 21),
('y', 1, 10, 24),
('x', 1, 10, 27),
('w', 1, 10, 30)
]
num = num.replace(',', '').strip().lower()
if num[-1].isdigit():
return float(num)
for i, char in enumerate(reversed(num)):
if char.isdigit():
input_suffix = num[-i:]
num = Decimal(num[:-i])
break
if input_suffix[0] == '!':
return reduce(mul, range(int(num), 0, -len(input_suffix)))
while len(input_suffix) > 0:
for suffix, min_abbrev, base, power in suffixes:
if input_suffix[:min_abbrev] == suffix[:min_abbrev]:
for i in range(min_abbrev, len(input_suffix) + 1):
if input_suffix[:i+1] != suffix[:i+1]:
num *= base ** power
input_suffix = input_suffix[i:]
break
break
return num
test = "2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre\n\
1,567 +1.567k 0.1567e-2m\n\
25.123kK 25.123m 2.5123e-00002G\n\
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei\n\
-.25123e-34Vikki 2e-77gooGols\n\
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!"
for test_line in test.split("\n"):
test_cases = test_line.split()
print("Input:", ' '.join(test_cases))
print("Output:", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))
|
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Fortran | Fortran | PROGRAM RUS
IMPLICIT NONE
REAL, PARAMETER:: E_m = 1.
REAL, PARAMETER:: E_mm = 1.E-3
REAL, PARAMETER:: E_km = 1.E+3
REAL, PARAMETER:: E_cm = 1.E-2
REAL, PARAMETER:: E_arshin = 71.12 * E_cm
REAL, PARAMETER:: E_fut = 3./7. * E_arshin
REAL, PARAMETER:: E_piad = 1./4. * E_arshin
REAL, PARAMETER:: E_vershok = 1./16. * E_arshin
REAL, PARAMETER:: E_dyuim = 1./28. * E_arshin
REAL, PARAMETER:: E_liniya = 1./280. * E_arshin
REAL, PARAMETER:: E_tochka = 1./2800. * E_arshin
REAL, PARAMETER:: E_ladon = 7.5 * E_cm
REAL, PARAMETER:: E_lokot = 45 * E_cm
REAL, PARAMETER:: E_sazhen = 3. * E_arshin
REAL, PARAMETER:: E_versta = 1500. * E_arshin
REAL, PARAMETER:: E_milya = 10500. * E_arshin
INTEGER, PARAMETER:: N = 16
CHARACTER(LEN=7), DIMENSION(N):: nam = (/&
&'m ', 'mm ', 'km ', 'cm ',&
&'arshin ', 'fut ', 'piad ', 'vershok',&
&'dyuim ', 'liniya ', 'tochka ', 'ladon ',&
&'lokot ', 'sazhen ', 'versta ', 'milya ' /)
REAL, DIMENSION(N):: wert = (/ &
&1., E_mm, E_km, E_cm,&
&E_arshin, E_fut, E_piad, E_vershok,&
&E_dyuim, E_liniya, E_tochka, E_ladon,&
&E_lokot, E_sazhen, E_versta, E_milya /)
CHARACTER(LEN=7):: RD_U
REAL:: RD_V
INTEGER:: I, J
DO I=1, N
WRITE(*, '(A, " ")', ADVANCE='NO') nam(I)
END DO
WRITE (*, *)
WRITE(*, '(A)', ADVANCE='NO') 'value unit -> '
READ(*, *) RD_V, RD_U
RD_U = ADJUSTL(RD_U)
J = 1
DO WHILE (NAM(J) .NE. RD_U)
J = J + 1
IF (J .GT. N) STOP "Unit not known: "//RD_U
END DO
RD_V = RD_V * wert(J)
DO I=1, N
J = J + 1
IF (J .GT. N) J = 1
WRITE (*, '(F20.3, " ", A)') RD_V / wert(J), nam(J)
END DO
END PROGRAM RUS |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Go | Go | package main
import (
gl "github.com/chsc/gogl/gl21"
"github.com/go-gl/glfw/v3.2/glfw"
"log"
"runtime"
)
// Window dimensions.
const (
Width = 640
Height = 480
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
// OpenGL requires a dedicated OS thread.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
err := glfw.Init()
check(err)
defer glfw.Terminate()
// Open window with the specified dimensions.
window, err := glfw.CreateWindow(Width, Height, "Triangle", nil, nil)
check(err)
window.MakeContextCurrent()
err = gl.Init()
check(err) /* may need to comment out this line for this program to work on Windows 10 */
// Initiate viewport.
resize(Width, Height)
// Register that we are interested in receiving close and resize events.
window.SetCloseCallback(func(w *glfw.Window) {
return
})
window.SetSizeCallback(func(w *glfw.Window, width, height int) {
resize(width, height)
})
for !window.ShouldClose() {
draw()
window.SwapBuffers()
glfw.PollEvents()
}
}
// resize resizes the window to the specified dimensions.
func resize(width, height int) {
gl.Viewport(0, 0, gl.Sizei(width), gl.Sizei(height))
gl.MatrixMode(gl.PROJECTION)
gl.LoadIdentity()
gl.Ortho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)
gl.MatrixMode(gl.MODELVIEW)
}
// draw draws the triangle.
func draw() {
gl.ClearColor(0.3, 0.3, 0.3, 0.0)
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.ShadeModel(gl.SMOOTH)
gl.LoadIdentity()
gl.Translatef(-15.0, -15.0, 0.0)
gl.Begin(gl.TRIANGLES)
gl.Color3f(1.0, 0.0, 0.0)
gl.Vertex2f(0.0, 0.0)
gl.Color3f(0.0, 1.0, 0.0)
gl.Vertex2f(30.0, 0.0)
gl.Color3f(0.0, 0.0, 1.0)
gl.Vertex2f(0.0, 30.0)
gl.End()
gl.Flush()
} |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Common_Lisp | Common Lisp | (defun one-of-n-fn ()
(let ((cur 0) (sel nil))
#'(lambda (v)
(setq cur (+ cur 1))
(if (eql 0 (random cur)) (setq sel v))
sel)))
(defun test-one-of-n ()
(let ((counts (make-array 10 :initial-contents '(0 0 0 0 0 0 0 0 0 0)))
(fnt))
(do ((test 0 (+ 1 test)))
((eql test 1000000) counts)
(setq fnt (one-of-n-fn))
(do ((probe 0 (+ 1 probe)))
((eql probe 9) t)
(funcall fnt probe))
(let* ((sel (funcall fnt 9)))
(setf (aref counts sel) (+ 1 (aref counts sel)))))))
|
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.
| #zkl | zkl | fcn bh(pvalues){ // Benjamini-Hochberg
psz,pszf := pvalues.len(), psz.toFloat();
n_i := psz.pump(List,'wrap(n){ pszf/(psz - n) }); # N/(N-0),N/(N-1),..
o,ro := order(pvalues,True),order(o,False); # sort pvalues, sort indices
in := psz.pump(List,'wrap(n){ n_i[n]*pvalues[o[n]] });
pmin := cummin(in).apply((1.0).min); # (min(1,c[0]),min(1,c[1]),...)
ro.apply(pmin.get); # (pmin[ro[0]],pmin[ro[1]],...)
}
fcn by(pvalues){ // Benjamini & Yekutieli
psz,pszf := pvalues.len(), psz.toFloat();
o,ro := order(pvalues,True),order(o,False); # sort pvalues, sort indices
n_i := psz.pump(List,'wrap(n){ pszf/(psz - n) }); # N/(N-0),N/(N-1),..
q := [1..psz].reduce(fcn(q,n){ q+=1.0/n },0.0);
in := psz.pump(List,'wrap(n){ q * n_i[n] * pvalues[o[n]] });
cummin(in).apply((1.0).min) : ro.apply(_.get);
}
fcn hochberg(pvalues){
psz,pszf := pvalues.len(), psz.toFloat();
o,ro := order(pvalues,True),order(o,False); # sort pvalues, sort indices
n_i := psz.pump(List,'wrap(n){ pszf/(psz - n) }); # N/(N-0),N/(N-1),..
in := psz.pump(List,'wrap(n){ pvalues[o[n]]*(n + 1) });
cummin(in).apply((1.0).min) : ro.apply(_.get);
}
fcn cummin(pvalues){ // R's cumulative minima --> list of mins
out,m := List.createLong(pvalues.len()), pvalues[0];
foreach pv in (pvalues){ out.append(m=m.min(pv)) }
out
}
fcn order(list,downUp){ // True==increasing, --> List(int) sorted indices
f:=(downUp) and fcn(a,b){ a[1]>b[1] } or fcn(a,b){ a[1]<b[1] };
[0..].zip(list).pump(List()).sort(f).pump(List,T("get",0))
}
fcn bonferroni(pvalues){ // -->List
sz,r := pvalues.len(),List();
foreach pv in (pvalues){
b:=pv*sz;
if(b>=1.0) r.append(1.0);
else if(0.0<=b<1.0) r.append(b);
else throw(Exception.ValueError(
"%g is outside of the interval I planned.".fmt(b)));
}
r
}
fcn hommel(pvalues){
psz,indices := pvalues.len(), [1..psz].walk(); // 1,2,3,4...
o,ro := order(pvalues,False),order(o,False); # sort pvalues, sort indices
p := o.apply('wrap(n){ pvalues[n] }).copy(); // pvalues[*o]
npi := [1..].zip(p).apply('wrap([(n,p)]){ p*psz/n });
min := (0.0).min(npi); // min value in npi
pa,q := List.createLong(psz,min), pa.copy(); #(min,min,,,)
foreach j in ([psz - 1..2,-1]){
ij:=[0..psz - j].walk();
i2:=(j - 1).pump(List,'+(psz - j + 1));
q1:=(0.0).min((j-1).pump(List,'wrap(n){ p[i2[n]]*j/(2 + n) }));
foreach i in (psz - j + 1){ q[ij[i]] = q1.min(p[ij[i]]*j) }
foreach i in (j - 1){ q[i2[i]] = q[psz - j] }
foreach i in (psz){ pa[i] = pa[i].max(q[i]) }
}
psz.pump(List,'wrap(n){ pa[ro[n]] }); // Hommel q-values
} |
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
| #Python | Python | from __future__ import print_function
def order_disjoint_list_items(data, items):
#Modifies data list in-place
itemindices = []
for item in set(items):
itemcount = items.count(item)
#assert data.count(item) >= itemcount, 'More of %r than in data' % item
lastindex = [-1]
for i in range(itemcount):
lastindex.append(data.index(item, lastindex[-1] + 1))
itemindices += lastindex[1:]
itemindices.sort()
for index, item in zip(itemindices, items):
data[index] = item
if __name__ == '__main__':
tostring = ' '.join
for data, items in [ (str.split('the cat sat on the mat'), str.split('mat cat')),
(str.split('the cat sat on the mat'), str.split('cat mat')),
(list('ABCABCABC'), list('CACA')),
(list('ABCABDABE'), list('EADA')),
(list('AB'), list('B')),
(list('AB'), list('BA')),
(list('ABBA'), list('BA')),
(list(''), list('')),
(list('A'), list('A')),
(list('AB'), list('')),
(list('ABBA'), list('AB')),
(list('ABAB'), list('AB')),
(list('ABAB'), list('BABA')),
(list('ABCCBA'), list('ACAC')),
(list('ABCCBA'), list('CACA')),
]:
print('Data M: %-24r Order N: %-9r' % (tostring(data), tostring(items)), end=' ')
order_disjoint_list_items(data, items)
print("-> M' %r" % 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
| #JavaScript | JavaScript | function sorter(table, options) {
opts = {}
opts.ordering = options.ordering || 'lexicographic';
opts.column = options.column || 0;
opts.reverse = options.reverse || false;
// ...
}
sorter(the_data, {reverse: true, ordering: 'numeric'}); |
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.
| #Factor | Factor | IN: scratchpad { 2 3 } { 2 5 } before? .
t
|
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.
| #FreeBASIC | FreeBASIC | Dim Shared list1(4) As Integer = {1, 2, 1, 5, 2}
Dim Shared list2(5) As Integer = {1, 2, 1, 5, 2, 2}
Dim Shared list3(4) As Integer = {1, 2, 3, 4, 5}
Dim Shared list4(4) As Integer = {1, 2, 3, 4, 5}
Function Orden(listA() As Integer, listB() As Integer) As Boolean
Dim As Integer i = 0, l1, l2
l1 = Ubound(listA, 1)
l2 = Ubound(listB, 1)
While listA(i) = listB(i) And i < l1 And i < l2
i += 1
Wend
If listA(i) < listB(i) Then Return True
If listA(i) > listB(i) Then Return False
Return l1 < l2
End Function
If Orden(list1(), list2()) Then Print "list1<list2" Else Print "list1>=list2"
If Orden(list2(), list3()) Then Print "list2<list3" Else Print "list2>=list3"
If Orden(list3(), list4()) Then Print "list3<list4" Else Print "list3>=list4"
Sleep |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var binomial = Fn.new { |n, k|
if (n == k) return 1
var prod = 1
var i = n - k + 1
while (i <= n) {
prod = prod * i
i = i + 1
}
return prod / Int.factorial(k)
}
var pascalTriangle = Fn.new { |n|
if (n <= 0) return
for (i in 0...n) {
System.write(" " * (n-i-1))
for (j in 0..i) {
Fmt.write("$3d ", binomial.call(i, j))
}
System.print()
}
}
pascalTriangle.call(13) |
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.
| #Python | Python | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
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.
| #Q | Q | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 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
| #Gambas | Gambas | Public Sub Main()
Dim sDict As String = File.Load(User.Home &/ "unixdict.txt") 'Store the 'Dictionary'
Dim sOrdered As New String[] 'To store ordered words
Dim sHold As New String[] 'General store
Dim sTemp As String 'Temp variable
Dim siCount As Short 'Counter
For Each sTemp In Split(sDict, gb.NewLine) 'For each word in the Dictionary
For siCount = 1 To Len(sTemp) 'Loop for each letter in the word
sHold.Add(Mid(sTemp, siCount, 1)) 'Put each letter in sHold array
Next
sHold.Sort() 'Sort sHold (abbott = abboot, zoom = mooz)
If sTemp = sHold.Join("") Then sOrdered.Add(sTemp) 'If they are the same (abbott(OK) mooz(not OK)) then add to sOrdered
sHold.Clear 'Empty sHold
Next
siCount = 0 'Reset siCount
For Each sTemp In sOrdered 'For each of the Ordered words
If Len(sTemp) > siCount Then siCount = Len(sTemp) 'Count the length of the word and keep a record of the longest length
Next
For Each sTemp In sOrdered 'For each of the Ordered words
If Len(sTemp) = siCount Then sHold.Add(sTemp) 'If it is one of the longest add it to sHold
Next
sHold.Sort() 'Sort sHold
Print sHold.Join(gb.NewLine) 'Display the result
End |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Perl | Perl | # Palindrome.pm
package Palindrome;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT = qw(palindrome palindrome_c palindrome_r palindrome_e);
sub palindrome
{
my $s = (@_ ? shift : $_);
return $s eq reverse $s;
}
sub palindrome_c
{
my $s = (@_ ? shift : $_);
for my $i (0 .. length($s) >> 1)
{
return 0 unless substr($s, $i, 1) eq substr($s, -1 - $i, 1);
}
return 1;
}
sub palindrome_r
{
my $s = (@_ ? shift : $_);
if (length $s <= 1) { return 1; }
elsif (substr($s, 0, 1) ne substr($s, -1, 1)) { return 0; }
else { return palindrome_r(substr($s, 1, -1)); }
}
sub palindrome_e
{
(@_ ? shift : $_) =~ /^(.?|(.)(?1)\2)$/ + 0
} |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #Ada | Ada | generic
type Real is digits <>;
with function Sqrt(X: Real) return Real;
with function "**"(X: Real; Y: Real) return Real;
package Approximation is
type Number is private;
-- create an approximation
function Approx(Value: Real; Sigma: Real) return Number;
-- unary operations and conversion Real to Number
function "+"(X: Real) return Number;
function "-"(X: Real) return Number;
function "+"(X: Number) return Number;
function "-"(X: Number) return Number;
-- addition / subtraction
function "+"(X: Number; Y: Number) return Number;
function "-"(X: Number; Y: Number) return Number;
-- multiplication / division
function "*"(X: Number; Y: Number) return Number;
function "/"(X: Number; Y: Number) return Number;
-- exponentiation
function "**"(X: Number; Y: Positive) return Number;
function "**"(X: Number; Y: Real) return Number;
-- Output to Standard IO (wrapper for Ada.Text_IO and Ada.Text_IO.Float_IO)
procedure Put_Line(Message: String;
Item: Number;
Value_Fore: Natural := 7;
Sigma_Fore: Natural := 4;
Aft: Natural := 2;
Exp: Natural := 0);
procedure Put(Item: Number;
Value_Fore: Natural := 7;
Sigma_Fore: Natural := 3;
Aft: Natural := 2;
Exp: Natural := 0);
private
type Number is record
Value: Real;
Sigma: Real;
end record;
end Approximation; |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Many can be generated in multiple ways:
90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9
130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9
The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite:
2, 3, 6, 7, etc.
Task
Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares.
Do not use magic numbers or pre-determined limits. Justify your answer mathematically.
See also
OEIS: A001422 Numbers which are not the sum of distinct squares
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
class Program {
// recursively permutates the list of squares to seek a matching sum
static bool soms(int n, IEnumerable<int> f) {
if (n <= 0) return false;
if (f.Contains(n)) return true;
switch(n.CompareTo(f.Sum())) {
case 1: return false;
case 0: return true;
case -1:
var rf = f.Reverse().Skip(1).ToList();
return soms(n - f.Last(), rf) || soms(n, rf);
}
return false;
}
static void Main() {
var sw = System.Diagnostics.Stopwatch.StartNew();
int c = 0, r, i, g; var s = new List<int>(); var a = new List<int>();
var sf = "stopped checking after finding {0} sequential non-gaps after the final gap of {1}";
for (i = 1, g = 1; g >= (i >> 1); i++) {
if ((r = (int)Math.Sqrt(i)) * r == i) s.Add(i);
if (!soms(i, s)) a.Add(g = i);
}
sw.Stop();
Console.WriteLine("Numbers which are not the sum of distinct squares:");
Console.WriteLine(string.Join(", ", a));
Console.WriteLine(sf, i - g, g);
Console.Write("found {0} total in {1} ms",
a.Count, sw.Elapsed.TotalMilliseconds);
}
} |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Bracmat | Bracmat | ( ( odd-word
= dothis doother forward backward
. ( forward
= ch
. fil$:?ch
& put$!ch
& ( low$!ch:~<a:~>z&forward$
| !ch:~"."
)
)
& ( backward
= ch
. fil$:?ch
& ( low$!ch:~<a:~>z
& backward$() (put$!ch&) { This reduces to the return value of backwards$()}
| '(.put$($ch)&$ch:~".") { Macro, evaluates to a function with actual ch. }
)
)
& fil$(!arg,r)
& ((=forward$).(=(backward$)$))
: (?dothis.?doother)
& whl
' ( !(dothis.)
& (!doother.!dothis):(?dothis.?doother)
)
& (fil$(,SET,-1)|) { This is how a file is closed: seek the impossible. }
)
& put$("what,is,the;meaning,of:life.","life.txt",NEW)
& put$("we,are;not,in,kansas;any,more.","kansas.txt",NEW)
& odd-word$"life.txt"
& put$\n
& odd-word$"kansas.txt" { Real file, as Bracmat cannot read a single character from stdin. }
); |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #C | C | #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
owp(odd);
return 0;
} else {
if (ispunct(ch))
return ch;
ret = owp(odd);
putc(ch, stdout);
return ret;
}
}
int
main(int argc, char **argv)
{
int ch = 1;
while ((ch = owp(!ch)) != EOF) {
if (ch)
putc(ch, stdout);
if (ch == '.')
break;
}
return 0;
}
|
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #ALGOL_68 | ALGOL 68 | INT stop generation = 9;
INT universe width = 20;
FORMAT alive or dead = $b("#","_")$;
BITS universe := 2r01110110101010100100;
# universe := BIN ( ENTIER ( random * max int ) ); #
INT upb universe = bits width;
INT lwb universe = bits width - universe width + 1;
PROC couple = (BITS parent, INT lwb, upb)BOOL: (
SHORT INT sum := 0;
FOR bit FROM lwb TO upb DO
sum +:= ABS (bit ELEM parent)
OD;
sum = 2
);
FOR generation FROM 0 WHILE
printf(($"Generation "d": "$, generation,
$f(alive or dead)$, []BOOL(universe)[lwb universe:upb universe],
$l$));
# WHILE # generation < stop generation DO
BITS next universe := 2r0;
# process the first event horizon manually #
IF couple(universe,lwb universe,lwb universe + 1) THEN
next universe := 2r10
FI;
# process the middle kingdom in a loop #
FOR bit FROM lwb universe + 1 TO upb universe - 1 DO
IF couple(universe,bit-1,bit+1) THEN
next universe := next universe OR 2r1
FI;
next universe := next universe SHL 1
OD;
# process the last event horizon manually #
IF couple(universe, upb universe - 1, upb universe) THEN
next universe := next universe OR 2r1
FI;
universe := next universe
OD |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #C | C | #include <stdio.h>
#include <math.h>
#define N 5
double Pi;
double lroots[N];
double weight[N];
double lcoef[N + 1][N + 1] = {{0}};
void lege_coef()
{
int n, i;
lcoef[0][0] = lcoef[1][1] = 1;
for (n = 2; n <= N; n++) {
lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n;
for (i = 1; i <= n; i++)
lcoef[n][i] = ((2 * n - 1) * lcoef[n - 1][i - 1]
- (n - 1) * lcoef[n - 2][i] ) / n;
}
}
double lege_eval(int n, double x)
{
int i;
double s = lcoef[n][n];
for (i = n; i; i--)
s = s * x + lcoef[n][i - 1];
return s;
}
double lege_diff(int n, double x)
{
return n * (x * lege_eval(n, x) - lege_eval(n - 1, x)) / (x * x - 1);
}
void lege_roots()
{
int i;
double x, x1;
for (i = 1; i <= N; i++) {
x = cos(Pi * (i - .25) / (N + .5));
do {
x1 = x;
x -= lege_eval(N, x) / lege_diff(N, x);
} while ( fdim( x, x1) > 2e-16 );
/* fdim( ) was introduced in C99, if it isn't available
* on your system, try fabs( ) */
lroots[i - 1] = x;
x1 = lege_diff(N, x);
weight[i - 1] = 2 / ((1 - x * x) * x1 * x1);
}
}
double lege_inte(double (*f)(double), double a, double b)
{
double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0;
int i;
for (i = 0; i < N; i++)
sum += weight[i] * f(c1 * lroots[i] + c2);
return c1 * sum;
}
int main()
{
int i;
Pi = atan2(1, 1) * 4;
lege_coef();
lege_roots();
printf("Roots: ");
for (i = 0; i < N; i++)
printf(" %g", lroots[i]);
printf("\nWeight:");
for (i = 0; i < N; i++)
printf(" %g", weight[i]);
printf("\nintegrating Exp(x) over [-3, 3]:\n\t%10.8f,\n"
"compred to actual\n\t%10.8f\n",
lege_inte(exp, -3, 3), exp(3) - exp(-3));
return 0;
} |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Serialize.Employee Extends %SerialObject
{
Method %OnNew(ByRef pId As %Integer = 0, pDepartment As %String, pName As %String) As %Status
{
Do ..IDSet(pId)
Set pId=pId+1
Do ..DepartmentSet(pDepartment)
Do ..NameSet(pName)
Quit $$$OK
}
Method Print()
{
Write "[", ..%ClassName(), "]", !
Write "- ID: "_..IDGet(), !
Write "- Name: "_..NameGet(), !
Write "- Department: "_..DepartmentGet(), !
Quit
}
Property ID As %Integer [ Private ];
Property Name As %String [ Private ];
Property Department As %String [ Private ];
} |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Common_Lisp | Common Lisp | (defmacro with-serialization-to-file ((stream pathname) &body body)
`(with-open-file (,stream ,pathname
:element-type '(unsigned-byte 8)
:direction :output
:if-exists :supersede)
,@body))
(defclass entity ()
((name :initarg :name :initform "Some entity")))
(defclass person (entity)
((name :initarg :name :initform "The Nameless One"))) |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AutoHotkey | AutoHotkey | Animals := [["fly", "I don't know why she swallowed the "]
, ["spider", "That wriggled and jiggled and tickled inside her"]
, ["bird", "Quite absurd"]
, ["cat", "Fancy that"]
, ["dog", "What a hog"]
, ["pig", "Her mouth was so big"]
, ["goat", "She just opened her throat"]
, ["cow", "I don't know how"]
, ["donkey", "It was rather wonky"]
, ["horse", "She's dead, of course!"]]
for i, V in Animals {
Output .= "I know an old lady who swallowed a " V.1 ".`n"
. (i = 1 ? Saved := V.2 V.1 ".`nPerhaps she'll die.`n`n"
: V.2 (i = Animals.MaxIndex() ? "" : (i = 2 ? "" : ". To swallow a " V.1) ".`n"
. (Saved := "She swallowed the " V.1 " to catch the " Animals[i - 1].1 ".`n" Saved)))
}
MsgBox, % Output |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
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
| #Raku | Raku | use Rat::Precise;
my $googol = 10**100;
«PAIRs 2 SCOres 20 DOZens 12 GRoss 144 GREATGRoss 1728 GOOGOLs $googol»
~~ m:g/ ((<.:Lu>+) <.:Ll>*) \s+ (\S+) /;
my %abr = |$/.map: {
my $abbrv = .[0].Str.fc;
my $mag = +.[1];
|map { $abbrv.substr( 0, $_ ) => $mag },
.[0][0].Str.chars .. $abbrv.chars
}
my %suffix = flat %abr,
(<K M G T P E Z Y X W V U>».fc Z=> (1000, * * 1000 … *)),
(<Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui>».fc Z=> (1024, * * 1024 … *));
my $reg = %suffix.keys.join('|');
sub comma ($i is copy) {
my $s = $i < 0 ?? '-' !! '';
my ($whole, $frac) = $i.split('.');
$frac = $frac.defined ?? ".$frac" !! '';
$s ~ $whole.abs.flip.comb(3).join(',').flip ~ $frac
}
sub units (Str $str) {
$str.fc ~~ /^(.+?)(<alpha>*)('!'*)$/;
my ($val, $unit, $fact) = $0, $1.Str.fc, $2.Str;
$val.=subst(',', '', :g);
if $val ~~ m:i/'e'/ {
my ($m,$e) = $val.split(/<[eE]>/);
$val = ($e < 0)
?? $m * FatRat.new(1,10**-$e)
!! $m * 10**$e;
}
my @suf = $unit;
unless %suffix{$unit}:exists {
$unit ~~ /(<$reg>)+/;
@suf = $0;
}
my $ret = $val<>;
$ret = [*] $ret, |@suf.map: { %suffix{$_} } if @suf[0];
$ret = [*] ($ret, * - $fact.chars …^ * < 2) if $fact.chars;
$ret.?precise // $ret
}
my $test = q:to '===';
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
.017k!!
===
printf "%16s: %s\n", $_, comma .&units for $test.words;
# Task required stupid layout
# say "\n In: $_\nOut: ", .words.map({comma .&units}).join(' ') for $test.lines; |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim units(1 To 13) As String = {"tochka", "liniya", "dyuim", "vershok", "piad", "fut", _
"arshin", "sazhen", "versta", "milia", _
"centimeter", "meter", "kilometer"}
' all expressed in centimeters
Dim convs(1 To 13) As Single = {0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, _
71.12, 213.36, 10668, 74676, _
1, 100, 10000}
Dim unit As Integer
Dim value As Single
Dim yn As String
Do
Shell("cls")
Print
For i As Integer = 1 To 13
Print Using "##"; i;
Print " "; units(i)
Next
Print
Do
Input "Please choose a unit 1 to 13 : "; unit
Loop Until unit >= 1 AndAlso unit <= 13
Print
Do
Input "Now enter a value in that unit : "; value
Loop Until value >= 0
Print
Print "The equivalent in the remaining units is : "
Print
For i As Integer = 1 To 13
If i = unit Then Continue For
Print " "; units(i), " : "; value * convs(unit) / convs(i)
Next
Print
Do
Input "Do another one y/n : "; yn
yn = LCase(yn)
Loop Until yn = "y" OrElse yn = "n"
Loop Until yn = "n"
End |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Haskell | Haskell | import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
main = do
getArgsAndInitialize
createWindow "Triangle"
displayCallback $= display
matrixMode $= Projection
loadIdentity
ortho2D 0 30 0 30
matrixMode $= Modelview 0
mainLoop
display = do
clear [ColorBuffer]
renderPrimitive Triangles $ do
corner 1 0 0 5 5
corner 0 1 0 25 5
corner 0 0 1 5 25
swapBuffers
corner r g b x y = do color (Color3 r g b :: Color3 GLfloat)
vertex (Vertex2 x y :: Vertex2 GLfloat) |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #D | D | import std.stdio, std.random, std.algorithm;
// Zero-based line numbers.
int oneOfN(in int n) {
int choice = 0;
foreach (immutable i; 1 .. n)
if (!uniform(0, i + 1))
choice = i;
return choice;
}
void main() {
int[10] bins;
foreach (immutable i; 0 .. 1_000_000)
bins[10.oneOfN]++;
bins.writeln;
writeln("Total of bins: ", bins[].sum);
} |
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
| #Racket | Racket | #lang racket
(define disjorder
(match-lambda**
(((list) n) '())
((m (list)) m)
(((list h m-tail ...) (list h n-tail ...))
(list* h (disjorder m-tail n-tail)))
;; the (not g/h) below stop greedy matching of the list which
;; would pick out orderings from the right first.
(((list h (and (not g) m-tail-left) ... g m-tail-right ...)
(list g (and (not h) n-tail-left) ... h n-tail-right ...))
(disjorder `(,g ,@m-tail-left ,h ,@m-tail-right)
`(,g ,@n-tail-left ,h ,@n-tail-right)))
(((list h m-tail ...) n)
(list* h (disjorder m-tail n)))))
(define (report-disjorder m n)
(printf "Data M: ~a Order N: ~a -> ~a~%"
(~a #:min-width 25 m) (~a #:min-width 10 n) (disjorder m n)))
;; Do the task tests
(report-disjorder '(the cat sat on the mat) '(mat cat))
(report-disjorder '(the cat sat on the mat) '(cat mat))
(report-disjorder '(A B C A B C A B C) '(C A C A))
(report-disjorder '(A B C A B D A B E) '(E A D A))
(report-disjorder '(A B) '(B))
(report-disjorder '(A B) '(B A))
(report-disjorder '(A B B A) '(B A))
;; Do all of the other python tests
(report-disjorder '() '())
(report-disjorder '(A) '(A))
(report-disjorder '(A B) '())
(report-disjorder '(A B B A) '(A B))
(report-disjorder '(A B A B) '(A B))
(report-disjorder '(A B A B) '(B A B A))
(report-disjorder '(A B C C B A) '(A C A C))
(report-disjorder '(A B C C B A) '(C A C A)) |
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
| #Raku | Raku | sub order-disjoint-list-items(\M, \N) {
my \bag = N.BagHash;
M.map: { bag{$_}-- ?? N.shift !! $_ }
}
# Testing:
for q:to/---/.comb(/ [\S+]+ % ' ' /).map({[.words]})
the cat sat on the mat mat cat
the cat sat on the mat cat mat
A B C A B C A B C C A C A
A B C A B D A B E E A D A
A B B
A B B A
A B B A B A
X X Y X
A X Y A
---
-> $m, $n { say "\n$m ==> $n\n", order-disjoint-list-items($m, $n) } |
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
| #jq | jq | def bar: 2 *.;
def foo: {"a": bar}; |
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
| #Julia | Julia | sorttable(T; ordering=<, column=1, reverse=false) =
sort(T, by = t -> t[column], lt = reverse ? (a,b) -> ordering(b,a) : ordering)
sorttable(T, ordering=<, column=1, reverse=false) =
sorttable(T, ordering=ordering, column=column, reverse=reverse) |
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.
| #Go | Go | package main
import "fmt"
// If your numbers happen to be in the range of Unicode code points (0 to 0x10ffff), this function
// satisfies the task:
func lessRune(a, b []rune) bool {
return string(a) < string(b) // see also bytes.Compare
}
// Otherwise, the following function satisfies the task for all integer
// and floating point types, by changing the type definition appropriately.
type numericType int
func lessNT(a, b []numericType) bool {
l := len(a)
if len(b) < l {
l = len(b)
}
for i := 0; i < l; i++ {
if a[i] != b[i] {
return a[i] < b[i]
}
}
return l < len(b)
}
var testCases = [][][]numericType{
{{0}, {}},
{{}, {}},
{{}, {0}},
{{-1}, {0}},
{{0}, {0}},
{{0}, {-1}},
{{0}, {0, -1}},
{{0}, {0, 0}},
{{0}, {0, 1}},
{{0, -1}, {0}},
{{0, 0}, {0}},
{{0, 0}, {1}},
}
func main() {
// demonstrate the general function
for _, tc := range testCases {
fmt.Printf("order %6s before %6s : %t\n",
fmt.Sprintf("%v", tc[0]),
fmt.Sprintf("%v", tc[1]),
lessNT(tc[0], tc[1]))
}
fmt.Println()
// demonstrate that the byte specific function gives identical results
// by offsetting test data to a printable range of characters.
for _, tc := range testCases {
a := toByte(tc[0])
b := toByte(tc[1])
fmt.Printf("order %6q before %6q : %t\n",
string(a),
string(b),
lessByte(a, b))
}
}
func toByte(a []numericType) []byte {
b := make([]byte, len(a))
for i, n := range a {
b[i] = 'b' + byte(n)
}
return b
} |
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
| #X86_Assembly | X86 Assembly |
%include "io.inc"
section .text
global CMAIN
CMAIN:
mov ebx, 7 ;size
call mloop
ret
mloop:
mov edx, 0 ;edx stands for the nth line
looping:
push ebx
push edx
call line
pop edx
pop ebx
inc edx
cmp edx, ebx
jl looping
xor eax, eax
ret
line:
mov ecx, 0 ;ecx stands for the nth character in each line
mlp:
push ecx
push edx
call nCk
pop edx
pop ecx
PRINT_DEC 4, eax ;print returned number
PRINT_STRING " "
inc ecx
cmp ecx, edx ;if
jle mlp
NEWLINE
ret
nCk:
;ecx : j
;edx : i
mov esi, edx
call fac ;i!
push eax ;save i!
mov esi, ecx
call fac ;j!
push eax ;save j!
mov ebx, edx
sub ebx, ecx ;(i-j)
mov esi, ebx
call fac ;(i-j)!
pop ebx ;(i-j)! is in eax
mul ebx ;(i-j)! * j!
mov ecx, eax
pop eax ; get i!
div ecx ; ; last step : i! divided by (i-j)! * j!
ret
fac:
push ecx
push edx
mov eax, 1
mov ecx, esi
cmp ecx, 0 ; 0! returns 1
je facz
lp:
mul ecx ;multiplies eax by ecx and then decrements ecx until ecx is 0
dec ecx
cmp ecx, 0
jg lp
jmp end
facz:
mov eax, 1
end:
pop edx
pop ecx
ret
|
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.
| #Quackery | Quackery | (function arguments ...) |
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.
| #Racket | Racket | (function arguments ...) |
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.
| #Raku | Raku | ╔══════════════════════════════════════════════════════════════════════╗
║ ║
║ The following is a table that lists the precedence and associativity ║
║ of all the operators in the (classic) REXX language. ║
║ ║
║ 1 is the highest precedence. ║
║ ║
╠══════════╤════════╤══════════════════════════════════════════════════╣
║ │ │ ║
║precedence│operator│ description ║
║ │ │ ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 1 │ - │ unary minus ║
║ │ + │ unary plus ║
║ │ \ │ logical not ║
║ │ ├──(the following aren't supported by all REXXes)──╢
║ │ ¬ │ logical not ║
║ │ ~ │ logical not ║
║ │ ^ │ logical not ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 2 │ ** │ exponentiation (integer power) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 3 │ * │ multiplication ║
║ │ / │ division ║
║ │ % │ integer division ║
║ │ // │ modulus (remainder division, sign of dividend)║
║ │ / / │ modulus (any 2 or 3 character operators may ║
║ │ │ have whitespace between characters.) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 4 │ + │ addition ║
║ │ - │ subtraction ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 5 │ || │ concatenation ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 6 │ & │ logical AND ║
║ │ | │ logical OR (inclusive OR) ║
║ │ && │ logical XOR (exclusive OR) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 7 │[blank] │ concatenation ║
║ │abuttal │ concatenation ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 8 │ = │ equal to ║
║ │ == │ exactly equal to (also, strictly equal to) ║
║ │ \= │ not equal to ║
║ │ <> │ not equal to (also, less than or greater than) ║
║ │ >< │ not equal to (also, greater than or less than) ║
║ │ > │ greater than ║
║ │ >= │ greater than or equal to ║
║ │ < │ less than ║
║ │ <= │ less than or equal to ║
║ │ >> │ exactly greater than ║
║ │ << │ exactly less than ║
║ │ <<= │ exactly less than or equal to ║
║ │ >>= │ exactly greater than or equal to ║
║ │ ├──(the following aren't supported by all REXXes)──╢
║ │ /= │ not equal to ║
║ │ ¬= │ not equal to ║
║ │ ~= │ not equal to ║
║ │ ^= │ not equal to ║
║ │ /== │ not exactly equal to ║
║ │ \== │ not exactly equal to ║
║ │ ¬== │ not exactly equal to ║
║ │ ~== │ not exactly equal to ║
║ │ ^== │ not exactly equal to ║
║ │ /< │ not less than ║
║ │ ~< │ not less than ║
║ │ ¬< │ not less than ║
║ │ ^< │ not less than ║
║ │ /> │ not greater than ║
║ │ ¬> │ not greater than ║
║ │ ~> │ not greater than ║
║ │ ^> │ not greater than ║
║ │ /<= │ not less than or equal to ║
║ │ ¬<= │ not less than or equal to ║
║ │ ~<= │ not less than or equal to ║
║ │ ^<= │ not less than or equal to ║
║ │ />= │ not greater than or equal to ║
║ │ ¬>= │ not greater than or equal to ║
║ │ ~>= │ not greater than or equal to ║
║ │ ^>= │ not greater than or equal to ║
║ │ \>> │ not exactly greater than ║
║ │ ¬>> │ not exactly greater than ║
║ │ ~>> │ not exactly greater than ║
║ │ ^>> │ not exactly greater than ║
║ │ \<< │ not exactly less than ║
║ │ ¬<< │ not exactly less than ║
║ │ ~<< │ not exactly less than ║
║ │ ^<< │ not exactly less than ║
╚══════════╧════════╧══════════════════════════════════════════════════╝
|
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
| #Go | Go | package main
import (
"bytes"
"fmt"
"io/ioutil"
)
func main() {
// read into memory in one chunk
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
fmt.Println(err)
return
}
// split at line ends
bss := bytes.Split(b, []byte{'\n'})
// accumulate result
var longest int
var list [][]byte
for _, bs := range bss {
// don't bother with words shorter than
// our current longest ordered word
if len(bs) < longest {
continue
}
// check for ordered property
var lastLetter byte
for i := 0; ; i++ {
if i == len(bs) {
// end of word. it's an ordered word.
// save it and break from loop
if len(bs) > longest {
longest = len(bs)
list = list[:0]
}
list = append(list, bs)
break
}
// check next letter
b := bs[i]
if b < 'a' || b > 'z' {
continue // not a letter. ignore.
}
if b < lastLetter {
break // word not ordered.
}
// letter passes test
lastLetter = b
}
}
// print result
for _, bs := range list {
fmt.Println(string(bs))
}
} |
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
| #Phix | Phix | function is_palindrome(sequence s)
return s==reverse(s)
end function
?is_palindrome("rotator") -- prints 1
?is_palindrome("tractor") -- prints 0
constant punctuation = " `~!@#$%^&*()-=_+[]{}\\|;:',.<>/?",
nulls = repeat("",length(punctuation))
function extra_credit(sequence s)
s = utf8_to_utf32(lower(substitute_all(s,punctuation,nulls)))
return s==reverse(s)
end function
-- these all print 1 (true)
?extra_credit("Madam, I'm Adam.")
?extra_credit("A man, a plan, a canal: Panama!")
?extra_credit("In girum imus nocte et consumimur igni")
?extra_credit("人人為我,我為人人")
?extra_credit("Я иду с мечем, судия")
?extra_credit("아들딸들아")
?extra_credit("가련하시다 사장집 아들딸들아 집장사 다시 하련가")
?extra_credit("tregða, gón, reiði - er nóg að gert")
|
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #ALGOL_68 | ALGOL 68 | # MODE representing a uncertain number #
MODE UNCERTAIN = STRUCT( REAL v, uncertainty );
# add a costant and an uncertain value #
OP + = ( INT c, UNCERTAIN u )UNCERTAIN: UNCERTAIN( v OF u + c, uncertainty OF u );
OP + = ( UNCERTAIN u, INT c )UNCERTAIN: c + u;
OP + = ( REAL c, UNCERTAIN u )UNCERTAIN: UNCERTAIN( v OF u + c, uncertainty OF u );
OP + = ( UNCERTAIN u, REAL c )UNCERTAIN: c + u;
# add two uncertain values #
OP + = ( UNCERTAIN a, b )UNCERTAIN: UNCERTAIN( v OF a + v OF b
, sqrt( ( uncertainty OF a * uncertainty OF a )
+ ( uncertainty OF b * uncertainty OF b )
)
);
# negate an uncertain value #
OP - = ( UNCERTAIN a )UNCERTAIN: ( - v OF a, uncertainty OF a );
# subtract an uncertain value from a constant #
OP - = ( INT c, UNCERTAIN u )UNCERTAIN: c + - u;
OP - = ( REAL c, UNCERTAIN u )UNCERTAIN: c + - u;
# subtract a constant from an uncertain value #
OP - = ( UNCERTAIN u, INT c )UNCERTAIN: u + - c;
OP - = ( UNCERTAIN u, REAL c )UNCERTAIN: u + - c;
# subtract two uncertain values #
OP - = ( UNCERTAIN a, b )UNCERTAIN: a + - b;
# multiply a constant by an uncertain value #
OP * = ( INT c, UNCERTAIN u )UNCERTAIN: UNCERTAIN( v OF u + c, ABS( c * uncertainty OF u ) );
OP * = ( UNCERTAIN u, INT c )UNCERTAIN: c * u;
OP * = ( REAL c, UNCERTAIN u )UNCERTAIN: UNCERTAIN( v OF u + c, ABS( c * uncertainty OF u ) );
OP * = ( UNCERTAIN u, REAL c )UNCERTAIN: c * u;
# multiply two uncertain values #
OP * = ( UNCERTAIN a, b )UNCERTAIN:
BEGIN
REAL av = v OF a;
REAL bv = v OF b;
REAL f = av * bv;
UNCERTAIN( f, f * sqrt( ( uncertainty OF a / av ) + ( uncertainty OF b / bv ) ) )
END # * # ;
# construct the reciprocol of an uncertain value #
OP ONEOVER = ( UNCERTAIN u )UNCERTAIN: ( 1 / v OF u, uncertainty OF u );
# divide a constant by an uncertain value #
OP / = ( INT c, UNCERTAIN u )UNCERTAIN: c * ONEOVER u;
OP / = ( REAL c, UNCERTAIN u )UNCERTAIN: c * ONEOVER u;
# divide an uncertain value by a constant #
OP / = ( UNCERTAIN u, INT c )UNCERTAIN: u * ( 1 / c );
OP / = ( UNCERTAIN u, REAL c )UNCERTAIN: u * ( 1 / c );
# divide two uncertain values #
OP / = ( UNCERTAIN a, b )UNCERTAIN: a * ONEOVER b;
# exponentiation #
OP ^ = ( UNCERTAIN u, INT c )UNCERTAIN:
BEGIN
REAL f = v OF u ^ c;
UNCERTAIN( f, ABS ( ( f * c * uncertainty OF u ) / v OF u ) )
END # ^ # ;
OP ^ = ( UNCERTAIN u, REAL c )UNCERTAIN:
BEGIN
REAL f = v OF u ^ c;
UNCERTAIN( f, ABS ( ( f * c * uncertainty OF u ) / v OF u ) )
END # ^ # ;
# test the above operatrs by using them to find the pythagorean distance between the two sample points #
UNCERTAIN x1 = UNCERTAIN( 100, 1.1 );
UNCERTAIN y1 = UNCERTAIN( 50, 1.2 );
UNCERTAIN x2 = UNCERTAIN( 200, 2.2 );
UNCERTAIN y2 = UNCERTAIN( 100, 2.3 );
UNCERTAIN d = ( ( ( x1 - x2 ) ^ 2 ) + ( y1 - y2 ) ^ 2 ) ^ 0.5;
print( ( "distance: ", fixed( v OF d, 0, 2 ), " +/- ", fixed( uncertainty OF d, 0, 2 ), newline ) ) |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Many can be generated in multiple ways:
90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9
130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9
The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite:
2, 3, 6, 7, etc.
Task
Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares.
Do not use magic numbers or pre-determined limits. Justify your answer mathematically.
See also
OEIS: A001422 Numbers which are not the sum of distinct squares
| #Go | Go | package main
import (
"fmt"
"math"
"rcu"
)
func contains(a []int, n int) bool {
for _, e := range a {
if e == n {
return true
}
}
return false
}
// recursively permutates the list of squares to seek a matching sum
func soms(n int, f []int) bool {
if n <= 0 {
return false
}
if contains(f, n) {
return true
}
sum := rcu.SumInts(f)
if n > sum {
return false
}
if n == sum {
return true
}
rf := make([]int, len(f))
copy(rf, f)
for i, j := 0, len(rf)-1; i < j; i, j = i+1, j-1 {
rf[i], rf[j] = rf[j], rf[i]
}
rf = rf[1:]
return soms(n-f[len(f)-1], rf) || soms(n, rf)
}
func main() {
var s, a []int
sf := "\nStopped checking after finding %d sequential non-gaps after the final gap of %d\n"
i, g := 1, 1
for g >= (i >> 1) {
r := int(math.Sqrt(float64(i)))
if r*r == i {
s = append(s, i)
}
if !soms(i, s) {
g = i
a = append(a, g)
}
i++
}
fmt.Println("Numbers which are not the sum of distinct squares:")
fmt.Println(a)
fmt.Printf(sf, i-g, g)
fmt.Printf("Found %d in total\n", len(a))
}
var r int |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #C.2B.2B | C++ | #include <iostream>
#include <cctype>
#include <functional>
using namespace std;
bool odd()
{
function<void ()> prev = []{};
while(true) {
int c = cin.get();
if (!isalpha(c)) {
prev();
cout.put(c);
return c != '.';
}
prev = [=] { cout.put(c); prev(); };
}
}
bool even()
{
while(true) {
int c;
cout.put(c = cin.get());
if (!isalpha(c)) return c != '.';
}
}
int main()
{
bool e = false;
while( e ? odd() : even() ) e = !e;
return 0;
} |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #ALGOL_W | ALGOL W | begin
string(20) state;
string(20) nextState;
integer generation;
generation := 0;
state := "_###_##_#_#_#_#__#__";
while begin
write( i_w := 1, s_w := 1, "Generation ", generation, state );
nextState := "____________________";
for cPos := 1 until 18 do begin
string(3) curr;
curr := state( cPos - 1 // 3 );
nextState( cPos // 1 ) := if curr = "_##" or curr = "#_#" or curr = "##_" then "#" else "_"
end for_cPos ;
( state not = nextState )
end do begin
state := nextState;
generation := generation + 1
end while_not_finished
end. |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #11l | 11l | F left_rect((Float -> Float) f, Float x, Float h) -> Float
R f(x)
F mid_rect((Float -> Float) f, Float x, Float h) -> Float
R f(x + h / 2)
F right_rect((Float -> Float) f, Float x, Float h) -> Float
R f(x + h)
F trapezium((Float -> Float) f, Float x, Float h) -> Float
R (f(x) + f(x + h)) / 2.0
F simpson((Float -> Float) f, Float x, Float h) -> Float
R (f(x) + 4 * f(x + h / 2) + f(x + h)) / 6.0
F cube(Float x) -> Float
R x * x * x
F reciprocal(Float x) -> Float
R 1 / x
F identity(Float x) -> Float
R x
F integrate(f, a, b, steps, meth)
V h = (b - a) / steps
V ival = h * sum((0 .< steps).map(i -> @meth(@f, @a + i * @h, @h)))
R ival
L(a, b, steps, func, func_name) [(0.0, 1.0, 100, cube, ‘cube’),
(1.0, 100.0, 1000, reciprocal, ‘reciprocal’),
(0.0, 5000.0, 5'000'000, identity, ‘identity’),
(0.0, 6000.0, 6'000'000, identity, ‘identity’)]
L(rule, rule_name) [(left_rect, ‘left_rect’),
(mid_rect, ‘mid_rect’),
(right_rect, ‘right_rect’),
(trapezium, ‘trapezium’),
(simpson, ‘simpson’)]
print("#. integrated using #.\n from #. to #. (#. steps) = #.".format(
func_name, rule_name, a, b, steps, integrate(func, a, b, steps, rule))) |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #11l | 11l | F riseEqFall(=num)
‘Check whether a number belongs to sequence A296712.’
V height = 0
V d1 = num % 10
num I/= 10
L num != 0
V d2 = num % 10
height += (d1 < d2) - (d1 > d2)
d1 = d2
num I/= 10
R height == 0
V num = 0
F nextNum()
L
:num++
I riseEqFall(:num)
L.break
R :num
print(‘The first 200 numbers are:’)
L 200
print(nextNum(), end' ‘ ’)
print()
L 0 .< 10'000'000 - 200 - 1
nextNum()
print(‘The 10,000,000th number is: ’nextNum()) |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
#include <cmath>
namespace Rosetta {
/*! Implementation of Gauss-Legendre quadrature
* http://en.wikipedia.org/wiki/Gaussian_quadrature
* http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature
*
*/
template <int N>
class GaussLegendreQuadrature {
public:
enum {eDEGREE = N};
/*! Compute the integral of a functor
*
* @param a lower limit of integration
* @param b upper limit of integration
* @param f the function to integrate
* @param err callback in case of problems
*/
template <typename Function>
double integrate(double a, double b, Function f) {
double p = (b - a) / 2;
double q = (b + a) / 2;
const LegendrePolynomial& legpoly = s_LegendrePolynomial;
double sum = 0;
for (int i = 1; i <= eDEGREE; ++i) {
sum += legpoly.weight(i) * f(p * legpoly.root(i) + q);
}
return p * sum;
}
/*! Print out roots and weights for information
*/
void print_roots_and_weights(std::ostream& out) const {
const LegendrePolynomial& legpoly = s_LegendrePolynomial;
out << "Roots: ";
for (int i = 0; i <= eDEGREE; ++i) {
out << ' ' << legpoly.root(i);
}
out << std::endl;
out << "Weights:";
for (int i = 0; i <= eDEGREE; ++i) {
out << ' ' << legpoly.weight(i);
}
out << std::endl;
}
private:
/*! Implementation of the Legendre polynomials that form
* the basis of this quadrature
*/
class LegendrePolynomial {
public:
LegendrePolynomial () {
// Solve roots and weights
for (int i = 0; i <= eDEGREE; ++i) {
double dr = 1;
// Find zero
Evaluation eval(cos(M_PI * (i - 0.25) / (eDEGREE + 0.5)));
do {
dr = eval.v() / eval.d();
eval.evaluate(eval.x() - dr);
} while (fabs (dr) > 2e-16);
this->_r[i] = eval.x();
this->_w[i] = 2 / ((1 - eval.x() * eval.x()) * eval.d() * eval.d());
}
}
double root(int i) const { return this->_r[i]; }
double weight(int i) const { return this->_w[i]; }
private:
double _r[eDEGREE + 1];
double _w[eDEGREE + 1];
/*! Evaluate the value *and* derivative of the
* Legendre polynomial
*/
class Evaluation {
public:
explicit Evaluation (double x) : _x(x), _v(1), _d(0) {
this->evaluate(x);
}
void evaluate(double x) {
this->_x = x;
double vsub1 = x;
double vsub2 = 1;
double f = 1 / (x * x - 1);
for (int i = 2; i <= eDEGREE; ++i) {
this->_v = ((2 * i - 1) * x * vsub1 - (i - 1) * vsub2) / i;
this->_d = i * f * (x * this->_v - vsub1);
vsub2 = vsub1;
vsub1 = this->_v;
}
}
double v() const { return this->_v; }
double d() const { return this->_d; }
double x() const { return this->_x; }
private:
double _x;
double _v;
double _d;
};
};
/*! Pre-compute the weights and abscissae of the Legendre polynomials
*/
static LegendrePolynomial s_LegendrePolynomial;
};
template <int N>
typename GaussLegendreQuadrature<N>::LegendrePolynomial GaussLegendreQuadrature<N>::s_LegendrePolynomial;
}
// This to avoid issues with exp being a templated function
double RosettaExp(double x) {
return exp(x);
}
int main() {
Rosetta::GaussLegendreQuadrature<5> gl5;
std::cout << std::setprecision(10);
gl5.print_roots_and_weights(std::cout);
std::cout << "Integrating Exp(X) over [-3, 3]: " << gl5.integrate(-3., 3., RosettaExp) << std::endl;
std::cout << "Actual value: " << RosettaExp(3) - RosettaExp(-3) << std::endl;
} |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #D | D | package test;
message base1 {
required int32 i32 = 1;
}
message base2 {
repeated base1 rep = 1;
}
|
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #E | E | def makeEvent(time :int) {
return def event {
to __printOn(out) { out.print(`@@$time`) }
to __optUncall() { return [makeEvent, "run", [time]] }
to getTime() { return time }
}
}
def makeArrival(time :int, what :any, position :int) {
return def arrival extends makeEvent(time) {
to __printOn(out) {
out.print(`$what to $position $super`)
}
to __optUncall() {
return [makeArrival, "run", [time, what, position]]
}
to getWhat() { return what }
to getPosition() { return position }
}
} |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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 |
# syntax: GAWK -f OLD_LADY_SWALLOWED_A_FLY.AWK
BEGIN {
arr[++i] = "fly/"
arr[++i] = "spider/That wriggled and jiggled and tickled inside her"
arr[++i] = "bird/Quite absurd@"
arr[++i] = "cat/Fancy that@"
arr[++i] = "dog/What a hog@"
arr[++i] = "pig/Her mouth was so big@"
arr[++i] = "goat/Opened her throat and down went the goat"
arr[++i] = "cow/I don't know how@"
arr[++i] = "donkey/It was rather wonkey@"
arr[++i] = "horse/She's dead of course"
leng = i # array length
for (i=1; i<=leng; i++) {
s = arr[i]
A[i] = substr(s,1,index(s,"/")-1) # critter name
text = substr(s,index(s,"/")+1)
sub(/@/," to swallow a "A[i],text)
printf("I know an old lady who swallowed a %s.\n",A[i])
if (text != "") {
printf("%s.\n",text)
}
if (i == leng) {
break
}
for (j=i; j>1; j--) {
printf("She swallowed the %s to catch the %s.\n",A[j],A[j-1])
}
printf("I don't know why she swallowed the fly.\n")
printf("Perhaps she'll die.\n\n")
}
exit(0)
}
|
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
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
| #REXX | REXX | /*REXX pgm converts numbers (with commas) with suffix multipliers──►pure decimal numbers*/
numeric digits 2000 /*allow the usage of ginormous numbers.*/
@.=; @.1= '2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre'
@.2= '1,567 +1.567k 0.1567e-2m'
@.3= '25.123kK 25.123m 2.5123e-00002G'
@.4= '25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei'
@.5= '-.25123e-34Vikki 2e-77gooGols'
@.6= 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
parse arg x /*obtain optional arguments from the CL*/
if x\=='' then do; @.2=; @.1=x /*use the number(s) specified on the CL*/
end /*allow user to specify their own list.*/
/* [↓] handle a list or multiple lists*/
do n=1 while @.n\==''; $= /*process each of the numbers in lists.*/
say 'numbers= ' @.n /*echo the original arg to the terminal*/
do j=1 for words(@.n); y= word(@.n, j) /*obtain a single number from the input*/
$= $ ' 'commas( num(y) ) /*process a number; add result to list.*/
end /*j*/ /* [↑] add commas to number if needed.*/
/* [↑] add extra blank betweenst nums.*/
say ' result= ' strip($); say /*echo the result(s) to the terminal. */
end /*n*/ /* [↑] elide the pre-pended blank. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isInt: return datatype( arg(1), 'Whole') /*return 1 if arg is an integer, or 0 */
isNum: return datatype( arg(1), 'Number') /* " " " " " a number. " " */
p: return word( arg(1), 1) /*pick 1st argument or 2nd argument. */
ser: say; say '***error*** ' arg(1); say; exit 13
shorten:procedure; parse arg a,n; return left(a, max(0, length(a) - p(n 1) ) )
/*──────────────────────────────────────────────────────────────────────────────────────*/
$fact!: procedure; parse arg x _ .; L= length(x); n= L - length(strip(x, 'T', "!") )
if n<=-n | _\=='' | arg()\==1 then return x; z= left(x, L - n)
if z<0 | \isInt(z) then return x; return $fact(z, n)
/*──────────────────────────────────────────────────────────────────────────────────────*/
$fact: procedure; parse arg x _ .; arg ,n ! .; n= p(n 1); if \isInt(n) then n= 0
if x<-n | \isInt(x) |n<1 | _||!\=='' |arg()>2 then return x||copies("!",max(1,n))
s= x // n; if s==0 then s= n /*compute where to start multiplying. */
!= 1 /*the initial factorial product so far.*/
do j=s to x by n; != !*j /*perform the actual factorial product.*/
end /*j*/ /*{operator // is REXX's ÷ remainder}*/
return ! /* [↑] handles any level of factorial.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
$sfxa: parse arg u,s 1 c,m; upper u c /*get original version & upper version.*/
if pos( left(s, 2), u)\==0 then do j=length(s) to compare(s, c)-1 by -1
if right(u, j) \== left(c, j) then iterate
_= left(u, length(u) - j) /*get the num.*/
if isNum(_) then return m * _ /*good suffix.*/
leave /*return as is*/
end
return arg(1) /* [↑] handles an alphabetic suffixes.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
$sfx!: parse arg y; if right(y, 1)=='!' then y= $fact!(y)
if \isNum(y) then y=$sfxz(); if isNum(y) then return y; return $sfxm(y)
/*──────────────────────────────────────────────────────────────────────────────────────*/
$sfxm: parse arg z 1 w; upper w; @= 'KMGTPEZYXWVU'; b= 1000
if right(w, 1)=='I' then do; z= shorten(z); w= z; upper w; b= 1024
end
_= pos( right(w, 1), @); if _==0 then return arg(1)
n= shorten(z); r= num(n, , 1); if isNum(r) then return r * b**_
return arg(1) /* [↑] handles metric or binary suffix*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
$sfxz: return $sfxa( $sfxa( $sfxa( $sfxa( $sfxa( $sfxa(y, 'PAIRs', 2), 'DOZens', 12), ,
'SCores', 20), 'GREATGRoss', 1728), 'GRoss', 144), 'GOOGOLs', 1e100)
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, "M")
e= verify(n, #'0', , verify(n, #"0.", 'M') ) - 4 /* [↑] add commas.*/
do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
num: procedure; parse arg x .,,q; if x=='' then return x
if isNum(x) then return x/1; x= space( translate(x, , ','), 0)
if \isNum(x) then x= $sfx!(x); if isNum(x) then return x/1
if q==1 then return x
if q=='' then call ser "argument isn't numeric or doesn't have a legal suffix:" x |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Forth | Forth | create units s" kilometer" 2, s" meter" 2, s" centimeter" 2, s" tochka" 2, s" liniya" 2, s" diuym" 2, s" vershok" 2, s" piad" 2, s" fut" 2, s" arshin" 2, s" sazhen" 2, s" versta" 2, s" milia" 2,
create values 1000.0e f, 1.0e f, 0.01e f, 0.000254e f, 0.00254e f, 0.0254e f, 0.04445e f, 0.1778e f, 0.3048e f, 0.7112e f, 2.1336e f, 1066.8e f, 7467.6e f,
: unit ( u1 -- caddr u1 )
units swap 2 cells * + 2@ ;
: myval ( u1 -- caddr u1 )
values swap 1 cells * + f@ ;
: 2define create 0 , 0 , ;
2define ch_u
variable mlt
variable theunit
: show ( chosen_unit chosen_mutliplier -- )
ch_u 2!
mlt f!
13 0 DO
ch_u 2@ i unit compare if
else mlt f@ f. i unit type cr ." ===========" cr
i myval theunit f!
13 0 DO
." " i unit type ." : " theunit f@ i myval f/ mlt f@ f* f. cr
LOOP
then
LOOP cr ;
1e s" meter" show
20e s" versta" show
10e s" milia" show |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Frink | Frink | arshin := (2 + 1/3) ft
vershok := 1/16 arshin
sazhen := 3 arshin
verst := 1500 arshin
versta := verst
do
{
valstr = input["Enter unit of measure: ", "1 arshin"]
val = eval[valstr]
if ! (val conforms length)
println["$valstr is not a unit of length."]
} until val conforms length
println["$valstr = "]
println[" " + (val -> "arshin")]
println[" " + (val -> "vershok")]
println[" " + (val -> "sazhen")]
println[" " + (val -> "verst")]
println[" " + (val -> "feet")]
println[" " + (val -> "meters")]
println[" " + (val -> "centimeters")]
println[" " + (val -> "kilometers")] |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #J | J | coclass 'example'
(coinsert[require) 'jzopengl'
create=:3 :0
ogl=: ''conew'jzopengl'
wd 'pc p;cc c isigraph opengl rightmove bottommove;pas 0 0;pshow;'
)
p_close=: destroy=:3 :0
destroy__ogl''
wd'pclose'
codestroy''
)
corner=:4 :0
glColor3d x
glVertex2d y
)
p_c_paint=:3 :0
rc__ogl''
glClear GL_COLOR_BUFFER_BIT
glBegin GL_TRIANGLES
1 0 0 corner 0 0-0.5
0 1 0 corner 1 0-0.5
0 0 1 corner 0 1-0.5
glEnd''
show__ogl''
)
conew~'example' |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Delphi | Delphi |
class
APPLICATION
create
make
feature
make
-- Simulates one_of_n_lines a 1000000 times.
local
t: INTEGER
simulator: ARRAY [INTEGER]
do
create simulator.make_filled (0, 1, 10)
create one.make
across
1 |..| 1000000 as c
loop
t := one.one_of_n_lines (10)
simulator [t] := simulator [t] + 1
end
across
simulator as s
loop
io.put_integer (s.item)
io.new_line
end
end
one: ONE_OF_N_LINES
end
|
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Simulates one_of_n_lines a 1000000 times.
local
t: INTEGER
simulator: ARRAY [INTEGER]
do
create simulator.make_filled (0, 1, 10)
create one.make
across
1 |..| 1000000 as c
loop
t := one.one_of_n_lines (10)
simulator [t] := simulator [t] + 1
end
across
simulator as s
loop
io.put_integer (s.item)
io.new_line
end
end
one: ONE_OF_N_LINES
end
|
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
| #REXX | REXX | /*REXX program orders a disjoint list of M items with a list of N items. */
used = '0'x /*indicates that a word has been parsed*/
@. = /*placeholder indicates end─of─array, */
@.1 = " the cat sat on the mat | mat cat " /*a string.*/
@.2 = " the cat sat on the mat | cat mat " /*" " */
@.3 = " A B C A B C A B C | C A C A " /*" " */
@.4 = " A B C A B D A B E | E A D A " /*" " */
@.5 = " A B | B " /*" " */
@.6 = " A B | B A " /*" " */
@.7 = " A B B A | B A " /*" " */
@.8 = " | " /*" " */
@.9 = " A | A " /*" " */
@.10 = " A B | " /*" " */
@.11 = " A B B A | A B " /*" " */
@.12 = " A B A B | A B " /*" " */
@.13 = " A B A B | B A B A " /*" " */
@.14 = " A B C C B A | A C A C " /*" " */
@.15 = " A B C C B A | C A C A " /*" " */
/* ════════════M═══════════ ════N════ */
do j=1 while @.j\=='' /* [↓] process each input string (@.).*/
parse var @.j m '|' n /*parse input string into M and N. */
#= words(m) /*#: number of words in the M list.*/
do i=# for # by -1 /*process list items in reverse order. */
_= word(m, i); !.i= _; $._= i /*construct the !. and $. arrays.*/
end /*i*/
r.= /*nullify the replacement string [R.] */
do k=1 by 2 for words(n)%2 /* [↓] process the N array. */
_= word(n, k); v= word(n, k+1) /*get an order word and the replacement*/
p1= wordpos(_, m); p2= wordpos(v, m) /*positions of " " " " */
if p1==0 | p2==0 then iterate /*if either not found, then skip them. */
if $._>>$.v then do; r.p2= !.p1; r.p1= !.p2; end /*switch the words.*/
else do; r.p1= !.p1; r.p2= !.p2; end /*don't switch. */
!.p1= used; !.p2= used /*mark 'em as used.*/
m=
do i=1 for #; m= m !.i; _= word(m, i); !.i= _; $._= i
end /*i*/
end /*k*/ /* [↑] rebuild the !. and $. arrays.*/
mp= /*the MP (aka M') string (so far). */
do q=1 for #; if !.q==used then mp= mp r.q /*use the original.*/
else mp= mp !.q /*use substitute. */
end /*q*/ /* [↑] re─build the (output) string. */
say @.j ' ────► ' space(mp) /*display new re─ordered text ──► term.*/
end /*j*/ /* [↑] end of processing for N words*/
/*stick a fork in it, we're all done. */ |
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
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
:mypower
1 tolist flatten len
1 equal
( [pop drop 2]
[pop pop drop]
) if
power
;
"2 ^2 = " print 2 mypower ?
"2 ^3 = " print ( 2 3 ) mypower ?
"End " input |
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
| #Kotlin | Kotlin | // version 1.1.51
typealias Table = List<List<String>>
/* Note that if ordering is specified, first two parameters are ignored */
fun Table.sort(
column: Int = 0,
reverse: Boolean = false,
ordering: Comparator<List<String>> =
if (!reverse) compareBy { it[column] }
else compareByDescending { it[column] }
) = this.sortedWith(ordering)
fun Table.print(title: String) {
println(title)
for (i in 0 until this.size) {
for (j in 0 until this[0].size) System.out.print("%-3s ".format(this[i][j]))
println()
}
println()
}
fun main(args: Array<String>) {
val table = listOf(
listOf("a", "b", "c"),
listOf("", "q", "z"),
listOf("zap", "zip", "Zot")
)
table.print("Original:")
val titles = listOf(
"Sorted by col 0:", "Sorted by col 1:", "Sorted by col 2:",
"Reverse sorted by col 0:", "Reverse sorted by col 1:", "Reverse Sorted by col 2"
)
val params = listOf(
0 to false, 1 to false, 2 to false, 0 to true, 1 to true, 2 to true
)
for ((i, title) in titles.withIndex()) {
val table2 = table.sort(params[i].first, params[i].second)
table2.print(title)
}
// using non-default Comparator (case insensitive by col 2, reversed)
val comp: Comparator<List<String>> = compareByDescending { it[2].toLowerCase() }
val table3 = table.sort(ordering = comp)
table3.print("Reverse case insensitive sort by col 2:")
} |
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.
| #Groovy | Groovy | class CList extends ArrayList implements Comparable {
CList() { }
CList(Collection c) { super(c) }
int compareTo(Object that) {
assert that instanceof List
def n = [this.size(), that.size()].min()
def comp = [this[0..<n], that[0..<n]].transpose().find { it[0] != it[1] }
comp ? comp[0] <=> comp[1] : this.size() <=> that.size()
}
} |
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
| #XBasic | XBasic |
PROGRAM "pascal"
VERSION "0.0001"
DECLARE FUNCTION Entry()
FUNCTION Entry()
r@@ = UBYTE(INLINE$("Number of rows? "))
FOR i@@ = 0 TO r@@ - 1
c%% = 1
FOR k@@ = 0 TO i@@
PRINT FORMAT$("####", c%%);
c%% = c%% * (i@@ - k@@) / (k@@ + 1)
NEXT k@@
PRINT
NEXT i@@
END FUNCTION
END PROGRAM
|
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.
| #REALbasic | REALbasic | ╔══════════════════════════════════════════════════════════════════════╗
║ ║
║ The following is a table that lists the precedence and associativity ║
║ of all the operators in the (classic) REXX language. ║
║ ║
║ 1 is the highest precedence. ║
║ ║
╠══════════╤════════╤══════════════════════════════════════════════════╣
║ │ │ ║
║precedence│operator│ description ║
║ │ │ ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 1 │ - │ unary minus ║
║ │ + │ unary plus ║
║ │ \ │ logical not ║
║ │ ├──(the following aren't supported by all REXXes)──╢
║ │ ¬ │ logical not ║
║ │ ~ │ logical not ║
║ │ ^ │ logical not ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 2 │ ** │ exponentiation (integer power) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 3 │ * │ multiplication ║
║ │ / │ division ║
║ │ % │ integer division ║
║ │ // │ modulus (remainder division, sign of dividend)║
║ │ / / │ modulus (any 2 or 3 character operators may ║
║ │ │ have whitespace between characters.) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 4 │ + │ addition ║
║ │ - │ subtraction ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 5 │ || │ concatenation ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 6 │ & │ logical AND ║
║ │ | │ logical OR (inclusive OR) ║
║ │ && │ logical XOR (exclusive OR) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 7 │[blank] │ concatenation ║
║ │abuttal │ concatenation ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 8 │ = │ equal to ║
║ │ == │ exactly equal to (also, strictly equal to) ║
║ │ \= │ not equal to ║
║ │ <> │ not equal to (also, less than or greater than) ║
║ │ >< │ not equal to (also, greater than or less than) ║
║ │ > │ greater than ║
║ │ >= │ greater than or equal to ║
║ │ < │ less than ║
║ │ <= │ less than or equal to ║
║ │ >> │ exactly greater than ║
║ │ << │ exactly less than ║
║ │ <<= │ exactly less than or equal to ║
║ │ >>= │ exactly greater than or equal to ║
║ │ ├──(the following aren't supported by all REXXes)──╢
║ │ /= │ not equal to ║
║ │ ¬= │ not equal to ║
║ │ ~= │ not equal to ║
║ │ ^= │ not equal to ║
║ │ /== │ not exactly equal to ║
║ │ \== │ not exactly equal to ║
║ │ ¬== │ not exactly equal to ║
║ │ ~== │ not exactly equal to ║
║ │ ^== │ not exactly equal to ║
║ │ /< │ not less than ║
║ │ ~< │ not less than ║
║ │ ¬< │ not less than ║
║ │ ^< │ not less than ║
║ │ /> │ not greater than ║
║ │ ¬> │ not greater than ║
║ │ ~> │ not greater than ║
║ │ ^> │ not greater than ║
║ │ /<= │ not less than or equal to ║
║ │ ¬<= │ not less than or equal to ║
║ │ ~<= │ not less than or equal to ║
║ │ ^<= │ not less than or equal to ║
║ │ />= │ not greater than or equal to ║
║ │ ¬>= │ not greater than or equal to ║
║ │ ~>= │ not greater than or equal to ║
║ │ ^>= │ not greater than or equal to ║
║ │ \>> │ not exactly greater than ║
║ │ ¬>> │ not exactly greater than ║
║ │ ~>> │ not exactly greater than ║
║ │ ^>> │ not exactly greater than ║
║ │ \<< │ not exactly less than ║
║ │ ¬<< │ not exactly less than ║
║ │ ~<< │ not exactly less than ║
║ │ ^<< │ not exactly less than ║
╚══════════╧════════╧══════════════════════════════════════════════════╝
|
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.
| #REXX | REXX | ╔══════════════════════════════════════════════════════════════════════╗
║ ║
║ The following is a table that lists the precedence and associativity ║
║ of all the operators in the (classic) REXX language. ║
║ ║
║ 1 is the highest precedence. ║
║ ║
╠══════════╤════════╤══════════════════════════════════════════════════╣
║ │ │ ║
║precedence│operator│ description ║
║ │ │ ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 1 │ - │ unary minus ║
║ │ + │ unary plus ║
║ │ \ │ logical not ║
║ │ ├──(the following aren't supported by all REXXes)──╢
║ │ ¬ │ logical not ║
║ │ ~ │ logical not ║
║ │ ^ │ logical not ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 2 │ ** │ exponentiation (integer power) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 3 │ * │ multiplication ║
║ │ / │ division ║
║ │ % │ integer division ║
║ │ // │ modulus (remainder division, sign of dividend)║
║ │ / / │ modulus (any 2 or 3 character operators may ║
║ │ │ have whitespace between characters.) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 4 │ + │ addition ║
║ │ - │ subtraction ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 5 │ || │ concatenation ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 6 │ & │ logical AND ║
║ │ | │ logical OR (inclusive OR) ║
║ │ && │ logical XOR (exclusive OR) ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 7 │[blank] │ concatenation ║
║ │abuttal │ concatenation ║
╟──────────┼────────┼──────────────────────────────────────────────────╢
║ 8 │ = │ equal to ║
║ │ == │ exactly equal to (also, strictly equal to) ║
║ │ \= │ not equal to ║
║ │ <> │ not equal to (also, less than or greater than) ║
║ │ >< │ not equal to (also, greater than or less than) ║
║ │ > │ greater than ║
║ │ >= │ greater than or equal to ║
║ │ < │ less than ║
║ │ <= │ less than or equal to ║
║ │ >> │ exactly greater than ║
║ │ << │ exactly less than ║
║ │ <<= │ exactly less than or equal to ║
║ │ >>= │ exactly greater than or equal to ║
║ │ ├──(the following aren't supported by all REXXes)──╢
║ │ /= │ not equal to ║
║ │ ¬= │ not equal to ║
║ │ ~= │ not equal to ║
║ │ ^= │ not equal to ║
║ │ /== │ not exactly equal to ║
║ │ \== │ not exactly equal to ║
║ │ ¬== │ not exactly equal to ║
║ │ ~== │ not exactly equal to ║
║ │ ^== │ not exactly equal to ║
║ │ /< │ not less than ║
║ │ ~< │ not less than ║
║ │ ¬< │ not less than ║
║ │ ^< │ not less than ║
║ │ /> │ not greater than ║
║ │ ¬> │ not greater than ║
║ │ ~> │ not greater than ║
║ │ ^> │ not greater than ║
║ │ /<= │ not less than or equal to ║
║ │ ¬<= │ not less than or equal to ║
║ │ ~<= │ not less than or equal to ║
║ │ ^<= │ not less than or equal to ║
║ │ />= │ not greater than or equal to ║
║ │ ¬>= │ not greater than or equal to ║
║ │ ~>= │ not greater than or equal to ║
║ │ ^>= │ not greater than or equal to ║
║ │ \>> │ not exactly greater than ║
║ │ ¬>> │ not exactly greater than ║
║ │ ~>> │ not exactly greater than ║
║ │ ^>> │ not exactly greater than ║
║ │ \<< │ not exactly less than ║
║ │ ¬<< │ not exactly less than ║
║ │ ~<< │ not exactly less than ║
║ │ ^<< │ not exactly less than ║
╚══════════╧════════╧══════════════════════════════════════════════════╝
|
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.
| #Ring | Ring |
The next table present operators from higher precedence (Evaluated first) to lower precedence.
Operator
. [] () {}
- ~ :Literal [list items]
++ - -
Start:End
* / %
+ -
<< >>
&
| ^
< > <= >=
= !=
not
and or
Assignment = += -= *= /= %=>>= <<= &= ^= |=
Example:
See 3+5*4 # prints 23
|
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
| #Groovy | Groovy | def isOrdered = { word -> def letters = word as List; letters == ([] + letters).sort() }
assert isOrdered('abbey')
assert !isOrdered('cat')
def dictUrl = new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt')
def orderedWords = dictUrl.readLines().findAll { isOrdered(it) }
def owMax = orderedWords*.size().max()
orderedWords.findAll { it.size() == owMax }.each { println it } |
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
| #PHP | PHP | <?php
function is_palindrome($string) {
return $string == strrev($string);
}
?> |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #C | C |
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
typedef struct{
double value;
double delta;
}imprecise;
#define SQR(x) ((x) * (x))
imprecise imprecise_add(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value + b.value;
ret.delta = sqrt(SQR(a.delta) + SQR(b.delta));
return ret;
}
imprecise imprecise_mul(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value * b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta));
return ret;
}
imprecise imprecise_div(imprecise a, imprecise b)
{
imprecise ret;
ret.value = a.value / b.value;
ret.delta = sqrt(SQR(a.value * b.delta) + SQR(b.value * a.delta)) / SQR(b.value);
return ret;
}
imprecise imprecise_pow(imprecise a, double c)
{
imprecise ret;
ret.value = pow(a.value, c);
ret.delta = fabs(ret.value * c * a.delta / a.value);
return ret;
}
char* printImprecise(imprecise val)
{
char principal[30],error[30],*string,sign[2];
sign[0] = 241; /* ASCII code for ±, technical notation for denoting errors */
sign[1] = 00;
sprintf(principal,"%f",val.value);
sprintf(error,"%f",val.delta);
string = (char*)malloc((strlen(principal)+1+strlen(error)+1)*sizeof(char));
strcpy(string,principal);
strcat(string,sign);
strcat(string,error);
return string;
}
int main(void) {
imprecise x1 = {100, 1.1};
imprecise y1 = {50, 1.2};
imprecise x2 = {-200, 2.2};
imprecise y2 = {-100, 2.3};
imprecise d;
d = imprecise_pow(imprecise_add(imprecise_pow(imprecise_add(x1, x2), 2),imprecise_pow(imprecise_add(y1, y2), 2)), 0.5);
printf("Distance, d, between the following points :");
printf("\n( x1, y1) = ( %s, %s)",printImprecise(x1),printImprecise(y1));
printf("\n( x2, y2) = ( %s, %s)",printImprecise(x2),printImprecise(y2));
printf("\nis d = %s", printImprecise(d));
return 0;
}
|
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Many can be generated in multiple ways:
90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9
130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9
The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite:
2, 3, 6, 7, etc.
Task
Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares.
Do not use magic numbers or pre-determined limits. Justify your answer mathematically.
See also
OEIS: A001422 Numbers which are not the sum of distinct squares
| #jq | jq | #def squares: range(1; infinite) | . * .;
# sums of distinct squares (sods)
# Output: a stream of [$n, $sums] where $sums is the array of sods based on $n
def sods:
# input: [$n, $sums]
def next:
. as [$n, $sums]
| (($n+1)*($n+1)) as $next
| reduce $sums[] as $s ($sums + [$next];
if index($s + $next) then . else . + [$s + $next] end)
| [$n + 1, unique];
[1, [1]]
| recurse(next);
# Input: an array
# Output: the length of the run beginning at $n
def length_of_run($n):
label $out
| (range($n+1; length),null) as $i
| if $i == null then (length-$n)
elif .[$i] == .[$i-1] + 1 then empty
else $i-$n, break $out
end;
# Input: an array
def length_of_longest_run:
. as $in
| first(
foreach (range(0; length),null) as $i (0;
if $i == null then .
else ($in|length_of_run($i)) as $n
| if $n > . then $n else . end
end;
if $i == null or (($in|length) - $i) < . then . else empty end) );
def sq: .*.;
# Output: [$ix, $length]
def relevant_sods:
first(
sods
| . as [$n, $s]
| ($s|length_of_longest_run) as $length
| if $length > ($n+1|sq) then . else empty end );
def not_sum_of_distinct_squares:
relevant_sods
| . as [$ix, $sods]
| [range(2; $ix+2|sq)] - $sods;
not_sum_of_distinct_squares |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Many can be generated in multiple ways:
90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9
130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9
The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite:
2, 3, 6, 7, etc.
Task
Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares.
Do not use magic numbers or pre-determined limits. Justify your answer mathematically.
See also
OEIS: A001422 Numbers which are not the sum of distinct squares
| #Julia | Julia | #=
Here we show all the 128 < numbers < 400 can be expressed as a sum of distinct squares. Now
11 * 11 < 128 < 12 * 12. It is also true that we need no square less than 144 (12 * 12) to
reduce via subtraction of squares all the numbers above 400 to a number > 128 and < 400 by
subtracting discrete squares of numbers over 12, since the interval between such squares can
be well below 128: for example, |14^2 - 15^2| is 29. So, we can always find a serial subtraction
of discrete integer squares from any number > 400 that targets the interval between 129 and
400. Once we get to that interval, we already have shown in the program below that we can
use the remaining squares under 400 to complete the remaining sum.
=#
using Combinatorics
squares = [n * n for n in 1:20]
possibles = [n for n in 1:500 if all(combo -> sum(combo) != n, combinations(squares))]
println(possibles)
|
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Many can be generated in multiple ways:
90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9
130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9
The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite:
2, 3, 6, 7, etc.
Task
Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares.
Do not use magic numbers or pre-determined limits. Justify your answer mathematically.
See also
OEIS: A001422 Numbers which are not the sum of distinct squares
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[SumOfSquareable]
SumOfSquareable[n_Integer] := MemberQ[Total /@ Subsets[Range[1, Floor[Sqrt[n]]]^2, {1, \[Infinity]}], n]
notsummable = {};
i = 1;
Do[
If[SumOfSquareable[i],
If[i > 1,
If[i - Max[notsummable] > Max[notsummable],
Break[]
]
]
,
AppendTo[notsummable, i]
];
i++
,
{\[Infinity]}
]
notsummable |
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares | Numbers which are not the sum of distinct squares |
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... )
Most positive integers can be generated as the sum of 1 or more distinct integer squares.
1 == 1
5 == 4 + 1
25 == 16 + 9
77 == 36 + 25 + 16
103 == 49 + 25 + 16 + 9 + 4
Many can be generated in multiple ways:
90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9
130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9
The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite:
2, 3, 6, 7, etc.
Task
Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares.
Do not use magic numbers or pre-determined limits. Justify your answer mathematically.
See also
OEIS: A001422 Numbers which are not the sum of distinct squares
| #Pascal | Pascal | program practicalnumbers;
{$IFDEF Windows} {$APPTYPE CONSOLE} {$ENDIF}
var
HasSum: array of byte;
function FindLongestContiniuosBlock(startIdx,MaxIdx:NativeInt):NativeInt;
var
hs0 : pByte;
l : NativeInt;
begin
l := 0;
hs0 := @HasSum[0];
for startIdx := startIdx to MaxIdx do
Begin
IF hs0[startIdx]=0 then
BREAK;
inc(l);
end;
FindLongestContiniuosBlock := l;
end;
function SumAllSquares(Limit: Uint32):NativeInt;
//mark sum and than shift by next summand == add
var
hs0, hs1: pByte;
idx, j, maxlimit, delta,MaxContiniuos,MaxConOffset: NativeInt;
begin
MaxContiniuos := 0;
MaxConOffset := 0;
maxlimit := 0;
hs0 := @HasSum[0];
hs0[0] := 1; //has sum of 0*0
idx := 1;
writeln('number offset longest sum of');
writeln(' block squares');
while idx <= Limit do
begin
delta := idx*idx;
//delta is within the continiuos range than break
If (MaxContiniuos-MaxConOffset) > delta then
BREAK;
//mark oldsum+ delta with oldsum
hs1 := @hs0[delta];
for j := maxlimit downto 0 do
hs1[j] := hs1[j] or hs0[j];
maxlimit := maxlimit + delta;
j := MaxConOffset;
repeat
delta := FindLongestContiniuosBlock(j,maxlimit);
IF delta>MaxContiniuos then
begin
MaxContiniuos:= delta;
MaxConOffset := j;
end;
inc(j,delta+1);
until j > (maxlimit-delta);
writeln(idx:4,MaxConOffset:7,MaxContiniuos:8,maxlimit:8);
inc(idx);
end;
SumAllSquares:= idx;
end;
var
limit,
sumsquare,
n: NativeInt;
begin
Limit := 25;
sumsquare := 0;
for n := 1 to Limit do
sumsquare := sumsquare+n*n;
writeln('sum of square [1..',limit,'] = ',sumsquare) ;
writeln;
setlength(HasSum,sumsquare+1);
n := SumAllSquares(Limit);
writeln(n);
for Limit := 1 to n*n do
if HasSum[Limit]=0 then
write(Limit,',');
setlength(HasSum,0);
{$IFNDEF UNIX} readln; {$ENDIF}
end.
|
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Ceylon | Ceylon |
String[] meaning = ["what,", "is,", "the;", "meaning,", "of:", "life."];
String[] kansas = ["we,", "are,", "not,", "in,", "kansas;", "any,", "more."];
shared void run() {
print("".join(reverseWords(meaning)));
print("".join(reverseWords(kansas)));
}
String[] reverseWords(String[] words)
=> recursiveReverseWords(words, []);
String[] recursiveReverseWords(String[] remOrig, String[] revWords)
=> if (nonempty remOrig)
then recursiveReverseWords(remOrig.rest,
revWords.withTrailing(reverseWordRecursive(remOrig.first.sequence(),
[],
revWords.size.even)))
else revWords;
String reverseWordRecursive(Character[] remOldChars, Character[] revChars, Boolean isEven)
=> if (nonempty remOldChars)
then let (char = remOldChars.first) reverseWordRecursive(remOldChars.rest,
conditionalAddChar(char, revChars, isEven),
isEven)
else String(revChars);
Character[] conditionalAddChar(Character char, Character[] chars, Boolean isEven)
=> if (isEven || isPunctuation(char))
then chars.withTrailing(char)
else chars.withLeading(char);
Boolean isPunctuation(Character char)
=> ",.:;".contains(char);
|
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Clojure | Clojure | (defn next-char []
(char (.read *in*)))
(defn forward []
(let [ch (next-char)]
(print ch)
(if (Character/isLetter ch)
(forward)
(not= ch \.))))
(defn backward []
(let [ch (next-char)]
(if (Character/isLetter ch)
(let [result (backward)]
(print ch)
result)
(fn [] (print ch) (not= ch \.)))) )
(defn odd-word [s]
(with-in-str s
(loop [forward? true]
(when (if forward?
(forward)
((backward)))
(recur (not forward?)))) )
(println)) |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Arturo | Arturo | evolve: function [arr][
ary: [0] ++ arr ++ [0]
ret: new []
loop 1..(size ary)-2 'i [
a: ary\[i-1]
b: ary\[i]
c: ary\[i+1]
if? 2 = a+b+c -> 'ret ++ 1
else -> 'ret ++ 0
]
ret
]
printIt: function [arr][
print replace replace join map arr => [to :string] "0" "_" "1" "#"
]
arr: [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0]
printIt arr
newGen: evolve arr
while [newGen <> arr][
arr: newGen
newGen: evolve arr
printIt newGen
] |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #ActionScript | ActionScript | function leftRect(f:Function, a:Number, b:Number, n:uint):Number
{
var sum:Number = 0;
var dx:Number = (b-a)/n;
for (var x:Number = a; n > 0; n--, x += dx)
sum += f(x);
return sum * dx;
}
function rightRect(f:Function, a:Number, b:Number, n:uint):Number
{
var sum:Number = 0;
var dx:Number = (b-a)/n;
for (var x:Number = a + dx; n > 0; n--, x += dx)
sum += f(x);
return sum * dx;
}
function midRect(f:Function, a:Number, b:Number, n:uint):Number
{
var sum:Number = 0;
var dx:Number = (b-a)/n;
for (var x:Number = a + (dx / 2); n > 0; n--, x += dx)
sum += f(x);
return sum * dx;
}
function trapezium(f:Function, a:Number, b:Number, n:uint):Number
{
var dx:Number = (b-a)/n;
var x:Number = a;
var sum:Number = f(a);
for(var i:uint = 1; i < n; i++)
{
a += dx;
sum += f(a)*2;
}
sum += f(b);
return 0.5 * dx * sum;
}
function simpson(f:Function, a:Number, b:Number, n:uint):Number
{
var dx:Number = (b-a)/n;
var sum1:Number = f(a + dx/2);
var sum2:Number = 0;
for(var i:uint = 1; i < n; i++)
{
sum1 += f(a + dx*i + dx/2);
sum2 += f(a + dx*i);
}
return (dx/6) * (f(a) + f(b) + 4*sum1 + 2*sum2);
} |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #8080_Assembly | 8080 Assembly | puts: equ 9 ; CP/M calls
putch: equ 2
org 100h
;;; Print first 200 numbers
lxi d,first
mvi c,puts
call 5
mvi b,200 ; 200 numbers
f200: push b
call next ; Get next number
call pnum ; Print the number
pop b ; Restore counter
dcr b ; Are we there yet?
jnz f200 ; If not, next number
;;; Find 10,000,000th number
lxi d,tenmil
mvi c,puts
call 5
f1e7: call next ; Keep generating numbers until ten million reached
jnz f1e7 ; Then print the number
;;; Print the current number
pnum: lxi d,num
pscan: dcx d ; Scan for zero
ldax d
ana a
jnz pscan
mvi c,puts ; Once found, print string
jmp 5
;;; Increment number until rises and falls are equal
next: lxi h,num
incdgt: mov a,m ; Get digit
ana a ; If 0, then initialize
jz grow
inr a ; Otherwise, increment
mov m,a ; Store back
cpi '9'+1 ; Rollover?
jnz idone ; If not, we're done
mvi m,'0' ; If so, set digit to 0
dcx h ; And increment previous digit
jmp incdgt
grow: mvi m,'1'
idone: lxi h,num ; Find rises and falls
mvi b,0 ; B = rises - falls
mov c,m ; C = right digit in comparison
pair: dcx h
mov a,m ; A = left digit in comparison
ana a ; When zero, done
jz check
cmp c ; Compare left digit to right digit
jc fall ; A<C = fall
jnz rise ; A>C = rise
nxdgt: mov c,a ; C is now left digit
jmp pair ; Check next pair
fall: dcr b ; Fall: decrement B
jmp nxdgt
rise: inr b ; Rise: increment B
jmp nxdgt
check: mov a,b ; If B=0 then rises and falls are equal
ana a
jnz next ; Otherwise, increment number and try again
lxi h,ctr ; But if so, decrement the counter to 10 million
mov a,m ; First byte
sui 1
mov m,a
inx h ; Second byte
mov a,m
sbb b ; B=0 here
mov m,a
inx h ; Third byte
mov a,m
sbb b
mov m,a
dcx h ; OR them together to see if the number is zero
ora m
dcx h
ora m
ret
;;; Strings
first: db 'The first 200 numbers are:',13,10,'$'
tenmil: db 13,10,10,'The 10,000,000th number is: $'
;;; Current number (stored as ASCII)
db 0,0,0,0,0,0,0,0
num: db '0 $'
;;; 24-bit counter to keep track of ten million
ctr: db 80h,96h,98h ; 1e7 = 989680h |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #8086_Assembly | 8086 Assembly | puts: equ 9 ; MS-DOS print string
cpu 8086
bits 16
org 100h
section .text
mov bp,98h ; BP:DI = 989680h = ten million
mov di,9680h
;;; Print first 200 numbers
mov dx,first ; Print message
mov ah,puts
int 21h
n200: call next ; Get next number
call pnum ; Print the number
cmp di,95B8h ; Have we had 200 yet?
ja n200 ; If not, print next number
;;; Print the 10 millionth number
mov dx,tenmil ; Print message
mov ah,puts
int 21h
n1e7: call next ; Get next number
jnz n1e7 ; Until we have the 10 millionth
;;; Print the current number
pnum: std ; Read backwards
xchg si,di ; Keep DI safe
mov di,num
mov cx,9
xor al,al ; Find the first zero
repnz scasb
inc di ; Go to first digit
inc di
xchg si,di ; Put DI back
mov dx,si ; Call DOS to print the number
mov ah,puts
int 21h
ret
;;; Increment number until rises and falls are equal
next: std ; Read number backwards
.inc: mov bx,num
.iloop: mov al,[bx] ; Get digit
test al,al ; If uninitialized, write a 1
jz .grow
inc ax ; Otherwise, increment
mov [bx],al ; Write it back
cmp al,'9'+1 ; Rollover?
jnz .idone ; If not, the increment is done
mov [bx],byte '0' ; But if so, this digit should be 0,
dec bx ; and the next digit incremented.
jmp .iloop
.grow: mov [bx],byte '1' ; The number gains an extra digit
.idone: xor bl,bl ; BL = rise and fall counter
mov si,num
lodsb ; Read first digit to compare to
.pair: xchg ah,al ; Previous digit to compare
lodsb ; Read next digit
test al,al ; Done yet?
jz .done
cmp al,ah ; If not, compare the digits
ja .fall ; If they are different,
jb .rise ; there is a fall or a rise
jmp .pair ; Otherwise, try next pair
.fall: dec bl ; Fall: decrement BL
jmp .pair
.rise: inc bl ; Rise: increment BL
jmp .pair
.done: test bl,bl ; At the end, check if BL is zero
jnz .inc ; If not, try next number
sub di,1 ; Decrement the million counter in BP:DI
sbb bp,0
mov ax,di ; Test if BP:DI is zero
or ax,bp
ret
section .data
;;; Strings
first: db 'The first 200 numbers are:',13,10,'$'
tenmil: db 13,10,10,'The 10,000,000th number is: $'
;;; Current number, stored as ASCII
db 0,0,0,0,0,0,0,0
num: db '0 $' |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #C.23 | C# |
using System;
//Works in .NET 6+
//Tested using https://dotnetfiddle.net because im lazy
public class Program {
public static double[][] legeCoef(int N) {
//Initialising Jagged Array
double[][] lcoef = new double[N+1][];
for (int i=0; i < lcoef.Length; ++i)
lcoef[i] = new double[N+1];
lcoef[0][0] = lcoef[1][1] = 1;
for (int n = 2; n <= N; n++) {
lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n;
for (int i = 1; i <= n; i++)
lcoef[n][i] = ((2*n - 1) * lcoef[n-1][i-1]
- (n-1) * lcoef[n-2][i] ) / n;
}
return lcoef;
}
static double legeEval(double[][] lcoef, int N, double x) {
double s = lcoef[N][N];
for (int i = N; i > 0; --i)
s = s * x + lcoef[N][i-1];
return s;
}
static double legeDiff(double[][] lcoef, int N, double x) {
return N * (x * legeEval(lcoef, N, x) - legeEval(lcoef, N-1, x)) / (x*x - 1);
}
static void legeRoots(double[][] lcoef, int N, out double[] lroots, out double[] weight) {
lroots = new double[N];
weight = new double[N];
double x, x1;
for (int i = 1; i <= N; i++) {
x = Math.Cos(Math.PI * (i - 0.25) / (N + 0.5));
do {
x1 = x;
x -= legeEval(lcoef, N, x) / legeDiff(lcoef, N, x);
}
while (x != x1);
lroots[i-1] = x;
x1 = legeDiff(lcoef, N, x);
weight[i-1] = 2 / ((1 - x*x) * x1*x1);
}
}
static double legeInte(Func<Double, Double> f, int N, double[] weights, double[] lroots, double a, double b) {
double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0;
for (int i = 0; i < N; i++)
sum += weights[i] * f.Invoke(c1 * lroots[i] + c2);
return c1 * sum;
}
//..................Main...............................
public static string Combine(double[] arrayD) {
return string.Join(", ", arrayD);
}
public static void Main() {
int N = 5;
var lcoeff = legeCoef(N);
double[] roots;
double[] weights;
legeRoots(lcoeff, N, out roots, out weights);
var integrateResult = legeInte(x=>Math.Exp(x), N, weights, roots, -3, 3);
Console.WriteLine("Roots: " + Combine(roots));
Console.WriteLine("Weights: " + Combine(weights)+ "\n" );
Console.WriteLine("integral: " + integrateResult );
Console.WriteLine("actual: " + (Math.Exp(3)-Math.Exp(-3)) );
}
} |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #EchoLisp | EchoLisp |
(define (person->string self) (format "%a : person." (person-name self)))
(define (writer->string self) (format "%a: writer of %a."
(person-name self)
(writer-books self)))
(define (father->string self) (format "%a: father of %a."
(person-name self)
(map person-name (father-children self))))
; 'classes' definition, with inheritance.
; a writer is a person, too.
(struct person (name) #:tostring person->string)
(struct writer person (books) #:tostring writer->string)
(struct father person (children) #:tostring father->string)
(define simon (writer "Simon" '(my-life my-wife my-bike)))
(define elvis (person "Elvis"))
(define papa (father "papa" (list simon elvis)))
(local-put-value 'simon simon "objects.dat")
📕 local-db: local-put:unknown store : "objects.dat"
;; forgot to create the store. Create it :
(local-make-store "objects.dat") → "objects.dat"
(local-put-value 'simon simon "objects.dat")
(local-put-value 'elvis elvis "objects.dat")
(local-put-value 'papa papa "objects.dat")
;; inspect
simon → Simon: writer of (my-life my-wife my-bike).
papa → papa: father of (Simon Elvis).
elvis → Elvis : person.
|
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Erlang | Erlang |
-module( object_serialization ).
-export( [task/0] ).
-record( entity, {name, date} ).
-record( person, {entity, email} ).
task() ->
Person = #person{entity=#entity{name="Cletus", date=20080808}, email="test+1@localhost.localdomain"},
print( Person ),
Entity = #entity{name="Entity", date=20111111},
print( Entity ),
ok = file:write_file( "objects.dat", erlang:term_to_binary([Person, Entity]) ),
{ok, Binary} = file:read_file( "objects.dat" ),
[New_person, New_entity] = erlang:binary_to_term( Binary ),
io:fwrite( "Deserialized\n" ),
print( New_person ),
print( New_entity ).
print( #entity{name=Name, date=Date} ) ->
io:fwrite( "Entity: " ),
io:fwrite( "name: ~p, date: ~p~n", [Name, Date] );
print( #person{entity=Entity, email=Email} ) ->
io:fwrite( "Person: " ),
print( Entity ),
io:fwrite( "\temail: ~p~n", [Email] ).
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Babel | Babel | ((main {fly !})
(fly
{{"There was an old lady who swallowed a " <<
iter 1 - dup
<- 0 animal ! nl << ->
1 animal ! <<
{iter 10 ~=}{
" " <<
{iter 1 =}{last}{fnord} ifte
iter 1 - 0 animal ! nl <<
{"She swallowed the " <<
this_iter ! 0 animal ! <<
" to catch the " <<
next_iter ! 0 animal ! nl <<
{iter 2 =}
{8 1 animal ! nl <<}
{fnord}
ifte}
11 iter - 1 -
times}
{fnord}
ifte
"But I don't know why she swallowed the fly\nPerhaps she'll die\n\n" <<}
animals len
times})
(next_iter {10 iter - })
(this_iter {next_iter ! 1 -})
(animal { <- <- animals -> ith -> ith})
-- There are 10 animals
(animals
(("horse" "She's dead of course...\n")
("donkey" "It was rather wonkey! To swallow a")
("cow" "I don't know how she swallowed a")
("goat" "She just opened her throat! And swallowed the")
("pig" "Her mouth was so big, to swallow a")
("dog" "What a hog! To swallow a")
("cat" "Fancy that! She swallowed a")
("bird" "Quite absurd to swallow a")
("spider" "That wriggled and jiggled and tickled inside her")
("fly" " "))))
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
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
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
%== An "ugly" pseudo-array ===%
set pseudo=^
fly/@^
spider/That_wiggled_and_jiggled_and_tickled_inside_her,@^
bird/How_absurd,_to_swallow_a_bird,@^
cat/Imagine_that._She_swallowed_a_cat,@^
dog/What_a_hog_to_swallow_a_dog,@^
goat/She_just_opened_her_throat_and_swallowed_that_goat,@^
cow/I_don't_know_how_she_swallowed_that_cow,@^
horse/She's_dead_of_course...
%== Counting and seperating... ===%
set str=!pseudo!
:count
if "!str!"=="" goto print_song
for /f "tokens=1,* delims=@" %%A in ("!str!") do (
set /a cnt+=1
for /f "tokens=1,2 delims=/" %%C in ("%%A") do (
set animal!cnt!=%%C
set comment!cnt!=%%D
)
set str=%%B
)
goto count
%== Print the song ===%
:print_song
for /l %%i in (1,1,!cnt!) do (
echo There was an old lady who swallowed a !animal%%i!.
if not "!comment%%i!"=="" echo !comment%%i:_= !
if %%i equ !cnt! goto done
for /l %%j in (%%i,-1,2) do (
set/a prev=%%j-1
call set prev_animal=%%animal!prev!%%
echo She swallowed the !animal%%j! to catch the !prev_animal!.
)
echo I don't know why she swallowed the fly.
echo Perhaps she'll die.
echo.
)
:done
pause>nul&exit/b 0 |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
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
| #Wren | Wren | import "/big" for BigRat
import "/str" for Str
import "/fmt" for Fmt
var abbrevs = {
"PAIRs": [4, 2], "SCOres": [3, 20], "DOZens": [3, 12],
"GRoss": [2, 144], "GREATGRoss": [7, 1728], "GOOGOLs": [6, 1e100]
}
var metric = {
"K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18,
"Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36
}
var b = Fn.new { |e| BigRat.two.pow(e) }
var binary = {
"Ki": b.call(10), "Mi": b.call(20), "Gi": b.call(30), "Ti": b.call(40),
"Pi": b.call(50), "Ei": b.call(60), "Zi": b.call(70), "Yi": b.call(80),
"Xi": b.call(90), "Wi": b.call(100), "Vi": b.call(110), "Ui": b.call(120)
}
var googol = BigRat.fromDecimal("1e100")
var fact = Fn.new { |num, d|
var prod = 1
var n = Num.fromString(num)
var i = n
while (i > 0) {
prod = prod * i
i = i - d
}
return prod
}
var parse = Fn.new { |number|
// find index of last digit
var i = number.count - 1
while (i >= 0) {
if (48 <= number.bytes[i] && number.bytes[i] <= 57) break
i = i - 1
}
var num = number[0..i]
num = num.replace(",", "") // get rid of any commas
var suf = Str.upper(number[i+1..-1])
if (suf == "") return BigRat.fromDecimal(num)
if (suf[0] == "!") {
var prod = fact.call(num, suf.count)
return BigRat.new(prod)
}
for (me in abbrevs) {
var kk = Str.upper(me.key)
if (kk.startsWith(suf) && suf.count >= me.value[0]) {
var t1 = BigRat.fromDecimal(num)
var t2 = (me.key != "GOOGOLS") ? BigRat.fromDecimal(me.value[1]) : googol
return t1 * t2
}
}
var bf = BigRat.fromDecimal(num)
for (me in metric) {
var j = 0
while (j < suf.count) {
if (me.key == suf[j]) {
if (j < suf.count-1 && suf[j+1] == "I") {
bf = bf * binary[me.key + "i"]
j = j + 1
} else {
bf = bf * me.value
}
}
j = j + 1
}
}
return bf
}
var process = Fn.new { |numbers|
System.write("numbers = ")
for (number in numbers) Fmt.write("$s ", number)
System.write("\nresults = ")
for (number in numbers) {
var res = parse.call(number)
if (res.isInteger) {
Fmt.write("$,s ", res.toDecimal(50))
} else {
var sres = Fmt.swrite("$,s", res.truncate.toDecimal)
Fmt.write("$s ", sres + res.fraction.abs.toDecimal(50)[1..-1])
}
}
System.print("\n")
}
var numbers = ["2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"]
process.call(numbers)
numbers = ["1,567", "+1.567k", "0.1567e-2m"]
process.call(numbers)
numbers = ["25.123kK", "25.123m", "2.5123e-00002G"]
process.call(numbers)
numbers = ["25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"]
process.call(numbers)
numbers = ["-.25123e-34Vikki", "2e-77gooGols"]
process.call(numbers)
numbers = ["9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!", "9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"]
process.call(numbers) |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Go | Go | package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
units := []string{
"tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer",
}
convs := []float32{
0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,
71.12, 213.36, 10668, 74676,
1, 100, 10000,
}
scanner := bufio.NewScanner(os.Stdin)
for {
for i, u := range units {
fmt.Printf("%2d %s\n", i+1, u)
}
fmt.Println()
var unit int
var err error
for {
fmt.Print("Please choose a unit 1 to 13 : ")
scanner.Scan()
unit, err = strconv.Atoi(scanner.Text())
if err == nil && unit >= 1 && unit <= 13 {
break
}
}
unit--
var value float64
for {
fmt.Print("Now enter a value in that unit : ")
scanner.Scan()
value, err = strconv.ParseFloat(scanner.Text(), 32)
if err == nil && value >= 0 {
break
}
}
fmt.Println("\nThe equivalent in the remaining units is:\n")
for i, u := range units {
if i == unit {
continue
}
fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i])
}
fmt.Println()
yn := ""
for yn != "y" && yn != "n" {
fmt.Print("Do another one y/n : ")
scanner.Scan()
yn = strings.ToLower(scanner.Text())
}
if yn == "n" {
return
}
}
} |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Java | Java | import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;
public class OpenGlExample {
public void run() throws LWJGLException {
Display.setDisplayMode(new DisplayMode(640, 480));
Display.create();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-30, 30, -30, 30, -30, 30);
glMatrixMode(GL_MODELVIEW);
while(!Display.isCloseRequested()) {
render();
Display.update();
}
Display.destroy();
}
public void render() {
glClearColor(0.3f, 0.3f, 0.3f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
glLoadIdentity();
glTranslatef(-15.0f, -15.0f, 0.0f);
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex2f(0.0f, 0.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex2f(30f, 0.0f);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex2f(0.0f, 30.0f);
glEnd();
}
public static void main(String[] args) {
OpenGlExample openGlExmpl = new OpenGlExample();
try {
openGlExmpl.run();
} catch(LWJGLException e) {
System.err.println(e);
}
}
}
|
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Elixir | Elixir | defmodule One_of_n_lines_in_file do
def task do
dict = Enum.reduce(1..1000000, %{}, fn _,acc ->
Map.update( acc, one_of_n(10), 1, &(&1+1) )
end)
Enum.each(Enum.sort(Map.keys(dict)), fn x ->
:io.format "Line ~2w selected: ~6w~n", [x, dict[x]]
end)
end
def one_of_n( n ), do: loop( n, 2, :rand.uniform, 1 )
def loop( max, n, _random, acc ) when n == max + 1, do: acc
def loop( max, n, random, _acc ) when random < (1/n), do: loop( max, n + 1, :rand.uniform, n )
def loop( max, n, _random, acc ), do: loop( max, n + 1, :rand.uniform, acc )
end
One_of_n_lines_in_file.task |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Erlang | Erlang |
-module( one_of_n_lines_in_file ).
-export( [one_of_n/1, task/0] ).
one_of_n( N ) -> loop( N, 2, random:uniform(), 1 ).
task() ->
Dict = lists:foldl( fun update_counter/2, dict:new(), lists:seq(1, 1000000) ),
[io:fwrite("Line ~p selected: ~p~n", [X, dict:fetch(X, Dict)]) || X <- lists:sort(dict:fetch_keys(Dict))].
loop( Max, N, _Random, Acc ) when N =:= Max + 1 -> Acc;
loop( Max, N, Random, _Acc ) when Random < (1/N) -> loop( Max, N + 1, random:uniform(), N );
loop( Max, N, _Random, Acc ) -> loop( Max, N + 1, random:uniform(), Acc ).
update_counter( _N, Dict ) -> dict:update_counter( one_of_n(10), 1, Dict ).
|
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
| #Ruby | Ruby | def order_disjoint(m,n)
print "#{m} | #{n} -> "
m, n = m.split, n.split
from = 0
n.each_slice(2) do |x,y|
next unless y
sd = m[from..-1]
if x > y && (sd.include? x) && (sd.include? y) && (sd.index(x) > sd.index(y))
new_from = m.index(x)+1
m[m.index(x)+from], m[m.index(y)+from] = m[m.index(y)+from], m[m.index(x)+from]
from = new_from
end
end
puts m.join(' ')
end
[
['the cat sat on the mat', 'mat cat'],
['the cat sat on the mat', 'cat mat'],
['A B C A B C A B C' , 'C A C A'],
['A B C A B D A B E' , 'E A D A'],
['A B' , 'B' ],
['A B' , 'B A' ],
['A B B A' , 'B A' ]
].each {|m,n| order_disjoint(m,n)} |
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
| #Lasso | Lasso | define sortarray( // params are set by position
items::array, // required param
ordering::string = 'lexicographic', // optional param
column::integer = 1,
reverse::boolean = false
) => {
// sorting process
local(sorteditems = array)
// Lasso has no build in method to sort an array of arrays by position in the contained arrays
// But a method could be built for it
return #sorteditems
}
define sortarray(
-items::array, // required param
-ordering::string = 'lexicographic', // optional param
-column::integer = 1,
-reverse::boolean = false
) => sortarray(#items, #ordering, #column, #reverse)
local(items = array(
array(10, 'red', 'Volvo'),
array(15, 'gren', 'Ford'),
array(48, 'yellow', 'Kia'),
array(12, 'black', 'Holden'),
array(19, 'brown', 'Fiat'),
array(8, 'pink', 'Batmobile'),
array(74, 'orange', 'Bicycle')
))
sortarray(-items = #items, -reverse)
sortarray(#items) |
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
| #Logo | Logo | to sort :table [:column 1] [:ordering "before?] [:reverse "false]
; ...
end |
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.
| #Haskell | Haskell | Prelude> [1,2,1,3,2] < [1,2,0,4,4,0,0,0]
False |
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
| #XPL0 | XPL0 | include c:\cxpl\codes;
proc Pascal(N); \Display the first N rows of Pascal's triangle
int N; \if N<=0 then nothing is displayed
int Row, I, Old(40), New(40);
[for Row:= 0 to N-1 do
[New(0):= 1;
for I:= 1 to Row do New(I):= Old(I-1) + Old(I);
for I:= 1 to (N-Row-1)*2 do ChOut(0, ^ );
for I:= 0 to Row do
[if New(I)<100 then ChOut(0, ^ );
IntOut(0, New(I));
if New(I)<10 then ChOut(0, ^ );
ChOut(0, ^ );
];
New(Row+1):= 0;
I:= Old; Old:= New; New:= I;
CrLf(0);
];
];
Pascal(13) |
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.
| #Ruby | Ruby | $ syntax expr: .(). + .() is -> 7; |
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.
| #Scala | Scala | $ syntax expr: .(). + .() is -> 7; |
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.
| #Scheme | Scheme | $ syntax expr: .(). + .() is -> 7; |
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.