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/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Peloton | Peloton | <@ SAYFCTLIT>5</@> |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Factor | Factor | ( scratchpad ) 20 even? .
t
( scratchpad ) 35 even? .
f
( scratchpad ) 20 odd? .
f
( scratchpad ) 35 odd? .
t
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Fish | Fish | <v"Please enter a number:"a
>l0)?!vo v < v o<
^ >i:a=?v>i:a=?v$a*+^>"The number is even."ar>l0=?!^>
> >2%0=?^"The number is odd."ar ^ |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Phix | Phix | global function choose(integer n, k)
atom res = 1
for i=1 to k do
res = (res*(n-i+1))/i
end for
return res
end function
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #PHP | PHP | <?php
$n=5;
$k=3;
function factorial($val){
for($f=2;$val-1>1;$f*=$val--);
return $f;
}
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?> |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbers should be in order.
Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.
The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.
See also
Wikipedia, Emirp.
The Prime Pages, emirp.
Wolfram MathWorld™, Emirp.
The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
| #Groovy | Groovy | class Emirp {
//trivial prime algorithm, sub in whatever algorithm you want
static boolean isPrime(long x) {
if (x < 2) return false
if (x == 2) return true
if ((x & 1) == 0) return false
for (long i = 3; i <= Math.sqrt(x); i += 2) {
if (x % i == 0) return false
}
return true
}
static boolean isEmirp(long x) {
String xString = Long.toString(x)
if (xString.length() == 1) return false
if (xString.matches("[24568].*") || xString.matches(".*[24568]")) return false //eliminate some easy rejects
long xR = Long.parseLong(new StringBuilder(xString).reverse().toString())
if (xR == x) return false
return isPrime(x) && isPrime(xR)
}
static void main(String[] args) {
int count = 0
long x = 1
println("First 20 emirps:")
while (count < 20) {
if (isEmirp(x)) {
count++
print(x + " ")
}
x++
}
println("\nEmirps between 7700 and 8000:")
for (x = 7700; x <= 8000; x++) {
if (isEmirp(x)) {
print(x + " ")
}
}
println("\n10,000th emirp:")
x = 1
count = 0
for (; count < 10000; x++) {
if (isEmirp(x)) {
count++
}
}
//--x to fix the last increment from the loop
println(--x)
}
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Ring | Ring |
apple = 0
banana = 1
cherry = 2
see "apple : " + apple + nl
see "banana : " + banana + nl
see "cherry : " + cherry + nl
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Ruby | Ruby | module Fruits
APPLE = 0
BANANA = 1
CHERRY = 2
end
# It is possible to use a symbol if the value is unrelated.
FRUITS = [:apple, :banana, :cherry]
val = :banana
FRUITS.include?(val) #=> true |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Rust | Rust | enum Fruits {
Apple,
Banana,
Cherry
}
enum FruitsWithNumbers {
Strawberry = 0,
Pear = 27,
}
fn main() {
// Access to numerical value by conversion
println!("{}", FruitsWithNumbers::Pear as u8);
} |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #Dart | Dart | main() {
var empty = '';
if (empty.isEmpty) {
print('it is empty');
}
if (empty.isNotEmpty) {
print('it is not empty');
}
} |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #Delphi | Delphi | program EmptyString;
{$APPTYPE CONSOLE}
uses SysUtils;
function StringIsEmpty(const aString: string): Boolean;
begin
Result := aString = '';
end;
var
s: string;
begin
s := '';
Writeln(StringIsEmpty(s)); // True
s := 'abc';
Writeln(StringIsEmpty(s)); // False
end. |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #PicoLisp | PicoLisp | (prinl "myDir is" (and (dir "myDir") " not") " empty") |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #PowerShell | PowerShell |
$path = "C:\Users"
if((Dir $path).Count -eq 0) {
"$path is empty"
} else {
"$path is not empty"
}
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Prolog | Prolog | non_empty_file('.').
non_empty_file('..').
empty_dir(Dir) :-
directory_files(Dir, Files),
maplist(non_empty_file, Files). |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Clojure | Clojure | start_up = proc ()
end start_up |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #CLU | CLU | start_up = proc ()
end start_up |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #friendly_interactive_shell | friendly interactive shell | function entropy
for arg in $argv
set name count_$arg
if not count $$name > /dev/null
set $name 0
set values $values $arg
end
set $name (math $$name + 1)
end
set entropy 0
for value in $values
set name count_$value
set entropy (echo "
scale = 50
p = "$$name" / "(count $argv)"
$entropy - p * l(p)
" | bc -l)
end
echo "$entropy / l(2)" | bc -l
end
entropy (echo 1223334444 | fold -w1) |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math"
"strings"
)
func main(){
fmt.Println(H("1223334444"))
}
func H(data string) (entropy float64) {
if data == "" {
return 0
}
for i := 0; i < 256; i++ {
px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return entropy
} |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Elixir | Elixir | defmodule Ethiopian do
def halve(n), do: div(n, 2)
def double(n), do: n * 2
def even(n), do: rem(n, 2) == 0
def multiply(lhs, rhs) when is_integer(lhs) and lhs > 0 and is_integer(rhs) and rhs > 0 do
multiply(lhs, rhs, 0)
end
def multiply(1, rhs, acc), do: rhs + acc
def multiply(lhs, rhs, acc) do
if even(lhs), do: multiply(halve(lhs), double(rhs), acc),
else: multiply(halve(lhs), double(rhs), acc+rhs)
end
end
IO.inspect Ethiopian.multiply(17, 34) |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #Phix | Phix | with javascript_semantics
function equilibrium(sequence s)
atom lower_sum = 0,
higher_sum = sum(s)
sequence res = {}
for i=1 to length(s) do
higher_sum -= s[i]
if lower_sum=higher_sum then
res &= i
end if
lower_sum += s[i]
end for
return res
end function
?equilibrium({-7,1,5,2,-4,3,0})
|
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #PHP | PHP | <?php
$arr = array(-7, 1, 5, 2, -4, 3, 0);
function getEquilibriums($arr) {
$right = array_sum($arr);
$left = 0;
$equilibriums = array();
foreach($arr as $key => $value){
$right -= $value;
if($left == $right) $equilibriums[] = $key;
$left += $value;
}
return $equilibriums;
}
echo "# results:\n";
foreach (getEquilibriums($arr) as $r) echo "$r, ";
?> |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #Nim | Nim |
# Brute force approach
import times
# assumes an array of non-decreasing positive integers
proc binarySearch(a : openArray[int], target : int) : int =
var left, right, mid : int
left = 0
right = len(a) - 1
while true :
if left > right : return 0 # no match found
mid = (left + right) div 2
if a[mid] < target :
left = mid + 1
elif a[mid] > target :
right = mid - 1
else :
return mid # match found
var
p5 : array[250, int]
sum = 0
y, t1 : int
let t0 = cpuTime()
for i in 1 .. 249 :
p5[i] = i * i * i * i * i
for x0 in 1 .. 249 :
for x1 in 1 .. x0 - 1 :
for x2 in 1 .. x1 - 1 :
for x3 in 1 .. x2 - 1 :
sum = p5[x0] + p5[x1] + p5[x2] + p5[x3]
y = binarySearch(p5, sum)
if y > 0 :
t1 = int((cputime() - t0) * 1000.0)
echo "Time : ", t1, " milliseconds"
echo $x0 & "^5 + " & $x1 & "^5 + " & $x2 & "^5 + " & $x3 & "^5 = " & $y & "^5"
quit()
if y == 0 :
echo "No solution was found"
|
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Perl | Perl | sub factorial
{
my $n = shift;
my $result = 1;
for (my $i = 1; $i <= $n; ++$i)
{
$result *= $i;
};
$result;
}
# using a .. range
sub factorial {
my $r = 1;
$r *= $_ for 1..shift;
$r;
} |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Forth | Forth | : odd? ( n -- ? ) 1 and ; |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Tue May 21 20:22:56
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt
!gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics f.f08 -o f
! n odd even
!-6 F T
!-5 T F
!-4 F T
!-3 T F
!-2 F T
!-1 T F
! 0 F T
! 1 T F
! 2 F T
! 3 T F
! 4 F T
! 5 T F
! 6 F T
! -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 n
! F T F T F T F T F T F T F odd
! T F T F T F T F T F T F T even
!
!Compilation finished at Tue May 21 20:22:56
module bit0parity
interface odd
module procedure odd_scalar, odd_list
end interface
interface even
module procedure even_scalar, even_list
end interface
contains
logical function odd_scalar(a)
implicit none
integer, intent(in) :: a
odd_scalar = btest(a, 0)
end function odd_scalar
logical function even_scalar(a)
implicit none
integer, intent(in) :: a
even_scalar = .not. odd_scalar(a)
end function even_scalar
function odd_list(a) result(rv)
implicit none
integer, dimension(:), intent(in) :: a
logical, dimension(size(a)) :: rv
rv = btest(a, 0)
end function odd_list
function even_list(a) result(rv)
implicit none
integer, dimension(:), intent(in) :: a
logical, dimension(size(a)) :: rv
rv = .not. odd_list(a)
end function even_list
end module bit0parity
program oe
use bit0parity
implicit none
integer :: i
integer, dimension(13) :: j
write(6,'(a2,2a8)') 'n', 'odd', 'even'
write(6, '(i2,2l5)') (i, odd_scalar(i), even_scalar(i), i=-6,6)
do i=-6, 6
j(i+7) = i
end do
write(6, '((13i3),a8/(13l3),a8/(13l3),a8)') j, 'n', odd(j), 'odd', even(j), 'even'
end program oe
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Picat | Picat | binomial_it(N,K) = Res =>
if K < 0 ; K > N then
R = 0
else
R = 1,
foreach(I in 0..K-1)
R := R * (N-I) // (I+1)
end
end,
Res = R. |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #PicoLisp | PicoLisp | (de binomial (N K)
(let f
'((N)
(if (=0 N) 1 (apply * (range 1 N))) )
(/
(f N)
(* (f (- N K)) (f K)) ) ) ) |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbers should be in order.
Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.
The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.
See also
Wikipedia, Emirp.
The Prime Pages, emirp.
Wolfram MathWorld™, Emirp.
The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
| #Haskell | Haskell | #!/usr/bin/env runghc
import Data.HashSet (HashSet, fromList, member)
import Data.List
import Data.Numbers.Primes
import System.Environment
import System.Exit
import System.IO
-- optimization mentioned on the talk page
startDigOK :: Integer -> Bool
startDigOK n = head (show n) `elem` "1379"
-- infinite list of primes that have an acceptable first digit
filtPrimes :: [Integer]
filtPrimes = filter startDigOK primes
-- finite list of primes that have an acceptable first digit and
-- are the specified number of digits in length
nDigsFPr :: Integer -> [Integer]
nDigsFPr n =
takeWhile (< hi) $ dropWhile (< lo) filtPrimes
where lo = 10 ^ (n - 1)
hi = 10 ^ n
-- hash set of the filtered primes of the specified number of digits
nDigsFPrHS :: Integer -> HashSet Integer
nDigsFPrHS n = fromList $ nDigsFPr n
-- infinite list of hash sets, where each hash set contains primes of
-- a specific number of digits, i. e. index 2 contains 2 digit primes,
-- index 3 contains 3 digit primes, etc.
-- Don't access index 0, because it will return an error
fPrByDigs :: [HashSet Integer]
fPrByDigs = map nDigsFPrHS [0 ..]
isEmirp :: Integer -> Bool
isEmirp n =
let revStr = reverse $ show n
reversed = read revStr
hs = fPrByDigs !! length revStr
in (startDigOK n) && (reversed /= n) && (reversed `member` hs)
emirps :: [Integer]
emirps = filter isEmirp primes
emirpSlice :: Integer -> Integer -> [Integer]
emirpSlice from to =
genericTake numToTake $ genericDrop numToDrop emirps
where
numToDrop = from - 1
numToTake = 1 + to - from
emirpValues :: Integer -> Integer -> [Integer]
emirpValues lo hi =
dropWhile (< lo) $ takeWhile (<= hi) emirps
usage = do
name <- getProgName
putStrLn $ "usage: " ++ name ++ " lo hi [slice | values]"
exitFailure
main = do
hSetBuffering stdout NoBuffering
args <- getArgs
fixedArgs <- case length args of
1 -> return $ args ++ args ++ ["slice"]
2 -> return $ args ++ ["slice"]
3 -> return args
_ -> usage
let lo = read $ fixedArgs !! 0
hi = read $ fixedArgs !! 1
case fixedArgs !! 2 of
"slice" -> print $ emirpSlice lo hi
"values" -> print $ emirpValues lo hi
_ -> usage |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Scala | Scala | sealed abstract class Fruit
case object Apple extends Fruit
case object Banana extends Fruit
case object Cherry extends Fruit
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Scheme | Scheme | (define apple 0)
(define banana 1)
(define cherry 2)
(define (fruit? atom)
(or (equal? 'apple atom)
(equal? 'banana atom)
(equal? 'cherry atom))) |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Seed7 | Seed7 | const type: fruits is new enum
apple, banana, cherry
end enum; |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #DWScript | DWScript | var s : String;
s := ''; // assign an empty string (can also use "")
if s = '' then
PrintLn('empty');
s := 'hello';
if s <> '' then
PrintLn('not empty'); |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #Dyalect | Dyalect | var str = "" |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #PureBasic | PureBasic | Procedure isDirEmpty(path$)
If Right(path$, 1) <> "\": path$ + "\": EndIf
Protected dirID = ExamineDirectory(#PB_Any, path$, "*.*")
Protected result
If dirID
result = 1
While NextDirectoryEntry(dirID)
If DirectoryEntryType(dirID) = #PB_DirectoryEntry_File Or (DirectoryEntryName(dirID) <> "." And DirectoryEntryName(dirID) <> "..")
result = 0
Break
EndIf
Wend
FinishDirectory(dirID)
EndIf
ProcedureReturn result
EndProcedure
Define path$, result$
path$ = PathRequester("Choose a path", "C:\")
If path$
If isDirEmpty(path$)
result$ = " is empty."
Else
result$ = " is not empty."
EndIf
MessageRequester("Empty directory test", #DQUOTE$ + path$ + #DQUOTE$ + result$)
EndIf |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Python | Python | import os;
if os.listdir(raw_input("directory")):
print "not empty"
else:
print "empty"
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #R | R |
is_dir_empty <- function(path){
if(length(list.files(path)) == 0)
print("This folder is empty")
}
is_dir_empty(path)
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #COBOL | COBOL | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #CoffeeScript | CoffeeScript | |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #Go | Go | package main
import (
"fmt"
"math"
"strings"
)
func main(){
fmt.Println(H("1223334444"))
}
func H(data string) (entropy float64) {
if data == "" {
return 0
}
for i := 0; i < 256; i++ {
px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return entropy
} |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Emacs_Lisp | Emacs Lisp | (defun even-p (n)
(= (mod n 2) 0))
(defun halve (n)
(floor n 2))
(defun double (n)
(* n 2))
(defun ethiopian-multiplication (l r)
(let ((sum 0))
(while (>= l 1)
(unless (even-p l)
(setq sum (+ r sum)))
(setq l (halve l))
(setq r (double r)))
sum)) |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #Picat | Picat | equilibrium_index1(A, Ix) =>
append(Front, [_|Back], A),
sum(Front) = sum(Back),
Ix = length(Front)+1. % give 1 based index |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #PicoLisp | PicoLisp | (de equilibria (Lst)
(make
(let Sum 0
(for ((I . L) Lst L (cdr L))
(and (= Sum (sum prog (cdr L))) (link I))
(inc 'Sum (car L)) ) ) ) ) |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #Oforth | Oforth | : eulerSum
| i j k l ip jp kp |
250 loop: i [
i 5 pow ->ip
i 1 + 250 for: j [
j 5 pow ip + ->jp
j 1 + 250 for: k [
k 5 pow jp + ->kp
k 1 + 250 for: l [
kp l 5 pow + 0.2 powf dup asInteger == ifTrue: [ [ i, j, k, l ] println ]
]
]
]
] ; |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Peylang | Peylang |
-- calculate factorial
chiz a = 5;
chiz n = 1;
ta a >= 2
{
n *= a;
a -= 1;
}
chaap n;
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim n As Integer
Do
Print "Enter an integer or 0 to finish : ";
Input "", n
If n = 0 Then
Exit Do
ElseIf n Mod 2 = 0 Then
Print "Your number is even"
Print
Else
Print "Your number is odd"
Print
End if
Loop
End |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #PL.2FI | PL/I |
binomial_coefficients:
procedure options (main);
declare (n, k) fixed;
get (n, k);
put (coefficient(n, k));
coefficient: procedure (n, k) returns (fixed decimal (15));
declare (n, k) fixed;
return (fact(n)/ (fact(n-k) * fact(k)) );
end coefficient;
fact: procedure (n) returns (fixed decimal (15));
declare n fixed;
declare i fixed, f fixed decimal (15);
f = 1;
do i = 1 to n;
f = f * i;
end;
return (f);
end fact;
end binomial_coefficients;
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #PowerShell | PowerShell |
function choose($n,$k) {
if($k -le $n -and 0 -le $k) {
$numerator = $denominator = 1
0..($k-1) | foreach{
$numerator *= ($n-$_)
$denominator *= ($_ + 1)
}
$numerator/$denominator
} else {
"$k is greater than $n or lower than 0"
}
}
choose 5 3
choose 2 1
choose 10 10
choose 10 2
choose 10 8
|
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbers should be in order.
Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.
The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.
See also
Wikipedia, Emirp.
The Prime Pages, emirp.
Wolfram MathWorld™, Emirp.
The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
| #J | J | emirp =: (] #~ ~: *. 1 p: ]) |.&.:":"0 NB. Input is array of primes |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbers should be in order.
Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.
The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.
See also
Wikipedia, Emirp.
The Prime Pages, emirp.
Wolfram MathWorld™, Emirp.
The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
| #Java | Java | public class Emirp{
//trivial prime algorithm, sub in whatever algorithm you want
public static boolean isPrime(long x){
if(x < 2) return false;
if(x == 2) return true;
if((x & 1) == 0) return false;
for(long i = 3; i <= Math.sqrt(x);i+=2){
if(x % i == 0) return false;
}
return true;
}
public static boolean isEmirp(long x){
String xString = Long.toString(x);
if(xString.length() == 1) return false;
if(xString.matches("[24568].*") || xString.matches(".*[24568]")) return false; //eliminate some easy rejects
long xR = Long.parseLong(new StringBuilder(xString).reverse().toString());
if(xR == x) return false;
return isPrime(x) && isPrime(xR);
}
public static void main(String[] args){
int count = 0;
long x = 1;
System.out.println("First 20 emirps:");
while(count < 20){
if(isEmirp(x)){
count++;
System.out.print(x + " ");
}
x++;
}
System.out.println("\nEmirps between 7700 and 8000:");
for(x = 7700; x <= 8000; x++){
if(isEmirp(x)){
System.out.print(x +" ");
}
}
System.out.println("\n10,000th emirp:");
for(x = 1, count = 0;count < 10000; x++){
if(isEmirp(x)){
count++;
}
}
//--x to fix the last increment from the loop
System.out.println(--x);
}
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Shen | Shen | (tc +)
(datatype fruit
if (element? Fruit [apple banana cherry])
_____________
Fruit : fruit;) |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Sidef | Sidef | enum {Apple, Banana, Cherry}; # numbered 0 through 2 |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Slate | Slate | define: #Fruit &parents: {Cloneable}.
Fruit traits define: #Apple -> Fruit clone.
Fruit traits define: #Banana -> Fruit clone.
Fruit traits define: #Cherry -> Fruit clone. |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Standard_ML | Standard ML | datatype fruit =
Apple
| Banana
| Cherry |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | local :e ""
if not e:
!print "an empty string"
if e:
!print "not an empty string" |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #EasyLang | EasyLang | a$ = ""
if a$ = ""
print "empty"
.
if a$ <> ""
print "no empty"
. |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Racket | Racket |
#lang racket
(empty? (directory-list "some-directory"))
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Raku | Raku | sub dir-is-empty ($d) { not dir $d } |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #REXX | REXX | /*REXX pgm checks to see if a directory is empty; if not, lists entries.*/
parse arg xdir; if xdir='' then xdir='\someDir' /*Any DIR? Use default.*/
@.=0 /*default in case ADDRESS fails. */
trace off /*suppress REXX err msg for fails*/
address system 'DIR' xdir '/b' with output stem @. /*issue the DIR cmd.*/
if rc\==0 then do /*an error happened?*/
say '***error!*** from DIR' xDIR /*indicate que pasa.*/
say 'return code=' rc /*show the ret Code.*/
exit rc /*exit with the RC.*/
end /* [↑] bad address.*/
#[email protected] /*number of entries.*/
if #==0 then #=' no ' /*use a word, ¬zero.*/
say center('directory ' xdir " has " # ' entries.',79,'─')
exit @.0+rc /*stick a fork in it, we're done.*/ |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Common_Lisp | Common Lisp | () |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Component_Pascal | Component Pascal |
MODULE Main;
END Main.
|
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #Groovy | Groovy | String.metaClass.getShannonEntrophy = {
-delegate.inject([:]) { map, v -> map[v] = (map[v] ?: 0) + 1; map }.values().inject(0.0) { sum, v ->
def p = (BigDecimal)v / delegate.size()
sum + p * Math.log(p) / Math.log(2)
}
} |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Erlang | Erlang | -module(ethopian).
-export([multiply/2]).
halve(N) ->
N div 2.
double(N) ->
N * 2.
even(N) ->
(N rem 2) == 0.
multiply(LHS,RHS) when is_integer(Lhs) and Lhs > 0 and
is_integer(Rhs) and Rhs > 0 ->
multiply(LHS,RHS,0).
multiply(1,RHS,Acc) ->
RHS+Acc;
multiply(LHS,RHS,Acc) ->
case even(LHS) of
true ->
multiply(halve(LHS),double(RHS),Acc);
false ->
multiply(halve(LHS),double(RHS),Acc+RHS)
end. |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #PowerShell | PowerShell |
function Get-EquilibriumIndex ( $Sequence )
{
$Indexes = 0..($Sequence.Count - 1)
$EqulibriumIndex = @()
ForEach ( $TestIndex in $Indexes )
{
$Left = 0
$Right = 0
ForEach ( $Index in $Indexes )
{
If ( $Index -lt $TestIndex ) { $Left += $Sequence[$Index] }
ElseIf ( $Index -gt $TestIndex ) { $Right += $Sequence[$Index] }
}
If ( $Left -eq $Right )
{
$EqulibriumIndex += $TestIndex
}
}
return $EqulibriumIndex
}
|
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #Prolog | Prolog | equilibrium_index(List, Index) :-
append(Front, [_|Back], List),
sumlist(Front, Sum),
sumlist(Back, Sum),
length(Front, Len),
Index is Len. |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #PARI.2FGP | PARI/GP | forvec(v=vector(4,i,[0,250]), if(ispower(v[1]^5+v[2]^5+v[3]^5+v[4]^5,5,&n), print(n" "v)), 2) |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Phix | Phix | global function factorial(integer n)
atom res = 1
while n>1 do
res *= n
n -= 1
end while
return res
end function
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Frink | Frink | isEven[x is isInteger] := getBit[x,0] == 0
isOdd[x is isInteger] := getBit[x,0] == 1 |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Futhark | Futhark |
fun main(x: int): bool = (x & 1) == 0
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #PureBasic | PureBasic | Procedure Factor(n)
Protected Result=1
While n>0
Result*n
n-1
Wend
ProcedureReturn Result
EndProcedure
Macro C(n,k)
(Factor(n)/(Factor(k)*factor(n-k)))
EndMacro
If OpenConsole()
Print("Enter value n: "): n=Val(Input())
Print("Enter value k: "): k=Val(Input())
PrintN("C(n,k)= "+str(C(n,k)))
Print("Press ENTER to quit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbers should be in order.
Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.
The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.
See also
Wikipedia, Emirp.
The Prime Pages, emirp.
Wolfram MathWorld™, Emirp.
The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
| #JavaScript | JavaScript | function isPrime(n) {
if (!(n % 2) || !(n % 3)) return 0;
var p = 1;
while (p * p < n) {
if (n % (p += 4) == 0 || n % (p += 2) == 0) {
return false
}
}
return true
}
function isEmirp(n) {
var s = n.toString();
var r = s.split("").reverse().join("");
return r != n && isPrime(n) && isPrime(r);
}
function main() {
var out = document.getElementById("content");
var c = 0;
var x = 11;
var last;
var str;
while (c < 10000) {
if (isEmirp(x)) {
c += 1;
// first twenty emirps
if (c == 1) {
str = "<p>" + x;
}
else if (c < 20) {
str += " " + x;
}
else if (c == 20) {
out.innerHTML = str + " " + x + "</p>";
}
// all emirps between 7,700 and 8,000
else if (7700 <= x && x <= 8001) {
if (last < 7700) {
str = "<p>" + x;
} else {
str += " " + x;
}
}
else if (x > 7700 && last < 8001) {
out.innerHTML += str + "</p>";
}
// the 10,000th emirp
else if (c == 10000) {
out.innerHTML += "<p>" + x + "</p>";
}
last = x;
}
x += 2;
}
}
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Swift | Swift | enum Fruit {
case Apple
case Banana
case Cherry
}
// or
enum Fruit {
case Apple, Banana, Cherry
}
enum Season : Int {
case Winter = 1
case Spring = 2
case Summer = 3
case Autumn = 4
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Tcl | Tcl | proc enumerate {name values} {
interp alias {} $name: {} lsearch $values
interp alias {} $name@ {} lindex $values
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Toka | Toka | needs enum
0 enum| apple banana carrot |
10 enum| foo bar baz | |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #Elena | Elena | import extensions;
public program()
{
auto s := emptyString;
if (s.isEmpty())
{ console.printLine("'", s, "' is empty") };
if (s.isNonempty())
{ console.printLine("'", s, "' is not empty") }
} |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #Elixir | Elixir |
empty_string = ""
not_empty_string = "a"
empty_string == ""
# => true
String.length(empty_string) == 0
# => true
byte_size(empty_string) == 0
# => true
not_empty_string == ""
# => false
String.length(not_empty_string) == 0
# => false
byte_size(not_empty_string) == 0
# => false
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Ring | Ring |
myList = dir("C:\Ring\bin")
if len(myList) > 0 see "C:\Ring\bin is not empty" + nl
else see "C:\Ring\bin is empty" + nl ok
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Ruby | Ruby | Dir.entries("testdir").empty? |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Run_BASIC | Run BASIC | files #f, DefaultDir$ + "\*.*" ' open some directory.
print "hasanswer: ";#f HASANSWER() ' if it has an answer it is not MT
print "rowcount: ";#f ROWCOUNT() ' if not MT, how many files? |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Rust | Rust | use std::fs::read_dir;
use std::error::Error;
fn main() {
for path in std::env::args().skip(1) { // iterate over the arguments, skipping the first (which is the executable)
match read_dir(path.as_str()) { // try to read the directory specified
Ok(contents) => {
let len = contents.collect::<Vec<_>>().len(); // calculate the amount of items in the directory
if len == 0 {
println!("{} is empty", path);
} else {
println!("{} is not empty", path);
}
},
Err(e) => { // If the attempt failed, print the corresponding error msg
println!("Failed to read directory \"{}\": {}", path, e.description());
}
}
}
} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Computer.2Fzero_Assembly | Computer/zero Assembly | STP |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Crystal | Crystal | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #D | D | void main() {} |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #Haskell | Haskell | import Data.List
main = print $ entropy "1223334444"
entropy :: (Ord a, Floating c) => [a] -> c
entropy = sum . map lg . fq . map genericLength . group . sort
where lg c = -c * logBase 2 c
fq c = let sc = sum c in map (/ sc) c |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #Icon_and_Unicon | Icon and Unicon | procedure main(a)
s := !a | "1223334444"
write(H(s))
end
procedure H(s)
P := table(0.0)
every P[!s] +:= 1.0/*s
every (h := 0.0) -:= P[c := key(P)] * log(P[c],2)
return h
end |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #ERRE | ERRE | PROGRAM ETHIOPIAN_MULT
FUNCTION EVEN(A)
EVEN=(A+1) MOD 2
END FUNCTION
FUNCTION HALF(A)
HALF=INT(A/2)
END FUNCTION
FUNCTION DOUBLE(A)
DOUBLE=2*A
END FUNCTION
BEGIN
X=17 Y=34 TOT=0
WHILE X>=1 DO
PRINT(X,)
IF EVEN(X)=0 THEN TOT=TOT+Y PRINT(Y) ELSE PRINT END IF
X=HALF(X) Y=DOUBLE(Y)
END WHILE
PRINT("=",TOT)
END PROGRAM
|
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #PureBasic | PureBasic | If OpenConsole()
Define i, c=CountProgramParameters()-1
For i=0 To c
Define j, LSum=0, RSum=0
For j=0 To c
If j<i
LSum+Val(ProgramParameter(j))
ElseIf j>i
RSum+Val(ProgramParameter(j))
EndIf
Next j
If LSum=RSum: PrintN(Str(i)): EndIf
Next i
EndIf |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #Python | Python | def eqindex2Pass(data):
"Two pass"
suml, sumr, ddelayed = 0, sum(data), 0
for i, d in enumerate(data):
suml += ddelayed
sumr -= d
ddelayed = d
if suml == sumr:
yield i |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #Pascal | Pascal | program Pot5Test;
{$IFDEF FPC} {$MODE DELPHI}{$ELSE]{$APPTYPE CONSOLE}{$ENDIF}
type
tTest = double;//UInt64;{ On linux 32Bit double is faster than Uint64 }
var
Pot5 : array[0..255] of tTest;
res,tmpSum : tTest;
x0,x1,x2,x3, y : NativeUint;//= Uint32 or 64 depending on OS xx-Bit
i : byte;
BEGIN
For i := 1 to 255 do
Pot5[i] := (i*i*i*i)*Uint64(i);
For x0 := 1 to 250-3 do
For x1 := x0+1 to 250-2 do
For x2 := x1+1 to 250-1 do
Begin
//set y here only, because pot5 is strong monoton growing,
//therefor the sum is strong monoton growing too.
y := x2+2;// aka x3+1
tmpSum := Pot5[x0]+Pot5[x1]+Pot5[x2];
For x3 := x2+1 to 250 do
Begin
res := tmpSum+Pot5[x3];
while (y< 250) AND (res > Pot5[y]) do
inc(y);
IF y > 250 then BREAK;
if res = Pot5[y] then
writeln(x0,'^5+',x1,'^5+',x2,'^5+',x3,'^5 = ',y,'^5');
end;
end;
END.
|
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Phixmonti | Phixmonti | /# recursive #/
def factorial
dup 1 > if
dup 1 - factorial *
else
drop 1
endif
enddef
/# iterative #/
def factorial2
1 swap for * endfor
enddef
0 22 2 tolist for
"Factorial(" print dup print ") = " print factorial2 print nl
endfor |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Form_Open()
Dim sAnswer, sMessage As String
sAnswer = InputBox("Input an integer", "Odd or even")
If IsInteger(sAnswer) Then
If Odd(Val(sAnswer)) Then sMessage = "' is an odd number"
If Even(Val(sAnswer)) Then sMessage = "' is an even number"
Else
sMessage = "' does not compute!!"
Endif
Print "'" & sAnswer & sMessage
End |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Python | Python | def binomialCoeff(n, k):
result = 1
for i in range(1, k+1):
result = result * (n-i+1) / i
return result
if __name__ == "__main__":
print(binomialCoeff(5, 3)) |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #Quackery | Quackery | [ tuck - over
1 swap times
[ over i + 1+ * ]
nip swap times
[ i 1+ / ] ] is binomial ( n n --> )
5 3 binomial echo |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbers should be in order.
Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.
The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.
See also
Wikipedia, Emirp.
The Prime Pages, emirp.
Wolfram MathWorld™, Emirp.
The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
| #jq | jq | def is_prime:
if . == 2 then true
else
2 < . and . % 2 == 1 and
(. as $in
| (($in + 1) | sqrt) as $m
| [false, 3] | until( .[0] or .[1] > $m; [$in % .[1] == 0, .[1] + 2])
| .[0]
| not)
end ;
def relatively_prime:
.[0] as $n
| .[1] as $primes
| ($n | sqrt) as $s
| (.[1] | length) as $length
| [0, true]
| until( .[0] > $length or ($primes[.[0]] > $s) or .[1] == false;
[.[0] + 1, ($n % $primes[.[0]] != 0)] )
| .[1] ;
def primes:
# The helper function, next, has arity 0 for tail recursion optimization;
# its input must be an array of primes of length at least 2,
# the last also being the greatest.
def next:
. as $previous
| .[length-1] as $last
| [(2 + $last), $previous]
| until( relatively_prime ; .[0] += 2) as $nextp
| ( $previous + [$nextp[0]] );
2, ([2,3] | recurse( next ) | .[-1]) ; |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #VBA | VBA |
'this enumerates from 0
Enum fruits
apple
banana
cherry
End Enum
'here we use our own enumeration
Enum fruits2
pear = 5
mango = 10
kiwi = 20
pineapple = 20
End Enum
Sub test()
Dim f As fruits
f = apple
Debug.Print "apple equals "; f
Debug.Print "kiwi equals "; kiwi
Debug.Print "cherry plus kiwi plus pineapple equals "; cherry + kiwi + pineapple
End Sub
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Visual_Basic_.NET | Visual Basic .NET | ' Is this valid?!
Enum fruits
apple
banana
cherry
End Enum
' This is correct
Enum fruits
apple = 0
banana = 1
cherry = 2
End Enum |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Wren | Wren | var APPLE = 1
var ORANGE = 2
var PEAR = 3
var CHERRY = 4
var BANANA = CHERRY + 1
var GRAPE = BANANA + 1
System.print([APPLE, ORANGE, PEAR, CHERRY, BANANA, GRAPE]) |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #Emacs_Lisp | Emacs Lisp | (setq str "") ;; empty string literal
(if (= 0 (length str))
(message "string is empty"))
(if (/= 0 (length str))
(message "string is not empty")) |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
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
| #Erlang | Erlang |
1> S = "". % erlang strings are actually lists, so the empty string is the same as the empty list [].
[]
2> length(S).
0
3> case S of [] -> empty; [H|T] -> not_empty end.
empty
4> case "aoeu" of [] -> empty; [H|T] -> not_empty end.
not_empty
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Scala | Scala | import java.io.File
def isDirEmpty(file:File) : Boolean =
return file.exists && file.isDirectory && file.list.isEmpty |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "osfiles.s7i";
const func boolean: dirEmpty (in string: dirName) is
return fileType(dirName) = FILE_DIR and length(readDir(dirName)) = 0;
const proc: main is func
begin
writeln(dirEmpty("somedir"));
end func; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.