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/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
| #Oberon | Oberon |
MODULE Binomial;
IMPORT
Out;
PROCEDURE For*(n,k: LONGINT): LONGINT;
VAR
i,m,r: LONGINT;
BEGIN
ASSERT(n > k);
r := 1;
IF k > n DIV 2 THEN m := n - k ELSE m := k END;
FOR i := 1 TO m DO
r := r * (n - m + i) DIV i
END;
RETURN r
END For;
BEGIN
Out.Int(For(5,2),0);Out.Ln
END Binomial.
|
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).
| #Factor | Factor | USING: io kernel lists lists.lazy math.extras math.parser
math.primes sequences ;
FROM: prettyprint => . pprint ;
IN: rosetta-code.emirp
: rev ( n -- n' )
number>string reverse string>number ;
: emirp? ( n -- ? )
dup rev [ = not ] [ [ prime? ] bi@ ] 2bi and and ;
: nemirps ( n -- seq )
0 lfrom [ emirp? ] lfilter ltake list>array ;
: print-seq ( seq -- )
[ pprint bl ] each nl ;
: part1 ( -- )
"First 20 emirps:" print 20 nemirps print-seq ;
: part2 ( -- )
"Emirps between 7700 and 8000:" print
7700 ... 8000 [ emirp? ] filter print-seq ;
: part3 ( -- )
"10,000th emirp:" print 10,000 nemirps last . ;
: main ( -- )
part1 nl part2 nl part3 ;
MAIN: main |
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).
| #Forth | Forth |
#! /usr/bin/gforth-fast
: reverse ( n -- n )
0 swap
begin
10 /mod >r swap 10 * +
r> dup 0= until drop ;
: 2^ 1 swap lshift ;
create 235-wheel 6 c, 4 c, 2 c, 4 c, 2 c, 4 c, 6 c, 2 c,
does> swap 7 and + c@ ;
0 1 2constant init-235 \ roll 235 wheel at position 1
2 11 2constant emirp-start \ starting position to roll wheel for emirp search.
: next-235 over 235-wheel + swap 1+ swap ;
\ check that n is prime excepting multiples of 2, 3, 5.
: sq dup * ;
: wheel-prime? ( n -- f )
>r init-235 begin
next-235
dup sq r@ > if rdrop 2drop true exit then
r@ over mod 0= if rdrop 2drop false exit then
again ;
: prime? ( n -- f )
dup 2 <
if drop false
else
dup 1 and 0=
if 2 =
else dup 3 mod 0=
if 3 =
else dup 5 mod 0=
if 5 =
else wheel-prime?
then
then
then
then ;
: emirp? ( n -- f )
dup reverse 2dup <>
swap prime? and
swap wheel-prime? and ;
: next-emirp ( m n -- m' n' )
begin
next-235
dup emirp? until ;
: task1
cr ." The first 20 emirps are: " 0 { count }
emirp-start begin
next-emirp dup .
count 1+ dup to count
20 = until 2drop ;
: task2
cr ." emirps between 7700 and 8000: "
emirp-start begin
next-emirp dup 7700 8000 within if dup . then
dup 8000 > until 2drop ;
: task3
cr ." The 10,000th emirp is " 0 { count }
emirp-start begin
next-emirp
count 1+ dup to count
10000 = until nip . ;
task1 task2 task3
cr bye
|
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:
y
2
=
x
3
+
a
x
+
b
{\displaystyle y^{2}=x^{3}+ax+b}
a and b are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation +, such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:
P + Q + R = 0
Here 0 (zero) is the infinity point, for which the x and y values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points P, Q and R, we define the sum S = P + Q as the point (possibly the infinity point) such that S, R and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
S is thus defined as the symmetric of R towards the x axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the a and b parameters of secp256k1, i.e. respectively zero and seven.
Hint: You might need to define a "doubling" function, that returns P+P for any given point P.
Extra credit: define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point P and integer n, the point P + P + ... + P (n times).
| #Tcl | Tcl | set C 7
set zero {x inf y inf}
proc tcl::mathfunc::cuberoot n {
# General power operator doesn't like negative, but its defined for root3
expr {$n>=0 ? $n**(1./3) : -((-$n)**(1./3))}
}
proc iszero p {
dict with p {}
return [expr {$x > 1e20 || $x<-1e20}]
}
proc negate p {
dict set p y [expr {-[dict get $p y]}]
}
proc double p {
if {[iszero $p]} {return $p}
dict with p {}
set L [expr {(3.0 * $x**2) / (2.0 * $y)}]
set rx [expr {$L**2 - 2.0 * $x}]
set ry [expr {$L * ($x - $rx) - $y}]
return [dict create x $rx y $ry]
}
proc add {p q} {
if {[dict get $p x]==[dict get $q x] && [dict get $p y]==[dict get $q y]} {
return [double $p]
}
if {[iszero $p]} {return $q}
if {[iszero $q]} {return $p}
dict with p {}
set L [expr {([dict get $q y]-$y) / ([dict get $q x]-$x)}]
dict set r x [expr {$L**2 - $x - [dict get $q x]}]
dict set r y [expr {$L * ($x - [dict get $r x]) - $y}]
return $r
}
proc multiply {p n} {
set r $::zero
for {set i 1} {$i <= $n} {incr i $i} {
if {$i & int($n)} {
set r [add $r $p]
}
set p [double $p]
}
return $r
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #PicoLisp | PicoLisp | (de enum "Args"
(mapc def "Args" (range 1 (length "Args"))) ) |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #PL.2FI | PL/I |
define ordinal animal (frog, gnu, elephant, snake);
define ordinal color (red value (1), green value (3), blue value (5));
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #PowerShell | PowerShell |
Enum fruits {
Apple
Banana
Cherry
}
[fruits]::Apple
[fruits]::Apple + 1
[fruits]::Banana + 1
|
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
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | EMPTYSTR
; Demonstrate how to assign an empty string to a variable.
set x = ""
; Demonstrate how to check that a string is empty.
; Length 0 is empty; equality/pattern check are 1=T, 0=F
write !,"Assigned x to null value. Tests: "
write !,"String length: "_$length(x)_", Equals null: "_(x = "")_", Empty pattern: "_(x?."") ; length 0 is empty
; Demonstrate how to check that a string is not empty. Same as above.
set x = " " ;assign to a space - not null
write !!,"Assigned x to a single blank space. Tests: "
write !,"String length: "_$length(x)_", Equals null: "_(x = "")_", Empty pattern: "_(x?."")
quit |
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
| #Clojure | Clojure |
(def x "") ;x is "globally" declared to be the empty string
(let [x ""]
;x is bound to the empty string within the let
)
(= x "") ;true if x is the empty string
(not= x "") ;true if x is not the empty string
|
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.
| #Nanoquery | Nanoquery | def isempty(dirname)
return len(new(Nanoquery.IO.File).listDir(dirname)) = 0
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.
| #Nemerle | Nemerle | using System.IO;
using System.Console;
module EmptyDirectory
{
IsDirectoryEmpty(dir : string) : bool
{
Directory.GetFileSystemEntries(dir).Length == 0
}
Main(args : array[string]) : void
{
foreach (dir in args) {
when (Directory.Exists(dir)) {
WriteLine("{0} {1} empty.", dir, if (IsDirectoryEmpty(dir)) "is" else "is not");
}
}
}
} |
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.
| #NewLISP | NewLISP |
(define (empty-dir? path-to-check)
(empty? (clean (lambda (x) (or (= "." x) (= ".." x))) (directory path-to-check)))
)
|
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.
| #Nim | Nim | import os, rdstdin
var empty = true
for f in walkDir(readLineFromStdin "directory: "):
empty = false
break
echo empty |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #bootBASIC | bootBASIC | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #BQN | BQN | ∞ |
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
| #Euler_Math_Toolbox | Euler Math Toolbox | >function entropy (s) ...
$ v=strtochar(s);
$ m=getmultiplicities(unique(v),v);
$ m=m/sum(m);
$ return sum(-m*logbase(m,2))
$endfunction
>entropy("1223334444")
1.84643934467 |
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.23 | F# | open System
let ld x = Math.Log x / Math.Log 2.
let entropy (s : string) =
let n = float s.Length
Seq.groupBy id s
|> Seq.map (fun (_, vals) -> float (Seq.length vals) / n)
|> Seq.fold (fun e p -> e - p * ld p) 0.
printfn "%f" (entropy "1223334444") |
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
| #E | E | def halve(&x) { x //= 2 }
def double(&x) { x *= 2 }
def even(x) { return x %% 2 <=> 0 }
def multiply(var a, var b) {
var ab := 0
while (a > 0) {
if (!even(a)) { ab += b }
halve(&a)
double(&b)
}
return ab
} |
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.
| #OCaml | OCaml | let lst = [ -7; 1; 5; 2; -4; 3; 0 ]
let sum = List.fold_left ( + ) 0 lst
let () =
let rec aux acc i left right = function
| x::xs ->
let right = right - x in
let acc = if left = right then i::acc else acc in
aux acc (succ i) (left + x) right xs
| [] -> List.rev acc
in
let res = aux [] 0 0 sum lst in
print_string "Results:";
List.iter (Printf.printf " %d") res;
print_newline() |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Standard_ML | Standard ML | OS.Process.getEnv "HOME" |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Stata | Stata | display "`:env PATH'"
display "`:env USERNAME'"
display "`:env USERPROFILE'" |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Swift | Swift | print("USER: \(ProcessInfo.processInfo.environment["USER"] ?? "Not set")")
print("PATH: \(ProcessInfo.processInfo.environment["PATH"] ?? "Not set")") |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #True_BASIC | True BASIC | ASK #1: ACCESS TYPE$
ASK BACK red
ASK COLOR red
ASK COLOR MIX (2) red, green, blue
ASK CURSOR vble1, vble2
ASK #2: DATUM TYPE$
ASK DIRECTORY dir$
ASK #3: ERASABLE TYPE$
ASK #4: FILESIZE vble09
ASK #5: FILETYPE vble10
ASK FREE MEMORY vble11
ASK #61: MARGIN vble12
ASK MAX COLOR vble13
ASK MAX CURSOR vble1, vble2
ASK MODE vble15$
ASK NAME vble16$
ASK #7: ORGANIZATION vble17$
ASK PIXELS vble1, vble2
ASK #8: POINTER vble19$
ASK #9: RECORD vble20
ASK #1: RECSIZE vble21
ASK #2: RECTYPE vble22$
ASK SCREEN vble1, vble2, vble3, vble4
ASK #3: SETTER vble24$
ASK TEXT JUSTIFY vble1$, vble2$
ASK WINDOW vble1, vble2, vble3, vble4
ASK #4: ZONEWIDTH vble27 |
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.
| #Lua | Lua | -- Fast table search (only works if table values are in order)
function binarySearch (t, n)
local start, stop, mid = 1, #t
while start < stop do
mid = math.floor((start + stop) / 2)
if n == t[mid] then
return mid
elseif n < t[mid] then
stop = mid - 1
else
start = mid + 1
end
end
return nil
end
-- Test Euler's sum of powers conjecture
function euler (limit)
local pow5, sum = {}
for i = 1, limit do pow5[i] = i^5 end
for x0 = 1, limit do
for x1 = 1, x0 do
for x2 = 1, x1 do
for x3 = 1, x2 do
sum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3]
if binarySearch(pow5, sum) then
print(x0 .. "^5 + " .. x1 .. "^5 + " .. x2 .. "^5 + " .. x3 .. "^5 = " .. sum^(1/5) .. "^5")
return true
end
end
end
end
end
return false
end
-- Main procedure
if euler(249) then
print("Time taken: " .. os.clock() .. " seconds")
else
print("Looks like he was right after all...")
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
| #Panda | Panda | fun fac(n) type integer->integer
product{{1..n}}
1..10.fac
|
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.
| #Erlang | Erlang | %% Implemented by Arjun Sunel
-module(even_odd).
-export([main/0]).
main()->
test(8).
test(N) ->
if (N rem 2)==1 ->
io:format("odd\n");
true ->
io:format("even\n")
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
| #OCaml | OCaml |
let binomialCoeff n p =
let p = if p < n -. p then p else n -. p in
let rec cm res num denum =
(* this method partially prevents overflow.
* float type is choosen to have increased domain on 32-bits computer,
* however algorithm ensures an integral result as long as it is possible
*)
if denum <= p then cm ((res *. num) /. denum) (num -. 1.) (denum +. 1.)
else res in
cm 1. n 1.
|
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
| #Oforth | Oforth | : binomial(n, k) | i | 1 k loop: i [ n i - 1+ * i / ] ; |
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).
| #Fortran | Fortran | MODULE BAG !A mixed assortment.
INTEGER MSG !I/O unit number to share about.
INTEGER PF16LIMIT,PF32LIMIT,NP !Know that P(3512) = 32749, the last within two's complement 16-bit integers.
PARAMETER (PF16LIMIT = 3512, PF32LIMIT = 4793) !32749² = 1,072,497,001; the integer limit is 2,147,483,647 in 32-bit integers.
INTEGER*2 PRIME16(PF16LIMIT) !P(4792) = 46337, next is 46349 and 46337² = 2,147,117,569.
INTEGER*4 PRIME32(PF16LIMIT + 1:PF32LIMIT) !Let the compiler track the offsets.
DATA NP,PRIME16(1),PRIME16(2)/2,2,3/ !But, start off with this. Note that Prime(NP) is odd...
INTEGER NGP,NNP,NIP !Invocation counts.
DATA NGP,NNP,NIP/3*0/ !Starting at zero.
CONTAINS !Some co-operating routines.
RECURSIVE INTEGER FUNCTION GETPRIME(I) !They are numbered. As if in an array Prime(i).
Chooses from amongst two arrays, of sizes known from previous work.
INTEGER I !The desired index.
INTEGER P !A potential prime.
INTEGER MP !Counts beyond NP.
NGP = NGP + 1 !Another try.
IF (I.LE.0) THEN !A silly question?
GETPRIME = -666 !This should cause trouble!
ELSE IF (I.LE.NP) THEN !I have a little list.
IF (I.LE.PF16LIMIT) THEN !Well actually, two little lists.
GETPRIME = PRIME16(I) !So, direct access from this.
ELSE !Or, for the larger numbers,
GETPRIME = PRIME32(I) !This.
END IF !So much for previous effort.
ELSE IF (I.LE.PF32LIMIT) THEN !My list may not yet be completely filled.
MP = NP !This is the last stashed so far.
P = GETPRIME(NP) !I'll ask me to figure out where this is stashed.
10 P = NEXTPRIME(P) !Go for the next one along.
MP = MP + 1 !Advance my count.
IF (MP.LT.I) GO TO 10 !Are we there yet?
GETPRIME = P !Yep.
ELSE !But, my list may be too short.
WRITE (MSG,*) "Hic!",I !So, give an indication.
STOP "Too far..." !And quit.
END IF !For factoring 32-bit, need only 4792 elements.
END FUNCTION GETPRIME !This is probably faster than reading from a monster disc file.
SUBROUTINE STASHPRIME(P) !Saves a value in the stash.
INTEGER P !The prime to be stashed.
NP = NP + 1 !Count another in.
IF (NP.LE.PF16LIMIT) THEN !But, where to?
PRIME16(NP) = P !The short list.
ELSE IF (NP.LE.PF32LIMIT) THEN!Or,
PRIME32(NP) = P !The long list (which is shorter)
ELSE !Or,
STOP "Stash overflow!" !Oh dear.
END IF !It is stashed.
END SUBROUTINE STASHPRIME !The checking should be redundant.
INTEGER FUNCTION FINDPRIME(IT) !Via binary search.
INTEGER IT !The value to be found.
INTEGER L,R,P !Assistants.
L = 0 !This is the *exclusive bounds* version.
R = NP + 1 !Thus, L = first - 1; R = Last + 1.
1 P = (R - L)/2 !Probe offset.
IF (P.LE.0) THEN !No span?
FINDPRIME = -L !Not found. IT follows Prime(L).
RETURN !Escape.
END IF !But otherwise,
P = P + L !Convert to an index into array PRIME, manifested via GETPRIME.
IF (IT - GETPRIME(P)) 2,4,3 !Compare... Three way result.
2 R = P; GO TO 1 !IT < PRIME(P): move R back.
3 L = P; GO TO 1 !PRIME(P) < IT: move L forward.
4 FINDPRIME = P !PRIME(P) = IT: Found here!
END FUNCTION FINDPRIME !Simple and fast.
RECURSIVE INTEGER FUNCTION NEXTPRIME(P) !Some effort may ensue.
Checks the stash in PRIME in the hope of finding the next prime directly, otherwise advances from P.
Collates a stash of primes in PRIME16 and PRIME32, advancing NP from 2 to PF32LIMIT as it goes.
INTEGER P !Not necessarily itself a prime number.
INTEGER PI !A possibly prime increment.
INTEGER IT !A finger.
NNP = NNP + 1 !Another try
IF (P.LE.1) THEN !Dodge annoying effects. Otherwise, FINDPRIME(P) would be zero.
PI = 2 !The first prime is known. Because P precedes Prime(1).
ELSE !The first stashed value is two.
IT = (ABS(FINDPRIME(P))) !The stash is ordered, and P = 2 will be found at 1.
IF (IT.LT.NP) THEN !Before my last-known prime? FINDPRIME(4) = -2 as it follows Prime(NP=2).
PI = GETPRIME(IT + 1) !Yes, so I know the next along already.
ELSE !Otherwise, it is past Prime(NP). and IT = NP thanks to the ABS.
IF (NP.LT.PF32LIMIT) THEN !If my stash is not yet filled,
PI = GETPRIME(IT) !I want to start with its last entry, known to be an odd number.
ELSE !So that I can stash each next prime along the way.
PI = P !Otherwise, start with P.
IF (MOD(PI,2).EQ.0) PI = PI - 1 !And some suspicion.
END IF !So much for a starting position.
DO WHILE (PI.LE.P) !Perhaps I must go further.
11 PI = PI + 2 !Advance to a possibility.
IF (.NOT.ISPRIME(PI)) GO TO 11 !Discard it?
IF (IT.EQ.NP .AND. IT.LT.PF32LIMIT) THEN !Am I one further on from NP?
CALL STASHPRIME(PI) !Yes, and there is space to stash it.
IT = IT + 1 !Ready for the next one along, if it comes.
END IF !All are candidates for my stash.
END DO !Perhaps this prime will be big enough.
END IF !It may be a long way past PRIME(NP).
END IF !And I may have filled my stash along the way.
NEXTPRIME = PI !Take that.
END FUNCTION NEXTPRIME !Messy.
RECURSIVE LOGICAL FUNCTION ISPRIME(N) !Checks an arbitrary number, though limited by INTEGER size.
Crunches up to SQRT(N), and at worst needs to be able to reach Prime(4793) = 46349; greater than SQRT(2147483647) = 46340·95...
INTEGER N !The number.
INTEGER I,F,Q !Assistants.
NIP = NIP + 1 !Another try.
IF (N.LT.2) THEN !Dodge annoyances.
ISPRIME = .FALSE. !Such as N = 1, and the first F being 2.
ELSE !Otherwise, some effort.
ISPRIME = .FALSE. !The usual result.
I = 1 !Start at the start with PRIME(1).
10 F = GETPRIME(I) !Thus, no special case with F = 2.
Q = N/F !So, how many times? (Truncation, remember)
IF (Q .GE. F) THEN !Q < F means F² > N.
IF (Q*F .EQ. N) RETURN !A factor is found!
I = I + 1 !Very well.
GO TO 10 !Try the next possible factor.
END IF !And if we get through all that,
ISPRIME = .TRUE. !It is a prime number.
END IF !And we're done.
END FUNCTION ISPRIME !After a lot of divisions.
INTEGER FUNCTION ESREVER(IT,BASE) !Reversed digits.
INTEGER IT !The number to be reversed. Presumably positive.
INTEGER BASE !For the numerology.
INTEGER N,R !Assistants.
IF (BASE.LE.1) STOP "Base 2 at least!" !Ah, distrust.
N = IT !A copy I can damage.
R = 0 !Here we go.
DO WHILE(N.GT.0) !A digit remains?
R = R*BASE + MOD(N,BASE) !Yes. Grab the low-order digit of N.
N = N/BASE !And reduce N by another power of BASE.
END DO !Test afresh.
ESREVER = R !That's it.
END FUNCTION ESREVER !Easy enough.
SUBROUTINE EMIRP(BASE,N1,N2,I1,I2) !Two-part interface.
INTEGER BASE !Avoid decimalist chauvinism.
INTEGER N1,N2 !Count span to show those found.
INTEGER I1,I2 !Search span.
INTEGER N !Counter.
INTEGER P,R !Assistants.
WRITE (MSG,1) N1,N2,BASE,I1,I2 !Declare the purpose.
1 FORMAT ("Show the first ",I0," to ",I0, !So as to encompass
& " emirP numbers (base ",I0,") between ",I0," and ",I0) !The specified options.
N = 0 !None found so far.
P = I1 - 1 !Syncopation. The starting position might itself be a prime number.
Chase another emirP.
10 P = NEXTPRIME(P) !I want the next prime.
IF (P.LT.I1) GO TO 10 !Up to the starting mark yet?
IF (P.GT.I2) GO TO 900 !Past the finishing mark?
R = ESREVER(P,BASE) !Righto, a candidate.
IF (P .EQ. R) GO TO 10 !Palindromes are rejected.
IF (.NOT.ISPRIME(R)) GO TO 10 !As are non-primes.
N = N + 1 !Aha, a success!
c if (mod(n,100) .eq. 0) then
c write (6,66) N,P,R,NP,NGP,NNP,NIP
c 66 format ("N=",I5,",p=",I6,",R=",I6,",NP=",I6,3I12)
c end if
IF (N.GE.N1) WRITE (6,*) P,R !Are we within the count span?
IF (N.LT.N2) GO TO 10 !Past the end?
Closedown.
900 WRITE (MSG,901) NP,GETPRIME(NP) !Might be of interest.
901 FORMAT ("Stashed up to Prime(",I0,") = ",I0,/)
END SUBROUTINE EMIRP !Well, that was odd.
END MODULE BAG !Mixed.
PROGRAM POKE !Now put it all to the test.
USE BAG !With ease.
MSG = 6 !Standard output.
CALL EMIRP(10, 1, 20, 1, 1000) !These parameters
CALL EMIRP(10, 1, 28,7700, 8000) !Meet the specifiction
CALL EMIRP(10,10000,10000, 1,1000000) !Of three separate invocations.
END !Whee! |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:
y
2
=
x
3
+
a
x
+
b
{\displaystyle y^{2}=x^{3}+ax+b}
a and b are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation +, such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:
P + Q + R = 0
Here 0 (zero) is the infinity point, for which the x and y values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points P, Q and R, we define the sum S = P + Q as the point (possibly the infinity point) such that S, R and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
S is thus defined as the symmetric of R towards the x axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the a and b parameters of secp256k1, i.e. respectively zero and seven.
Hint: You might need to define a "doubling" function, that returns P+P for any given point P.
Extra credit: define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point P and integer n, the point P + P + ... + P (n times).
| #Vlang | Vlang | import math
const b_coeff = 7
struct Pt {
x f64
y f64
}
fn zero() Pt {
return Pt{math.inf(1), math.inf(1)}
}
fn is_zero(p Pt) bool {
return p.x > 1e20 || p.x < -1e20
}
fn neg(p Pt) Pt {
return Pt{p.x, -p.y}
}
fn dbl(p Pt) Pt {
if is_zero(p) {
return p
}
l := (3 * p.x * p.x) / (2 * p.y)
x := l*l - 2*p.x
return Pt{
x: x,
y: l*(p.x-x) - p.y,
}
}
fn add(p Pt, q Pt) Pt {
if p.x == q.x && p.y == q.y {
return dbl(p)
}
if is_zero(p) {
return q
}
if is_zero(q) {
return p
}
l := (q.y - p.y) / (q.x - p.x)
x := l*l - p.x - q.x
return Pt{
x: x,
y: l*(p.x-x) - p.y,
}
}
fn mul(mut p Pt, n int) Pt {
mut r := zero()
for i := 1; i <= n; i <<= 1 {
if i&n != 0 {
r = add(r, p)
}
p = dbl(p)
}
return r
}
fn show(s string, p Pt) {
print("$s")
if is_zero(p) {
println("Zero")
} else {
println("(${p.x:.3f}, ${p.y:.3f})")
}
}
fn from_y(y f64) Pt {
return Pt{
x: math.cbrt(y*y - b_coeff),
y: y,
}
}
fn main() {
mut a := from_y(1)
b := from_y(2)
show("a = ", a)
show("b = ", b)
c := add(a, b)
show("c = a + b = ", c)
d := neg(c)
show("d = -c = ", d)
show("c + d = ", add(c, d))
show("a + b + d = ", add(a, add(b, d)))
show("a * 12345 = ", mul(mut a, 12345))
} |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:
y
2
=
x
3
+
a
x
+
b
{\displaystyle y^{2}=x^{3}+ax+b}
a and b are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation +, such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:
P + Q + R = 0
Here 0 (zero) is the infinity point, for which the x and y values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points P, Q and R, we define the sum S = P + Q as the point (possibly the infinity point) such that S, R and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
S is thus defined as the symmetric of R towards the x axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the a and b parameters of secp256k1, i.e. respectively zero and seven.
Hint: You might need to define a "doubling" function, that returns P+P for any given point P.
Extra credit: define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point P and integer n, the point P + P + ... + P (n times).
| #Wren | Wren | import "/fmt" for Fmt
var C = 7
class Pt {
static zero { Pt.new(1/0, 1/0) }
construct new(x, y) {
_x = x
_y = y
}
x { _x }
y { _y }
static fromNum(n) { Pt.new((n*n - C).cbrt, n) }
isZero { x > 1e20 || x < -1e20 }
double {
if (isZero) return this
var l = 3 * x * x / (2 * y)
var t = l*l - 2*x
return Pt.new(t, l*(x - t) - y)
}
- { Pt.new(x, -y) }
+(other) {
if (other.type != Pt) Fiber.abort("Argument must be a Pt object.")
if (x == other.x && y == other.y) return double
if (isZero) return other
if (other.isZero) return this
var l = (other.y - y) / (other.x - x)
var t = l*l - x - other.x
return Pt.new(t, l*(x-t) - y)
}
*(n) {
if (n.type != Num || !n.isInteger) {
Fiber.abort("Argument must be an integer.")
}
var r = Pt.zero
var p = this
var i = 1
while (i <= n) {
if ((i & n) != 0) r = r + p
p = p.double
i = i << 1
}
return r
}
toString { isZero ? "Zero" : Fmt.swrite("($0.3f, $0.3f)", x, y) }
}
var a = Pt.fromNum(1)
var b = Pt.fromNum(2)
var c = a + b
var d = -c
System.print("a = %(a)")
System.print("b = %(b)")
System.print("c = a + b = %(c)")
System.print("d = -c = %(d)")
System.print("c + d = %(c + d)")
System.print("a + b + d = %(a + b + d)")
System.print("a * 12345 = %(a * 12345)") |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Prolog | Prolog | fruit(apple,1).
fruit(banana,2).
fruit(cherry,4).
write_fruit_name(N) :-
fruit(Name,N),
format('It is a ~p~n', Name). |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #PureBasic | PureBasic | Enumeration
#Apple
#Banana
#Cherry
EndEnumeration |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Python | Python | >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>>
>>> # Explicit
>>> class Contact2(Enum):
FIRST_NAME = 1
LAST_NAME = 2
PHONE = 3
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>> |
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
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. EMPTYSTR.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 str PIC X(10).
PROCEDURE DIVISION.
Begin.
* * Assign an empty string.
INITIALIZE str.
* * Or
MOVE " " TO str.
IF (str = " ")
DISPLAY "String is empty"
ELSE
DISPLAY "String is not empty"
END-IF.
STOP RUN.
|
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
| #CoffeeScript | CoffeeScript |
isEmptyString = (s) ->
# Returns true iff s is an empty string.
# (This returns false for non-strings as well.)
return true if s instanceof String and s.length == 0
s == ''
empties = ["", '', new String()]
non_empties = [new String('yo'), 'foo', {}]
console.log (isEmptyString(v) for v in empties) # [true, true, true]
console.log (isEmptyString(v) for v in non_empties) # [false, false, false]
console.log (s = '') == "" # true
console.log new String() == '' # false, due to underlying JavaScript's distinction between objects and primitives
|
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.
| #Objeck | Objeck | function : IsEmptyDirectory(dir : String) ~ Bool {
return Directory->List(dir)->Size() = 0;
} |
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.
| #OCaml | OCaml | let is_dir_empty d =
Sys.readdir 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.
| #ooRexx | ooRexx | Call test 'D:\nodir' /* no such directory */
Call test 'D:\edir' /* an empty directory */
Call test 'D:\somedir' /* directory with 2 files */
Call test 'D:\somedir','S' /* directory with 3 files */
Exit
test: Parse Arg fd,nest
If SysIsFileDirectory(fd)=0 Then
Say 'Directory' fd 'not found'
Else Do
ret=SysFileTree(fd'\*.*','X', 'F'nest)
If x.0=0 Then
say 'Directory' fd 'is empty'
Else Do
If nest='' Then
say 'Directory' fd 'contains' x.0 'files'
Else
say 'Directory' fd 'contains' x.0 'files (some nested)'
End
End
Return |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Bracmat | Bracmat | touch empty
bracmat 'get$empty' |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Brainf.2A.2A.2A | Brainf*** | Empty program |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Brlcad | Brlcad | opendb empty.g y |
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
| #Factor | Factor | USING: assocs kernel math math.functions math.statistics
prettyprint sequences ;
IN: rosetta-code.entropy
: shannon-entropy ( str -- entropy )
[ length ] [ histogram >alist [ second ] map ] bi
[ swap / ] with map
[ dup log 2 log / * ] map-sum neg ;
"1223334444" shannon-entropy .
"Factor is my favorite programming language." shannon-entropy . |
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
| #Forth | Forth | : flog2 ( f -- f ) fln 2e fln f/ ;
create freq 256 cells allot
: entropy ( str len -- f )
freq 256 cells erase
tuck
bounds do
i c@ cells freq +
1 swap +!
loop
0e
256 0 do
i cells freq + @ ?dup if
s>f dup s>f f/
fdup flog2 f* f-
then
loop
drop ;
s" 1223334444" entropy f. \ 1.84643934467102 ok
|
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
| #EasyLang | EasyLang | x = 17
y = 34
tot = 0
while x >= 1
write x
write "\t"
if (x + 1) mod 2 = 0
tot += y
print y
else
print ""
.
x = x div 2
y = 2 * y
.
write "=\t"
print tot |
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.
| #Oforth | Oforth | : equilibrium(l)
| ls rs i e |
0 ->ls
l sum ->rs
ListBuffer new l size loop: i [
l at(i) ->e
rs e - dup ->rs ls == ifTrue: [ i over add ]
ls e + ->ls
] ; |
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.
| #PARI.2FGP | PARI/GP | equilib(v)={
my(a=sum(i=2,#v,v[i]),b=0,u=[]);
for(i=1,#v-1,
if(a==b, u=concat(u,i));
b+=v[i];
a-=v[i+1]
);
if(b,u,concat(u,#v))
}; |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Tcl | Tcl | $env(HOME) |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #TXR | TXR | @(next :env)
@(collect)
@VAR=@VAL
@(end) |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #UNIX_Shell | UNIX Shell | echo "$HOME" |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Ursa | Ursa | import "system"
out (system.getenv "HOME") endl console |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Ursala | Ursala | #import std
#executable ('parameterized','')
showenv = <.file$[contents: --<''>]>+ %smP+ ~&n-={'TERM','SHELL','X11BROWSER'}*~+ ~environs |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Sort[FindInstance[
x0^5 + x1^5 + x2^5 + x3^5 == y^5 && x0 > 0 && x1 > 0 && x2 > 0 &&
x3 > 0, {x0, x1, x2, x3, y}, Integers][[1, All, -1]]] |
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
| #PARI.2FGP | PARI/GP | fact(n)=if(n<2,1,n*fact(n-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.
| #ERRE | ERRE | PROGRAM ODD_EVEN
! works for -2^15 <= n% < 2^15
FUNCTION ISODD%(N%)
ISODD%=(N% AND 1)<>0
END FUNCTION
! works for -2^38 <= n# <= 2^38
FUNCTION ISODD#(N#)
ISODD#=N#<>2*INT(N#/2)
END FUNCTION
BEGIN
IF ISODD%(14) THEN PRINT("14 is odd") ELSE PRINT("14 is even") END IF
IF ISODD%(15) THEN PRINT("15 is odd") ELSE PRINT("15 is even") END IF
IF ISODD#(9876543210) THEN PRINT("9876543210 is odd") ELSE PRINT("9876543210 is even") END IF
IF ISODD#(9876543211) THEN PRINT("9876543211 is odd") ELSE PRINT("9876543211 is even") END IF
END PROGRAM
|
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.
| #Euphoria | Euphoria |
include std/math.e
for i = 1 to 10 do
? {i, is_even(i)}
end for
|
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
| #Oz | Oz | declare
fun {BinomialCoeff N K}
{List.foldL {List.number 1 K 1}
fun {$ Z I}
Z * (N-I+1) div I
end
1}
end
in
{Show {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
| #PARI.2FGP | PARI/GP | binomial(5,3) |
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).
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isPrime(n As UInteger) As Boolean
If n < 2 Then Return False
If n Mod 2 = 0 Then Return n = 2
If n Mod 3 = 0 Then Return n = 3
Dim d As Integer = 5
While d * d <= n
If n Mod d = 0 Then Return False
d += 2
If n Mod d = 0 Then Return False
d += 4
Wend
Return True
End Function
Function reverseNumber(n As UInteger) As UInteger
If n < 10 Then Return n
Dim As Integer sum = 0
While n > 0
sum = 10 * sum + (n Mod 10)
n \= 10
Wend
Return sum
End Function
Function isEmirp(n As UInteger) As Boolean
If Not isPrime(n) Then Return False
Dim As UInteger reversed = reverseNumber(n)
Return reversed <> n AndAlso CInt(isPrime(reversed))
End Function
' We can immediately rule out all primes from 2 to 11 as these are palindromic
' and not therefore Emirp primes
Print "The first 20 Emirp primes are :"
Dim As UInteger count = 0, i = 13
Do
If isEmirp(i) Then
Print Using "####"; i;
count + = 1
End If
i += 2
Loop Until count = 20
Print : Print
Print "The Emirp primes between 7700 and 8000 are:"
i = 7701
Do
If isEmirp(i) Then Print Using "#####"; i;
i += 2
Loop While i < 8000
Print : Print
Print "The 10,000th Emirp prime is : ";
i = 13 : count = 0
Do
If isEmirp(i) Then count += 1
If count = 10000 Then Exit Do
i += 2
Loop
Print i
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:
y
2
=
x
3
+
a
x
+
b
{\displaystyle y^{2}=x^{3}+ax+b}
a and b are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation +, such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:
P + Q + R = 0
Here 0 (zero) is the infinity point, for which the x and y values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points P, Q and R, we define the sum S = P + Q as the point (possibly the infinity point) such that S, R and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
S is thus defined as the symmetric of R towards the x axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the a and b parameters of secp256k1, i.e. respectively zero and seven.
Hint: You might need to define a "doubling" function, that returns P+P for any given point P.
Extra credit: define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point P and integer n, the point P + P + ... + P (n times).
| #zkl | zkl | const C=7, INFINITY=(0.0).inf;
fcn zero{ T(INFINITY, INFINITY) }
// should be INFINITY, but numeric precision is very much in the way
fcn is_zero(p){ x,_:=p; (x < -1e20 or x > 1e20) }
fcn neg(p){ return(p[0], -p[1]) }
fcn dbl(p){
if(is_zero(p)) return(p);
px,py := p;
L:=(3.0 * px * px) / (2.0 * py);
rx,ry := L * L - 2.0 * px, L * (px - rx) - py;
return(rx,ry);
}
fcn add(p,q){
px,py := p;
qx,qy := q;
if(px == qx and py == qy) return(dbl(p));
if(is_zero(p)) return(q);
if(is_zero(q)) return(p);
L := (qy - py) / (qx - px);
rx,ry := L * L - px - qx, L * (px - rx) - py;
return(rx,ry);
}
fcn mul(p,n){
r := zero();
i:=1; while(i <= n){
if(i.bitAnd(n)) r = add(r,p);
p = dbl(p);
i*=2;
}
r
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #R | R | factor(c("apple", "banana", "cherry"))
# [1] apple banana cherry
# Levels: apple banana cherry |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Racket | Racket |
#lang racket
;; Like other Lisps, Racketeers prefer using symbols directly instead of
;; numeric definitions, and lists of symbols instead of bitwise
;; combinations
(define fruits '(apple banana cherry))
;; In Typed Racket, a type can be defined for a specific set of symbols
;; (define-type Fruit (U 'apple 'banana 'cherry))
;; The conventional approach is possible too, of course
(define APPLE 1)
(define BANANA 2)
(define CHERRY 4)
;; And finally, when dealing with foreign functions it is useful to
;; translate idiomatic Racket values (= symbols) to/from integers.
;; Racket's ffi has two ways to do this -- either an enumeration (for
;; independent integer constants) or a bitmask (intended to represent
;; sets using bitwise or):
(require ffi/unsafe)
(define _fruit (_enum '(APPLE = 1
BANANA
CHERRY = 4)))
(define _fruits (_bitmask '(APPLE = 1
BANANA = 2
CHERRY = 4)))
;; Normally, Racket code will just use plain values (a symbol for the
;; first, and a list of symbols for the second) and the foreign side
;; sees the integers. But do demonstrate this, we can use the primitive
;; raw functionality to see how the translation works:
(require (only-in '#%foreign ctype-scheme->c ctype-c->scheme))
((ctype-scheme->c _fruit) 'CHERRY) ; -> 4
((ctype-scheme->c _fruits) 'CHERRY) ; -> 4
((ctype-scheme->c _fruits) '(APPLE CHERRY)) ; -> 5
((ctype-c->scheme _fruit) 4) ; -> 'CHERRY
((ctype-c->scheme _fruits) 4) ; -> '(CHERRY)
((ctype-c->scheme _fruits) 5) ; -> '(APPLE CHERRY)
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Raku | Raku | enum Fruit <Apple Banana Cherry>; # Numbered 0 through 2.
enum ClassicalElement (
Earth => 5,
'Air', # gets the value 6
'Fire', # gets the value 7
Water => 10,
); |
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
| #Common_Lisp | Common Lisp |
(defparameter *s* "") ;; Binds dynamic variable *S* to the empty string ""
(let ((s "")) ;; Binds the lexical variable S to the empty string ""
(= (length s) 0) ;; Check if the string is empty
(> (length s) 0)) ;; Check if length of string is over 0 (that is: non-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
| #Component_Pascal | Component Pascal |
MODULE EmptyString;
IMPORT StdLog;
PROCEDURE Do*;
VAR
s: ARRAY 64 OF CHAR;
(* s := "" <=> s[0] := 0X => s isEmpty*)
BEGIN
s := "";
StdLog.String("Is 's' empty?:> ");StdLog.Bool(s = "");StdLog.Ln;
StdLog.String("Is not 's' empty?:> ");StdLog.Bool(s # "");StdLog.Ln;
StdLog.Ln;
(* Or *)
s := 0X;
StdLog.String("Is 's' empty?:> ");StdLog.Bool(s = 0X);StdLog.Ln;
StdLog.String("Is not 's' empty?:> ");StdLog.Bool(s # 0X);StdLog.Ln;
StdLog.Ln;
END Do;
END EmptyString.
|
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.
| #PARI.2FGP | PARI/GP | chkdir(d)=extern(concat(["[ -d '",d,"' ]&&ls -A '",d,"'|wc -l||echo -1"])) |
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.
| #Pascal | Pascal | program emptyDirectory(input, output);
type
path = string(1024);
{
\brief determines whether a (hierarchial FS) directory is empty
\param accessVia a possible route to access a directory
\return whether \param accessVia is an empty directory
}
function isEmptyDirectory(protected accessVia: path): Boolean;
var
{ NB: `file` data types without a domain type are non-standard }
directory: bindable file;
FD: bindingType;
begin
{ initialize variables }
unbind(directory);
FD := binding(directory);
FD.name := accessVia;
{ binding to directories is usually not possible }
FD.force := true;
{ the actual test }
bind(directory, FD);
FD := binding(directory);
unbind(directory);
isEmptyDirectory := FD.bound and FD.directory and (FD.links <= 2)
end;
{ === MAIN ============================================================= }
var
s: path;
begin
readLn(s);
writeLn(isEmptyDirectory(s))
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.
| #Perl | Perl | sub dir_is_empty {!<$_[0]/*>} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #C | C | main()
{
return 0;
} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #C.23 | C# | int 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
| #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Tue May 21 21:43:12
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a 1223334444
!gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics f.f08 -o f
! Shannon entropy of 1223334444 is 1.84643936
!
!Compilation finished at Tue May 21 21:43:12
program shannonEntropy
implicit none
integer :: num, L, status
character(len=2048) :: s
num = 1
call get_command_argument(num, s, L, status)
if ((0 /= status) .or. (L .eq. 0)) then
write(0,*)'Expected a command line argument with some length.'
else
write(6,*)'Shannon entropy of '//(s(1:L))//' is ', se(s(1:L))
endif
contains
! algebra
!
! 2**x = y
! x*log(2) = log(y)
! x = log(y)/log(2)
! NB. The j solution
! entropy=: +/@:-@(* 2&^.)@(#/.~ % #)
! entropy '1223334444'
!1.84644
real function se(s)
implicit none
character(len=*), intent(in) :: s
integer, dimension(256) :: tallies
real, dimension(256) :: norm
tallies = 0
call TallyKey(s, tallies)
! J's #/. works with the set of items in the input.
! TallyKey is sufficiently close that, with the merge, gets the correct result.
norm = tallies / real(len(s))
se = sum(-(norm*log(merge(1.0, norm, norm .eq. 0))/log(2.0)))
end function se
subroutine TallyKey(s, counts)
character(len=*), intent(in) :: s
integer, dimension(256), intent(out) :: counts
integer :: i, j
counts = 0
do i=1,len(s)
j = iachar(s(i:i))
counts(j) = counts(j) + 1
end do
end subroutine TallyKey
end program shannonEntropy
|
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
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature {NONE}
make
do
io.put_integer (ethiopian_multiplication (17, 34))
end
ethiopian_multiplication (a, b: INTEGER): INTEGER
-- Product of 'a' and 'b'.
require
a_positive: a > 0
b_positive: b > 0
local
x, y: INTEGER
do
x := a
y := b
from
until
x <= 0
loop
if not is_even_int (x) then
Result := Result + y
end
x := halve_int (x)
y := double_int (y)
end
ensure
Result_correct: Result = a * b
end
feature {NONE}
double_int (n: INTEGER): INTEGER
--Two times 'n'.
do
Result := n * 2
end
halve_int (n: INTEGER): INTEGER
--'n' divided by two.
do
Result := n // 2
end
is_even_int (n: INTEGER): BOOLEAN
--Is 'n' an even integer?
do
Result := n \\ 2 = 0
end
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.
| #Pascal | Pascal | Program EquilibriumIndexDemo(output);
{$IFDEF FPC}{$Mode delphi}{$ENDIF}
function ArraySum(list: array of integer; first, last: integer): integer;
var
i: integer;
begin
Result := 0;
for i := first to last do // not taken if first > last
Result := Result + list[i];
end;
procedure EquilibriumIndex(list: array of integer; offset: integer);
var
i: integer;
begin
for i := low(list) to high(list) do
if ArraySum(list, low(list), i-1) = ArraySum(list, i+1, high(list)) then
write(offset + i:3);
end;
var
{** The base index of the array is fully taken care off and can be any number. **}
numbers: array [1..7] of integer = (-7, 1, 5, 2, -4, 3, 0);
i: integer;
begin
write('List of numbers: ');
for i := low(numbers) to high(numbers) do
write(numbers[i]:3);
writeln;
write('Equilibirum indices: ');
EquilibriumIndex(numbers, low(numbers));
writeln;
end. |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Vlang | Vlang | // Environment variables in V
// v run environment_variables.v
module main
import os
pub fn main() {
print('In the $os.environ().len environment variables, ')
println('\$HOME is set to ${os.getenv('HOME')}')
} |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Vedit_macro_language | Vedit macro language | Get_Environment(10,"PATH")
Message(@10) |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Visual_Basic | Visual Basic | Debug.Print Environ$("PATH") |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Wren | Wren | /* environment_variables.wren */
class Environ {
foreign static variable(name)
}
System.print(Environ.variable("SHELL")) |
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.
| #Microsoft_Small_Basic | Microsoft Small Basic | ' Euler sum of powers conjecture - 03/07/2015
'find: x1^5+x2^5+x3^5+x4^5=x5^5
'-> x1=27 x2=84 x3=110 x4=133 x5=144
maxn=250
For i=1 to maxn
p5[i]=Math.Power(i,5)
EndFor
For x1=1 to maxn-4
For x2=x1+1 to maxn-3
'TextWindow.WriteLine("x1="+x1+", x2="+x2)
For x3=x2+1 to maxn-2
'TextWindow.WriteLine("x1="+x1+", x2="+x2+", x3="+x3)
For x4=x3+1 to maxn-1
'TextWindow.WriteLine("x1="+x1+", x2="+x2+", x3="+x3+", x4="+x4)
x5=x4+1
valx=p5[x5]
sumx=p5[x1]+p5[x2]+p5[x3]+p5[x4]
While x5<=maxn and valx<=sumx
If valx=sumx Then
TextWindow.WriteLine("Found!")
TextWindow.WriteLine("-> "+x1+"^5+"+x2+"^5+"+x3+"^5+"+x4+"^5="+x5+"^5")
TextWindow.WriteLine("x5^5="+sumx)
Goto EndPgrm
EndIf
x5=x5+1
valx=p5[x5]
EndWhile 'x5
EndFor 'x4
EndFor 'x3
EndFor 'x2
EndFor 'x1
EndPgrm: |
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
| #Pascal | Pascal | function factorial(n: integer): integer;
var
i, result: integer;
begin
result := 1;
for i := 2 to n do
result := result * i;
factorial := result
end; |
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.
| #Excel | Excel |
=MOD(33;2)
=MOD(18;2)
|
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.23 | F# | let isEven x =
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
| #Pascal | Pascal | sub binomial {
use bigint;
my ($r, $n, $k) = (1, @_);
for (1 .. $k) { $r *= $n--; $r /= $_ }
$r;
}
print binomial(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
| #Perl | Perl | sub binomial {
use bigint;
my ($r, $n, $k) = (1, @_);
for (1 .. $k) { $r *= $n--; $r /= $_ }
$r;
}
print binomial(5, 3); |
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).
| #Frink | Frink |
isEmirp[x] :=
{
if isPrime[x]
{
s = toString[x]
rev = reverse[s]
return s != rev and isPrime[parseInt[rev]]
}
return false
}
// Functions that return finite and infinite enumerating expressions of emirps
emirps[] := select[primes[], getFunction["isEmirp", 1]]
emirps[begin, end] := select[primes[begin, end], getFunction["isEmirp", 1]]
println["First 20: " + first[emirps[], 20]]
println["Range: " + emirps[7700, 8000]]
println["10000th: " + last[first[emirps[], 10000]]]
|
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).
| #Go | Go | package main
import (
"flag"
"fmt"
"github.com/jbarham/primegen.go" // Sieve of Atkin implementation
"math"
)
// primeCache is a simple cache of small prime numbers, it very
// well might be faster to just regenerate them as needed.
type primeCache struct {
gen *primegen.Primegen
primes []uint64
}
func NewPrimeCache() primeCache {
g := primegen.New()
return primeCache{gen: g, primes: []uint64{g.Next()}}
}
// upto returns a slice of primes <= n.
// The returned slice is shared with all callers, do not modify it!
func (pc *primeCache) upto(n uint64) []uint64 {
if p := pc.primes[len(pc.primes)-1]; p <= n {
for p <= n {
p = pc.gen.Next()
pc.primes = append(pc.primes, p)
}
return pc.primes[:len(pc.primes)-1]
}
for i, p := range pc.primes {
if p > n {
return pc.primes[:i]
}
}
panic("not reached")
}
var cache = NewPrimeCache()
func sqrt(x uint64) uint64 { return uint64(math.Sqrt(float64(x))) }
// isprime does a simple test if n is prime.
// See also math/big.ProbablyPrime().
func isprime(n uint64) bool {
for _, p := range cache.upto(sqrt(n)) {
if n%p == 0 {
return false
}
}
return true
}
func reverse(n uint64) (r uint64) {
for n > 0 {
r = 10*r + n%10
n /= 10
}
return
}
// isEmirp does a simple test if n is Emirp, n must be prime
func isEmirp(n uint64) bool {
r := reverse(n)
return r != n && isprime(r)
}
// EmirpGen is a sequence generator for Emirp primes
type EmirpGen struct {
pgen *primegen.Primegen
nextn uint64
r1l, r1h uint64
r2l, r2h uint64
r3l, r3h uint64
}
func NewEmirpGen() *EmirpGen {
e := &EmirpGen{pgen: primegen.New()}
e.Reset()
return e
}
func (e *EmirpGen) Reset() {
e.pgen.Reset()
e.nextn = 0
// Primes >7 cannot end in 2,4,5,6,8 (leaving 1,3,7)
e.r1l, e.r1h = 20, 30
e.r2l, e.r2h = 40, 70
e.r3l, e.r3h = 80, 90
}
func (e *EmirpGen) next() (n uint64) {
for n = e.pgen.Next(); !isEmirp(n); n = e.pgen.Next() {
// Skip over inpossible ranges
// Benchmarks show this saves ~20% when generating n upto 1e6
switch {
case e.r1l <= n && n < e.r1h:
e.pgen.SkipTo(e.r1h)
case e.r2l <= n && n < e.r2h:
e.pgen.SkipTo(e.r2h)
case e.r3l <= n && n < e.r3h:
e.pgen.SkipTo(e.r3h)
case n > e.r3h:
e.r1l *= 10
e.r1h *= 10
e.r2l *= 10
e.r2h *= 10
e.r3l *= 10
e.r3h *= 10
}
}
return
}
func (e *EmirpGen) Next() (n uint64) {
if n = e.nextn; n != 0 {
e.nextn = 0
return
}
return e.next()
}
func (e *EmirpGen) Peek() uint64 {
if e.nextn == 0 {
e.nextn = e.next()
}
return e.nextn
}
func (e *EmirpGen) SkipTo(nn uint64) {
e.pgen.SkipTo(nn)
e.nextn = 0
return
}
// SequenceGen defines an arbitrary sequence generator.
// Both *primegen.Primegen and *EmirpGen implement this.
type SequenceGen interface {
Next() uint64
Peek() uint64
Reset()
SkipTo(uint64)
//Count(uint64) uint64 // not implemented for *EmirpGen
}
func main() {
var start, end uint64
var n, skip uint
var oneline, primes bool
flag.UintVar(&n, "n", math.MaxUint64, "number of emirps to print")
flag.UintVar(&skip, "skip", 0, "number of emirps to skip")
flag.Uint64Var(&start, "start", 0, "start at x>=start")
flag.Uint64Var(&end, "end", math.MaxUint64, "stop at x<=end")
flag.BoolVar(&oneline, "oneline", false, "output on a single line")
flag.BoolVar(&primes, "primes", false, "generate primes rather than emirps")
flag.Parse()
sep := "\n"
if oneline {
sep = " "
}
// Here's where making SequenceGen an interface comes in handy:
var seq SequenceGen
if primes {
seq = primegen.New()
} else {
seq = NewEmirpGen()
}
for seq.Peek() < start {
seq.Next()
}
for ; skip > 0; skip-- {
seq.Next()
}
for ; n > 0 && seq.Peek() <= end; n-- {
fmt.Print(seq.Next(), sep)
}
if oneline {
fmt.Println()
}
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Raven | Raven | { 'apple' 0 'banana' 1 'cherry' 2 } as fruits |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Retro | Retro | '/examples/enum.retro include
{ 'a=10 'b 'c 'd=998 'e 'f } a:enum
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #REXX | REXX | /*REXX program illustrates a method of enumeration of constants via stemmed arrays. */
fruit.=0 /*the default for all possible "FRUITS." (zero). */
fruit.apple = 65
fruit.cherry = 4
fruit.kiwi = 12
fruit.peach = 48
fruit.plum = 50
fruit.raspberry = 17
fruit.tomato = 8000
fruit.ugli = 2
fruit.watermelon = 0.5 /*◄─────────── could also be specified as: 1/2 */
/*A method of using a list (of some fruits).*/
@fruits= 'apple apricot avocado banana bilberry blackberry blackcurrant blueberry baobab',
'boysenberry breadfruit cantaloupe cherry chilli chokecherry citron coconut',
'cranberry cucumber currant date dragonfruit durian eggplant elderberry fig',
'feijoa gac gooseberry grape grapefruit guava honeydew huckleberry jackfruit',
'jambul juneberry kiwi kumquat lemon lime lingenberry loquat lychee mandarin',
'mango mangosteen nectarine orange papaya passionfruit peach pear persimmon',
'physalis pineapple pitaya pomegranate pomelo plum pumpkin rambutan raspberry',
'redcurrant satsuma squash strawberry tangerine tomato ugli watermelon zucchini'
/*╔════════════════════════════════════════════════════════════════════════════════════╗
║Parental warning: sex is discussed below: PG─13. Most berries don't have "berry" in║
║their name. A berry is a simple fruit produced from a single ovary. Some true ║
║berries are: pomegranate, guava, eggplant, tomato, chilli, pumpkin, cucumber, melon,║
║and citruses. Blueberry is a false berry; blackberry is an aggregate fruit; ║
║and strawberry is an accessory fruit. Most nuts are fruits. The following aren't║
║true nuts: almond, cashew, coconut, macadamia, peanut, pecan, pistachio, and walnut.║
╚════════════════════════════════════════════════════════════════════════════════════╝*/
/* ┌─◄── due to a Central America blight in 1922; it was*/
/* ↓ called the Panama disease (a soil─borne fungus)*/
if fruit.banana=0 then say "Yes! We have no bananas today." /* (sic) */
if fruit.kiwi \=0 then say "We gots " fruit.kiwi ' hairy fruit.' /* " */
if fruit.peach\=0 then say "We gots " fruit.peach ' fuzzy fruit.' /* " */
maxL=length(' fruit ') /*ensure this header title can be shown*/
maxQ=length(' quantity ') /* " " " " " " " */
say
do p =0 for 2 /*the first pass finds the maximums. */
do j=1 for words(@fruits) /*process each of the names of fruits. */
@=word(@fruits, j) /*obtain a fruit name from the list. */
#=value('FRUIT.'@) /* " the quantity of a fruit. */
if \p then do /*is this the first pass through ? */
maxL=max(maxL, length(@)) /*the longest (widest) name of a fruit.*/
maxQ=max(maxQ, length(#)) /*the widest width quantity of fruit. */
iterate /*j*/ /*now, go get another name of a fruit. */
end
if j==1 then say center('fruit', maxL) center("quantity", maxQ)
if j==1 then say copies('─' , maxL) copies("─" , maxQ)
if #\=0 then say right( @ , maxL) right( # , maxQ)
end /*j*/
end /*p*/
/*stick a fork in it, we're all done. */ |
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 | D | import std.array;
bool isEmptyNotNull(in string s) pure nothrow @safe {
return s is "";
}
void main(){
string s1 = null;
string s2 = "";
// the content is the same
assert(!s1.length);
assert(!s2.length);
assert(s1 == "" && s1 == null);
assert(s2 == "" && s2 == null);
assert(s1 == s2);
// but they don't point to the same memory region
assert(s1 is null && s1 !is "");
assert(s2 is "" && s2 !is null);
assert(s1 !is s2);
assert(s1.ptr == null);
assert(*s2.ptr == '\0'); // D string literals are \0 terminated
assert(s1.empty);
assert(s2.isEmptyNotNull());
} |
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.
| #Phix | Phix | without js -- file i/o
procedure test(string filename)
string msg
switch get_file_type(filename) do
case FILETYPE_UNDEFINED: msg = "is UNDEFINED"
case FILETYPE_NOT_FOUND: msg = "is NOT_FOUND"
case FILETYPE_FILE: msg = "is a FILE"
case FILETYPE_DIRECTORY:
integer count = length(filter(vslice(dir(filename),D_NAME),"out",{".",".."}))
msg = iff(count=0?"is an empty directory"
:sprintf("is a directory containing %d files",{count}))
end switch
printf(1,"%s %s\n",{filename,msg})
end procedure
constant tests = {"C:\\xx","C:\\not_there","C:\\Program Files (x86)\\Phix\\p.exe","C:\\Windows"}
for i=1 to length(tests) do
test(tests[i])
end for
|
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.
| #PHP | PHP |
$dir = 'path_here';
if(is_dir($dir)){
//scandir grabs the contents of a directory and array_diff is being used to filter out .. and .
$list = array_diff(scandir($dir), array('..', '.'));
//now we can just use empty to check if the variable has any contents regardless of it's type
if(empty($list)){
echo 'dir is empty';
}
else{
echo 'dir is not empty';
}
}
else{
echo 'not a directory';
}
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #C.2B.2B | C++ | int main(){} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Clean | Clean | module Empty
Start world = world |
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
| #FreeBASIC | FreeBASIC | ' version 25-06-2015
' compile with: fbc -s console
Sub calc_entropy(source As String, base_ As Integer)
Dim As Integer i, sourcelen = Len(source), totalchar(255)
Dim As Double prop, entropy
For i = 0 To sourcelen -1
totalchar(source[i]) += 1
Next
Print "Char count"
For i = 0 To 255
If totalchar(i) = 0 Then Continue For
Print " "; Chr(i); Using " ######"; totalchar(i)
prop = totalchar(i) / sourcelen
entropy = entropy - (prop * Log (prop) / Log(base_))
Next
Print : Print "The Entropy of "; Chr(34); source; Chr(34); " is"; entropy
End Sub
' ------=< MAIN >=------
calc_entropy("1223334444", 2)
Print
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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
| #Ela | Ela | open list number
halve x = x `div` 2
double = (2*)
ethiopicmult a b = sum <| map snd <| filter (odd << fst) <| zip
(takeWhile (>=1) <| iterate halve a)
(iterate double b)
ethiopicmult 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.
| #Perl | Perl | sub eq_index {
my ( $i, $sum, %sums ) = ( 0, 0 );
for (@_) {
push @{ $sums{ $sum * 2 + $_ } }, $i++;
$sum += $_;
}
return join ' ', @{ $sums{$sum} || [] }, "\n";
}
print eq_index qw( -7 1 5 2 -4 3 0 ); # 3 6
print eq_index qw( 2 4 6 ); # (no eq point)
print eq_index qw( 2 9 2 ); # 1
print eq_index qw( 1 -1 1 -1 1 -1 1 ); # 0 1 2 3 4 5 6 |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
int CpuReg, PspSeg, EnvSeg, I, J, C;
char EnvVar;
[CpuReg:= GetReg; \access CPU registers
PspSeg:= CpuReg(9); \get segment address of our PSP
EnvSeg:= Peek(PspSeg,$2C) + Peek(PspSeg,$2D)<<8;
EnvVar:= "PATH"; \environment variable
I:= 0;
loop [J:= 0;
loop [C:= Peek(EnvSeg,I); I:= I+1;
if C = 0 then quit;
if C = EnvVar(J) then
[J:= J+1;
if J = 4 then
[Text(0, EnvVar); \show env. var.
loop [C:= Peek(EnvSeg,I); \ and rest of
I:= I+1; \ its string
if C = 0 then exit;
ChOut(0, C);
];
];
]
else J:= 5; \line must start with environment variable
];
if Peek(EnvSeg,I) = 0 then quit; \double 0 = env. var. not found
];
] |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Yabasic | Yabasic | System.getenv("HOME")
/home/craigd
System.getenv() //--> Dictionary of all env vars |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #zkl | zkl | System.getenv("HOME")
/home/craigd
System.getenv() //--> Dictionary of all env vars |
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.
| #Modula-2 | Modula-2 | MODULE EulerConjecture;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE Pow5(a : LONGINT) : LONGINT;
BEGIN
RETURN a * a * a * a * a
END Pow5;
VAR
buf : ARRAY[0..63] OF CHAR;
a,b,c,d,e,sum,curr : LONGINT;
BEGIN
FOR a:=0 TO 250 DO
FOR b:=a TO 250 DO
IF b=a THEN CONTINUE END;
FOR c:=b TO 250 DO
IF (c=a) OR (c=b) THEN CONTINUE END;
FOR d:=c TO 250 DO
IF (d=a) OR (d=b) OR (d=c) THEN CONTINUE END;
sum := Pow5(a) + Pow5(b) + Pow5(c) + Pow5(d);
FOR e:=d TO 250 DO
IF (e=a) OR (e=b) OR (e=c) OR (e=d) THEN CONTINUE END;
curr := Pow5(e);
IF (sum#0) AND (sum=curr) THEN
FormatString("%l^5 + %l^5 + %l^5 + %l^5 = %l^5\n", buf, a, b, c, d, e);
WriteString(buf)
ELSIF curr > sum THEN
BREAK
END
END;
END;
END;
END;
END;
WriteString("Done");
WriteLn;
ReadChar
END EulerConjecture. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.