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/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #D | D | void main() {
// Named enumeration (commonly used enum in D).
// The underlying type is a 32 bit int.
enum Fruits1 { apple, banana, cherry }
// You can assign an enum to the general type, but not the opposite:
int f1 = Fruits1.banana; // No error.
// Fruits1 f2 = 1; // Error: cannot implicitly convert.
// Anonymous enumeration, as in C, of type 32 bit int.
enum { APPLE, BANANA, CHERRY }
static assert(CHERRY == 2);
// Named enumeration with specified values (int).
enum Fruits2 { apple = 0, banana = 10, cherry = 20 }
// Named enumeration, typed and with specified values.
enum Fruits3 : ubyte { apple = 0, banana = 100, cherry = 200 }
// Named enumeration, typed and with partially specified values.
enum Test : ubyte { A = 2, B, C = 3 }
static assert(Test.B == 3); // Uses the next ubyte, duplicated value.
// This raises a compile-time error for overflow.
// enum Fruits5 : ubyte { apple = 254, banana = 255, cherry }
enum Component {
none,
red = 2 ^^ 0,
green = 2 ^^ 1,
blue = 2 ^^ 2
}
// Phobos BitFlags support all the most common operations on flags.
// Some of the operations are shown below.
import std.typecons: BitFlags;
alias ComponentFlags = BitFlags!Component;
immutable ComponentFlags flagsEmpty;
// Value can be set with the | operator.
immutable flagsRed = flagsEmpty | Component.red;
immutable flagsGreen = ComponentFlags(Component.green);
immutable flagsRedGreen = ComponentFlags(Component.red, Component.green);
immutable flagsBlueGreen = ComponentFlags(Component.blue, Component.green);
// Use the & operator between BitFlags for intersection.
assert (flagsGreen == (flagsRedGreen & flagsBlueGreen));
} |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Clojure | Clojure | user> (def d [1 2 3 4 5]) ; immutable vector
#'user/d
user> (assoc d 3 7)
[1 2 3 7 5]
user> d
[1 2 3 4 5] |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #COBOL | COBOL | ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
SYMBOLIC CHARACTERS NUL IS 0, TAB IS 9. |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #D | D | import std.random;
// enum allows to define manifest (compile-time) constants:
int sqr(int x) { return x ^^ 2; }
enum int x = 5;
enum y = sqr(5); // Forces Compile-Time Function Evaluation (CTFE).
// enums are compile-time constants:
enum MyEnum { A, B, C }
// immutable defines values that can't change:
immutable double pi = 3.1415;
// A module-level immutable storage class variable that's not
// explicitly initialized can be initialized by its constructor,
// otherwise its value is the default initializer during its life-time.
immutable int z;
static this() {
z = uniform(0, 100); // Run-time initialization.
}
class Test1 {
immutable int w;
this() {
w = uniform(0, 100); // Run-time initialization.
}
}
// The items array can't be immutable here.
// "in" is short for "const scope":
void foo(const scope int[] items) {
// items is constant here.
// items[0] = 100; // Cannot modify const expression.
}
struct Test2 {
int x_; // Mutable.
@property int x() { return this.x_; }
}
// Unlike C++, D const and immutable are transitive.
// And there is also "inout". See D docs.
void main() {
int[] data = [10, 20, 30];
foo(data);
data[0] = 100; // But data is mutable here.
// Currently manifest constants like arrays and associative arrays
// are copied in-place every time they are used:
enum array = [1, 2, 3];
foo(array);
auto t = Test2(100);
auto x2 = t.x; // Reading x is allowed.
assert(x2 == 100);
// Not allowed, the setter property is missing:
// t.x = 10; // Error: not a property t.x
} |
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
| #Aime | Aime | integer c;
real h, v;
index x;
data s;
for (, c in (s = argv(1))) {
x[c] += 1r;
}
h = 0;
for (, v in x) {
v /= ~s;
h -= v * log2(v);
}
o_form("/d6/\n", h); |
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
| #ALGOL_68 | ALGOL 68 | BEGIN
# calculate the shannon entropy of a string #
PROC shannon entropy = ( STRING s )REAL:
BEGIN
INT string length = ( UPB s - LWB s ) + 1;
# count the occurences of each character #
[ 0 : max abs char ]INT char count;
FOR char pos FROM LWB char count TO UPB char count DO
char count[ char pos ] := 0
OD;
FOR char pos FROM LWB s TO UPB s DO
char count[ ABS s[ char pos ] ] +:= 1
OD;
# calculate the entropy, we use log base 10 and then convert #
# to log base 2 after calculating the sum #
REAL entropy := 0;
FOR char pos FROM LWB char count TO UPB char count DO
IF char count[ char pos ] /= 0
THEN
# have a character that occurs in the string #
REAL probability = char count[ char pos ] / string length;
entropy -:= probability * log( probability )
FI
OD;
entropy / log( 2 )
END; # shannon entropy #
# test the shannon entropy routine #
print( ( shannon entropy( "1223334444" ), newline ) )
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
| #AWK | AWK | function halve(x)
{
return int(x/2)
}
function double(x)
{
return x*2
}
function iseven(x)
{
return x%2 == 0
}
function ethiopian(plier, plicand)
{
r = 0
while(plier >= 1) {
if ( !iseven(plier) ) {
r += plicand
}
plier = halve(plier)
plicand = double(plicand)
}
return r
}
BEGIN {
print ethiopian(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.
| #Clojure | Clojure | (defn equilibrium [lst]
(loop [acc '(), i 0, left 0, right (apply + lst), lst lst]
(if (empty? lst)
(reverse acc)
(let [[x & xs] lst
right (- right x)
acc (if (= left right) (cons i acc) acc)]
(recur acc (inc i) (+ left x) right xs))))) |
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.
| #Common_Lisp | Common Lisp | (defun dflt-on-nil (v dflt)
(if v v dflt))
(defun eq-index (v)
(do*
((stack nil)
(i 0 (+ 1 i))
(rest v (cdr rest))
(lsum 0)
(rsum (apply #'+ (cdr v))))
;; Reverse here is not strictly necessary
((null rest) (reverse stack))
(if (eql lsum rsum) (push i stack))
(setf lsum (+ lsum (car rest)))
(setf rsum (- rsum (dflt-on-nil (cadr rest) 0))))) |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Var v = Environ("SystemRoot")
Print v
Sleep |
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
| #Frink | Frink | callJava["java.lang.System", "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
| #FunL | FunL | println( System.getenv('PATH') )
println( $home )
println( $user ) |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Phix | Phix | constant aleph = "0123456789ABCDEF"
function efill(string s, integer ch, i)
-- min-fill, like 10101 or 54321 or 32101
s[i] = ch
for j=i+1 to length(s) do
ch = iff(ch>='1'?iff(ch='A'?'9':ch-1):'1')
s[j] = ch
end for
return s
end function
function esthetic(string s, integer base = 10)
-- generate the next esthetic number after s
-- (nb unpredictable results if s is not esthetic, or "")
for i=length(s) to 1 by -1 do
integer ch = s[i], cp = iff(i>1?s[i-1]:'0')
if ch<cp and cp<aleph[base] then
return efill(s,aleph[find(ch,aleph)+2],i)
elsif i=1 and ch<aleph[base] then
return efill(s,iff(ch='9'?'A':ch+1),i)
end if
end for
return efill("1"&s,'1',1)
end function
string s
sequence res
for base=2 to 16 do
integer hi = base*6,
lo = base*4
{s,res} = {"",{}}
for i=1 to hi do
s = esthetic(s, base)
if i>=lo then
res = append(res,s)
end if
end for
res = join(shorten(res,"numbers",4))
printf(1,"Base %d esthetic numbers[%d..%d]: %s\n",{base,lo,hi,res})
end for
{s,res} = {efill("1000",'1',1),{}}
while length(s)=4 do
res = append(res,s)
s = esthetic(s)
end while
res = {join(shorten(res,"numbers",5))}
printf(1,"\nBase 10 esthetic numbers between 1,000 and 9,999: %s\n\n",res)
function comma(string s)
for i=length(s)-2 to 2 by -3 do
s[i..i-1] = ","
end for
return s
end function
for k=7 to 19 by 3 do
string f = "10"&repeat('0',k),
t = "13"&repeat('0',k)
{s,res} = {efill(f,'1',1),{}}
while s<t do
res = append(res,s)
s = esthetic(s)
end while
res = join(shorten(res,"numbers",1))
printf(1,"Base 10 esthetic numbers between %s and %s: %s\n",
{comma(f),comma(t),res})
end for
|
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.
| #Delphi | Delphi | n = 250
len p5[] n
len h5[] 65537
for i range n
p5[i] = i * i * i * i * i
h5[p5[i] mod 65537] = 1
.
func search a s . y .
y = -1
b = n
while a + 1 < b
i = (a + b) div 2
if p5[i] > s
b = i
elif p5[i] < s
a = i
else
a = b
y = i
.
.
.
for x0 range n
for x1 range x0
sum1 = p5[x0] + p5[x1]
for x2 range x1
sum2 = p5[x2] + sum1
for x3 range x2
sum = p5[x3] + sum2
if h5[sum mod 65537] = 1
call search x0 sum y
if y >= 0
print x0 & " " & x1 & " " & x2 & " " & x3 & " " & y
break 4
.
.
.
.
.
. |
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
| #MUMPS | MUMPS | factorial(num) New ii,result
If num<0 Quit "Negative number"
If num["." Quit "Not an integer"
Set result=1 For ii=1:1:num Set result=result*ii
Quit result
Write $$factorial(0) ; 1
Write $$factorial(1) ; 1
Write $$factorial(2) ; 2
Write $$factorial(3) ; 6
Write $$factorial(10) ; 3628800
Write $$factorial(-6) ; Negative number
Write $$factorial(3.7) ; Not an integer |
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.
| #BASIC | BASIC | 10 INPUT "ENTER A NUMBER: ";N
20 IF N/2 <> INT(N/2) THEN PRINT "THE NUMBER IS ODD":GOTO 40
30 PRINT "THE NUMBER IS EVEN"
40 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.
| #Batch_File | Batch File |
@echo off
set /p i=Insert number:
::bitwise and
set /a "test1=%i%&1"
::divide last character by 2
set /a test2=%i:~-1%/2
::modulo
set /a test3=%i% %% 2
set test
pause>nul
|
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Oforth | Oforth | : euler(f, y, a, b, h)
| t |
a b h step: t [
System.Out t <<wjp(6, JUSTIFY_RIGHT, 3) " : " << y << cr
t y f perform h * y + ->y
] ; |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Pascal | Pascal |
{$mode delphi}
PROGRAM Euler;
TYPE TNewtonCooling = FUNCTION (t: REAL) : REAL;
CONST T0 : REAL = 100.0;
CONST TR : REAL = 20.0;
CONST k : REAL = 0.07;
CONST time : INTEGER = 100;
CONST step : INTEGER = 10;
CONST dt : ARRAY[0..3] of REAL = (1.0,2.0,5.0,10.0);
VAR i : INTEGER;
FUNCTION NewtonCooling(t: REAL) : REAL;
BEGIN
NewtonCooling := -k * (t-TR);
END;
PROCEDURE Euler(F: TNewtonCooling; y, h : REAL; n: INTEGER);
VAR i: INTEGER = 0;
BEGIN
WRITE('dt=',trunc(h):2,':');
REPEAT
IF (i mod 10 = 0) THEN WRITE(' ',y:2:3);
INC(i,trunc(h));
y := y + h * F(y);
UNTIL (i >= n);
WRITELN;
END;
PROCEDURE Sigma;
VAR t: INTEGER = 0;
BEGIN
WRITE('Sigma:');
REPEAT
WRITE(' ',(20 + 80 * exp(-0.07 * t)):2:3);
INC(t,step);
UNTIL (t>=time);
WRITELN;
END;
BEGIN
WRITELN('Newton cooling function: Analytic solution (Sigma) with 3 Euler approximations.');
WRITELN('Time: ',0:7,10:7,20:7,30:7,40:7,50:7,60:7,70:7,80:7,90:7);
Sigma;
FOR i := 1 to 3 DO
Euler(NewtonCooling,T0,dt[i],time);
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function factorial(n As Integer) As Integer
If n < 1 Then Return 1
Dim product As Integer = 1
For i As Integer = 2 To n
product *= i
Next
Return Product
End Function
Function binomial(n As Integer, k As Integer) As Integer
If n < 0 OrElse k < 0 OrElse n <= k Then Return 1
Dim product As Integer = 1
For i As Integer = n - k + 1 To n
Product *= i
Next
Return product \ factorial(k)
End Function
For n As Integer = 0 To 14
For k As Integer = 0 To n
Print Using "####"; binomial(n, k);
Print" ";
Next k
Print
Next n
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #x86_Assembly | x86 Assembly | TITLE i hate visual studio 4 (Fibs.asm)
; __ __/--------\
; >__ \ / | |\
; \ \___/ @ \ / \__________________
; \____ \ / \\\
; \____ Coded with love by: |||
; \ Alexander Alvonellos |||
; | 9/29/2011 / ||
; | | MM
; | |--------------| |
; |< | |< |
; | | | |
; |mmmmmm| |mmmmm|
;; Epic Win.
INCLUDE Irvine32.inc
.data
BEERCOUNT = 48;
Fibs dd 0, 1, BEERCOUNT DUP(0);
.code
main PROC
; I am not responsible for this code.
; They made me write it, against my will.
;Here be dragons
mov esi, offset Fibs; offset array; ;;were to start (start)
mov ecx, BEERCOUNT; ;;count of items (how many)
mov ebx, 4; ;;size (in number of bytes)
call DumpMem;
mov ecx, BEERCOUNT; ;//http://www.wolframalpha.com/input/?i=F ib%5B47%5D+%3E+4294967295
mov esi, offset Fibs
NextPlease:;
mov eax, [esi]; ;//Get me the data from location at ESI
add eax, [esi+4]; ;//add into the eax the data at esi + another double (next mem loc)
mov [esi+8], eax; ;//Move that data into the memory location after the second number
add esi, 4; ;//Update the pointer
loop NextPlease; ;//Thank you sir, may I have another?
;Here be dragons
mov esi, offset Fibs; offset array; ;;were to start (start)
mov ecx, BEERCOUNT; ;;count of items (how many)
mov ebx, 4; ;;size (in number of bytes)
call DumpMem;
exit ; exit to operating system
main ENDP
END main |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Phix | Phix | without js -- command_line, file i/o
function entropy(sequence s)
sequence symbols = {},
counts = {}
integer N = length(s)
for i=1 to N do
object si = s[i]
integer k = find(si,symbols)
if k=0 then
symbols = append(symbols,si)
counts = append(counts,1)
else
counts[k] += 1
end if
end for
atom H = 0
for i=1 to length(counts) do
atom ci = counts[i]/N
H -= ci*log2(ci)
end for
return H
end function
?entropy(get_text(open(substitute(command_line()[2],".exe",".exw")),"rb"))
|
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #PHP | PHP | <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h; |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Delphi | Delphi | type
fruit = (apple, banana, cherry);
ape = (gorilla = 0, chimpanzee = 1, orangutan = 5); |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #DWScript | DWScript | type TFruit = (Apple, Banana, Cherry);
type TApe = (Gorilla = 0, Chimpanzee = 1, Orangutan = 5); |
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.
| #11l | 11l | I fs:list_dir(input()).empty
print(‘empty’)
E
print(‘not empty’) |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Delphi | Delphi | const
STR1 = 'abc'; // regular constant
STR2: string = 'def'; // typed constant |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Dyalect | Dyalect | let pi = 3.14
let helloWorld = "Hello, world!" |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #E | E | def x := 1
x := 2 # this is an error |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Ela | Ela | open unsafe.cell
r = ref 0 |
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
| #ALGOL_W | ALGOL W | begin
% calculates the shannon entropy of a string %
% strings are fixed length in algol W and the length is part of the %
% type, so we declare the string parameter to be the longest possible %
% string length (256 characters) and have a second parameter to %
% specify how much is actually used %
real procedure shannon_entropy ( string(256) value s
; integer value stringLength
);
begin
real probability, entropy;
% algol W assumes there are 256 possible characters %
integer MAX_CHAR;
MAX_CHAR := 256;
% declarations must preceed statements, so we start a new %
% block here so we can use MAX_CHAR as an array bound %
begin
% increment an integer variable %
procedure incI ( integer value result a ) ; a := a + 1;
integer array charCount( 1 :: MAX_CHAR );
% count the occurances of each character in s %
for charPos := 1 until MAX_CHAR do charCount( charPos ) := 0;
for sPos := 0 until stringLength - 1 do incI( charCount( decode( s( sPos | 1 ) ) ) );
% calculate the entropy, we use log base 10 and then convert %
% to log base 2 after calculating the sum %
entropy := 0.0;
for charPos := 1 until MAX_CHAR do
begin
if charCount( charPos ) not = 0
then begin
% have a character that occurs in the string %
probability := charCount( charPos ) / stringLength;
entropy := entropy - ( probability * log( probability ) )
end
end charPos
end;
entropy / log( 2 )
end shannon_entropy ;
% test the shannon entropy routine %
r_format := "A"; r_w := 12; r_d := 6; % set output to fixed format %
write( shannon_entropy( "1223334444", 10 ) )
end. |
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
| #APL | APL |
ENTROPY←{-+/R×2⍟R←(+⌿⍵∘.=∪⍵)÷⍴⍵}
⍝ How it works:
⎕←UNIQUE←∪X←'1223334444'
1234
⎕←TABLE_OF_OCCURENCES←X∘.=UNIQUE
1 0 0 0
0 1 0 0
0 1 0 0
0 0 1 0
0 0 1 0
0 0 1 0
0 0 0 1
0 0 0 1
0 0 0 1
0 0 0 1
⎕←COUNT←+⌿TABLE_OF_OCCURENCES
1 2 3 4
⎕←N←⍴X
10
⎕←RATIO←COUNT÷N
0.1 0.2 0.3 0.4
-+/RATIO×2⍟RATIO
1.846439345
|
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
| #BASIC | BASIC |
REM Ethiopian multiplication
X = 17
Y = 34
TOT = 0
WHILE X >= 1
PRINT X;
PRINT " ";
A = X
GOSUB CHECKEVEN:
IF ISEVEN = 0 THEN
TOT = TOT + Y
PRINT Y;
ENDIF
PRINT
A = X
GOSUB HALVE:
X = A
A = Y
GOSUB DOUBLE:
Y = A
WEND
PRINT "= ";
PRINT TOT
END
REM Subroutines are required, though
REM they complicate the code
DOUBLE:
A = 2 * A
RETURN
HALVE:
A = A / 2
RETURN
CHECKEVEN:
REM ISEVEN - result (0 if A odd, 1 otherwise)
ISEVEN = A MOD 2
ISEVEN = 1 - ISEVEN
RETURN
|
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.
| #D | D | import std.stdio, std.algorithm, std.range, std.functional;
auto equilibrium(Range)(Range r) pure nothrow @safe /*@nogc*/ {
return r.length.iota.filter!(i => r[0 .. i].sum == r[i + 1 .. $].sum);
}
void main() {
[-7, 1, 5, 2, -4, 3, 0].equilibrium.writeln;
} |
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.
| #Delphi | Delphi | import extensions;
import system'routines;
import system'collections;
import extensions'routines;
class EquilibriumEnumerator : Enumerator
{
int left;
int right;
int index;
Enumerator en;
constructor new(Enumerator en)
{
this en := en;
self.reset()
}
constructor new(Enumerable list)
<= new(list.enumerator());
constructor new(o)
<= new(cast Enumerable(o));
bool next()
{
index += 1;
while(en.next())
{
var element := en.get();
right -= element;
bool found := (left == right);
left += element;
if (found)
{
^ true
};
index += 1
};
^ false
}
reset()
{
en.reset();
left := 0;
right := en.summarize();
index := -1;
en.reset();
}
get() = index;
enumerable() => en;
}
public program()
{
EquilibriumEnumerator.new(new int[]{ -7, 1, 5, 2, -4, 3, 0 })
.forEach:printingLn
} |
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
| #Go | Go | package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(os.Getenv("SHELL"))
} |
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
| #Gri | Gri | get env \foo HOME
show "\foo" |
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
| #Groovy | Groovy | System.getenv().each { property, value -> println "$property = $value"} |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #PicoLisp | PicoLisp | (de esthetic (N Base)
(let Lst
(make
(loop
(yoke (% N Base))
(T (=0 (setq N (/ N Base)))) ) )
(and
(fully
=1
(make
(for (L Lst (cdr L) (cdr L))
(link (abs (- (car L) (cadr L)))) ) ) )
(pack
(mapcar
'((C)
(and (> C 9) (inc 'C 39))
(char (+ C 48)) )
Lst ) ) ) ) )
(de genCount (Num Base)
(let (C 0 N 0)
(tail
(inc (* 2 Base))
(make
(while (>= Num C)
(when (esthetic N Base) (link @) (inc 'C))
(inc 'N) ) ) ) ) )
(de genRange (A B Base)
(make
(while (>= B A)
(when (esthetic A Base) (link @))
(inc 'A) ) ) )
(for (N 2 (>= 16 N) (inc N))
(prin "Base " N ": ")
(mapc '((L) (prin L " ")) (genCount (* 6 N) N))
(prinl) )
(prinl)
(prinl "Base 10: 61 esthetic numbers between 1000 and 9999:")
(let L (genRange 1000 9999 10)
(while (cut 16 'L)
(mapc '((L) (prin L " ")) @)
(prinl) ) )
(prinl)
(prinl "Base 10: 126 esthetic numbers between 100000000 and 130000000:")
(let L (genRange 100000000 130000000 10)
(while (cut 9 'L)
(mapc '((L) (prin L " ")) @)
(prinl) ) ) |
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.
| #EasyLang | EasyLang | n = 250
len p5[] n
len h5[] 65537
for i range n
p5[i] = i * i * i * i * i
h5[p5[i] mod 65537] = 1
.
func search a s . y .
y = -1
b = n
while a + 1 < b
i = (a + b) div 2
if p5[i] > s
b = i
elif p5[i] < s
a = i
else
a = b
y = i
.
.
.
for x0 range n
for x1 range x0
sum1 = p5[x0] + p5[x1]
for x2 range x1
sum2 = p5[x2] + sum1
for x3 range x2
sum = p5[x3] + sum2
if h5[sum mod 65537] = 1
call search x0 sum y
if y >= 0
print x0 & " " & x1 & " " & x2 & " " & x3 & " " & y
break 4
.
.
.
.
.
. |
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
| #MyrtleScript | MyrtleScript | func factorial args: int a : returns: int {
int factorial = a
repeat int i = (a - 1) : i == 0 : i-- {
factorial *= i
}
return factorial
} |
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.
| #BBC_BASIC | BBC BASIC | IF FNisodd%(14) PRINT "14 is odd" ELSE PRINT "14 is even"
IF FNisodd%(15) PRINT "15 is odd" ELSE PRINT "15 is even"
IF FNisodd#(9876543210#) PRINT "9876543210 is odd" ELSE PRINT "9876543210 is even"
IF FNisodd#(9876543211#) PRINT "9876543211 is odd" ELSE PRINT "9876543211 is even"
END
REM Works for -2^31 <= n% < 2^31
DEF FNisodd%(n%) = (n% AND 1) <> 0
REM Works for -2^53 <= n# <= 2^53
DEF FNisodd#(n#) = n# <> 2 * INT(n# / 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.
| #bc | bc | i = -3
/* Assumes that i is an integer. */
scale = 0
if (i % 2 == 0) "i is even
"
if (i % 2) "i is odd
" |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Perl | Perl | sub euler_method {
my ($t0, $t1, $k, $step_size) = @_;
my @results = ( [0, $t0] );
for (my $s = $step_size; $s <= 100; $s += $step_size) {
$t0 -= ($t0 - $t1) * $k * $step_size;
push @results, [$s, $t0];
}
return @results;
}
sub analytical {
my ($t0, $t1, $k, $time) = @_;
return ($t0 - $t1) * exp(-$time * $k) + $t1
}
my ($T0, $T1, $k) = (100, 20, .07);
my @r2 = grep { $_->[0] % 10 == 0 } euler_method($T0, $T1, $k, 2);
my @r5 = grep { $_->[0] % 10 == 0 } euler_method($T0, $T1, $k, 5);
my @r10 = grep { $_->[0] % 10 == 0 } euler_method($T0, $T1, $k, 10);
print "Time\t 2 err(%) 5 err(%) 10 err(%) Analytic\n", "-" x 76, "\n";
for (0 .. $#r2) {
my $an = analytical($T0, $T1, $k, $r2[$_][0]);
printf "%4d\t".("%9.3f" x 7)."\n",
$r2 [$_][0],
$r2 [$_][1], ($r2 [$_][1] / $an) * 100 - 100,
$r5 [$_][1], ($r5 [$_][1] / $an) * 100 - 100,
$r10[$_][1], ($r10[$_][1] / $an) * 100 - 100,
$an;
}
|
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
| #Frink | Frink |
println[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
| #FunL | FunL | def
choose( n, k ) | k < 0 or k > n = 0
choose( n, 0 ) = 1
choose( n, n ) = 1
choose( n, k ) = product( [(n - i)/(i + 1) | i <- 0:min( k, n - k )] )
println( choose(5, 3) )
println( choose(60, 30) ) |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #xEec | xEec |
h#1 h#1 h#1 o#
h#10 o$ p
>f
o# h#10 o$ p
ma h? jnext p
t
jnf
|
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Picat | Picat |
entropy(File) = E =>
Bytes = read_file_bytes(File),
F = [0: I in 1..256],
foreach (B in Bytes)
B1 := B + 1,
F[B1] := F[B1] + 1
end,
HM = 0,
foreach (C in F)
if (C > 0) then
HM := HM + C * log(2, C)
end
end,
L = Bytes.length,
E = log(2, L) - HM / L.
main(Args) =>
printf("Entropy: %f\n", entropy(Args[1])).
|
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #PicoLisp | PicoLisp |
(scl 8)
(load "@lib/math.l")
(setq LN2 0.693147180559945309417)
(setq Me
(let F (file)
(pack (car F) (cadr F))))
(setq Hist NIL Sz 0)
(in Me
(use Ch
(while (setq Ch (rd 1))
(inc 'Sz)
(if (assoc Ch Hist)
(con @ (inc (cdr @)))
(setq Hist (cons (cons Ch 1) Hist))))))
(prinl "My entropy is "
(format
(*/
(sum
'((Pair)
(let R (*/ (cdr Pair) 1. Sz)
(- (*/ R (log R) 1.))))
Hist)
1. LN2)
*Scl))
(bye)
|
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Python | Python | import math
from collections import Counter
def entropy(s):
p, lns = Counter(s), float(len(s))
return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
with open(__file__) as f:
b=f.read()
print(entropy(b)) |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Racket | Racket |
#lang racket
(require math)
(define (log2 x) (/ (log x) (log 2)))
(define ds (string->list (file->string "entropy.rkt")))
(define n (length ds))
(- (for/sum ([(d c) (in-hash (samples->hash ds))])
(* (/ c n) (log2 (/ c n)))))
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #E | E | def apple { to value() { return 0 } }
def banana { to value() { return 1 } }
def cherry { to value() { return 2 } } |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #EGL | EGL | // Without explicit values
enumeration FruitsKind
APPLE,
BANANA,
CHERRY
end
program EnumerationTest
function main()
whatFruitAmI(FruitsKind.CHERRY);
end
function whatFruitAmI(fruit FruitsKind)
case (fruit)
when(FruitsKind.APPLE)
syslib.writestdout("You're an apple.");
when(FruitsKind.BANANA)
syslib.writestdout("You're a banana.");
when(FruitsKind.CHERRY)
syslib.writestdout("You're a cherry.");
otherwise
syslib.writestdout("I'm not sure what you are.");
end
end
end |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Elixir | Elixir | fruits = [:apple, :banana, :cherry]
fruits = ~w(apple banana cherry)a # Above-mentioned different notation
val = :banana
Enum.member?(fruits, val) #=> true
val in fruits #=> true |
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
| #11l | 11l | V s = ‘’
I s.empty
print(‘String s is empty.’)
I !s.empty
print(‘String s is not empty.’) |
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining equation, together with 𝒪.
There is a rule for adding two points on an elliptic curve to give a third point.
This addition operation and the set of points E(ℤp) form a group with identity 𝒪.
It is this group that is used in the construction of elliptic curve cryptosystems.
The addition rule — which can be explained geometrically — is summarized as follows:
1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp).
2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪.
3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q.
Then R = P + Q = (xR, yR), where
xR = λ^2 - xP - xQ
yR = λ·(xP - xR) - yP,
with
λ = (yP - yQ) / (xP - xQ) if P ≠ Q,
(3·xP·xP + a) / 2·yP if P = Q (point doubling).
Remark: there already is a task page requesting “a simplified (without modular arithmetic)
version of the elliptic curve arithmetic”.
Here we do add modulo operations. If also the domain is changed from reals to rationals,
the elliptic curves are no longer continuous but break up into a finite number of distinct points.
In that form we use them to implement ECDSA:
Elliptic curve digital signature algorithm.
A digital signature is the electronic analogue of a hand-written signature
that convinces the recipient that a message has been sent intact by the presumed sender.
Anyone with access to the public key of the signer may verify this signature.
Changing even a single bit of a signed message will cause the verification procedure to fail.
ECDSA key generation. Party A does the following:
1. Select an elliptic curve E defined over ℤp.
The number of points in E(ℤp) should be divisible by a large prime r.
2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪).
3. Select a random integer s in the interval [1, r - 1].
4. Compute W = sG.
The public key is (E, G, r, W), the private key is s.
ECDSA signature computation. To sign a message m, A does the following:
1. Compute message representative f = H(m), using a
cryptographic hash function.
Note that f can be greater than r but not longer (measuring bits).
2. Select a random integer u in the interval [1, r - 1].
3. Compute V = uG = (xV, yV) and c ≡ xV mod r (goto (2) if c = 0).
4. Compute d ≡ u^-1·(f + s·c) mod r (goto (2) if d = 0).
The signature for the message m is the pair of integers (c, d).
ECDSA signature verification. To verify A's signature, B should do the following:
1. Obtain an authentic copy of A's public key (E, G, r, W).
Verify that c and d are integers in the interval [1, r - 1].
2. Compute f = H(m) and h ≡ d^-1 mod r.
3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r.
4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r.
Accept the signature if and only if c1 = c.
To be cryptographically useful, the parameter r should have at least 250 bits.
The basis for the security of elliptic curve cryptosystems
is the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size:
given two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G,
determine an integer k such that W = kG and 0 ≤ k < r.
Task.
The task is to write a toy version of the ECDSA, quasi the equal of a real-world
implementation, but utilizing parameters that fit into standard arithmetic types.
To keep things simple there's no need for key export or a hash function (just a sample
hash value and a way to tamper with it). The program should be lenient where possible
(for example: if it accepts a composite modulus N it will either function as expected,
or demonstrate the principle of elliptic curve factorization)
— but strict where required (a point G that is not on E will always cause failure).
Toy ECDSA is of course completely useless for its cryptographic purpose.
If this bothers you, please add a multiple-precision version.
Reference.
Elliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see:
7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.)
7.1 The EC setting
7.1.2 EC domain parameters
7.1.3 EC key pairs
7.2 Primitives
7.2.7 ECSP-DSA (p. 35)
7.2.8 ECVP-DSA (p. 36)
Annex A. Number-theoretic background
A.9 Elliptic curves: overview (p. 115)
A.10 Elliptic curves: algorithms (p. 121)
| #C | C |
/*
subject: Elliptic curve digital signature algorithm,
toy version for small modulus N.
tested : gcc 4.6.3, tcc 0.9.27
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 64-bit integer type
typedef long long int dlong;
// rational ec point
typedef struct {
dlong x, y;
} epnt;
// elliptic curve parameters
typedef struct {
long a, b;
dlong N;
epnt G;
dlong r;
} curve;
// signature pair
typedef struct {
long a, b;
} pair;
// dlong for holding intermediate results,
// long variables in exgcd() for efficiency,
// maximum parameter size 2 * p.y (line 129)
// limits the modulus size to 30 bits.
// maximum modulus
const long mxN = 1073741789;
// max order G = mxN + 65536
const long mxr = 1073807325;
// symbolic infinity
const long inf = -2147483647;
// single global curve
curve e;
// point at infinity zerO
epnt zerO;
// impossible inverse mod N
int inverr;
// return mod(v^-1, u)
long exgcd (long v, long u)
{
register long q, t;
long r = 0, s = 1;
if (v < 0) v += u;
while (v) {
q = u / v;
t = u - q * v;
u = v; v = t;
t = r - q * s;
r = s; s = t;
}
if (u != 1) {
printf (" impossible inverse mod N, gcd = %d\n", u);
inverr = 1;
}
return r;
}
// return mod(a, N)
static inline dlong modn (dlong a)
{
a %= e.N;
if (a < 0) a += e.N;
return a;
}
// return mod(a, r)
dlong modr (dlong a)
{
a %= e.r;
if (a < 0) a += e.r;
return a;
}
// return the discriminant of E
long disc (void)
{
dlong c, a = e.a, b = e.b;
c = 4 * modn(a * modn(a * a));
return modn(-16 * (c + 27 * modn(b * b)));
}
// return 1 if P = zerO
int isO (epnt p)
{
return (p.x == inf) && (p.y == 0);
}
// return 1 if P is on curve E
int ison (epnt p)
{
long r, s;
if (! isO (p)) {
r = modn(e.b + p.x * modn(e.a + p.x * p.x));
s = modn(p.y * p.y);
}
return (r == s);
}
// full ec point addition
void padd (epnt *r, epnt p, epnt q)
{
dlong la, t;
if (isO(p)) {*r = q; return;}
if (isO(q)) {*r = p; return;}
if (p.x != q.x) { // R:= P + Q
t = p.y - q.y;
la = modn(t * exgcd(p.x - q.x, e.N));
}
else // P = Q, R := 2P
if ((p.y == q.y) && (p.y != 0)) {
t = modn(3 * modn(p.x * p.x) + e.a);
la = modn(t * exgcd (2 * p.y, e.N));
}
else
{*r = zerO; return;} // P = -Q, R := O
t = modn(la * la - p.x - q.x);
r->y = modn(la * (p.x - t) - p.y);
r->x = t; if (inverr) *r = zerO;
}
// R:= multiple kP
void pmul (epnt *r, epnt p, long k)
{
epnt s = zerO, q = p;
for (; k; k >>= 1) {
if (k & 1) padd(&s, s, q);
if (inverr) {s = zerO; break;}
padd(&q, q, q);
}
*r = s;
}
// print point P with prefix f
void pprint (char *f, epnt p)
{
dlong y = p.y;
if (isO (p))
printf ("%s (0)\n", f);
else {
if (y > e.N - y) y -= e.N;
printf ("%s (%lld, %lld)\n", f, p.x, y);
}
}
// initialize elliptic curve
int ellinit (long i[])
{
long a = i[0], b = i[1];
e.N = i[2]; inverr = 0;
if ((e.N < 5) || (e.N > mxN)) return 0;
e.a = modn(a);
e.b = modn(b);
e.G.x = modn(i[3]);
e.G.y = modn(i[4]);
e.r = i[5];
if ((e.r < 5) || (e.r > mxr)) return 0;
printf ("\nE: y^2 = x^3 + %dx + %d", a, b);
printf (" (mod %lld)\n", e.N);
pprint ("base point G", e.G);
printf ("order(G, E) = %lld\n", e.r);
return 1;
}
// pseudorandom number [0..1)
double rnd(void)
{
return rand() / ((double)RAND_MAX + 1);
}
// signature primitive
pair signature (dlong s, long f)
{
long c, d, u, u1;
pair sg;
epnt V;
printf ("\nsignature computation\n");
do {
do {
u = 1 + (long)(rnd() * (e.r - 1));
pmul (&V, e.G, u);
c = modr(V.x);
}
while (c == 0);
u1 = exgcd (u, e.r);
d = modr(u1 * (f + modr(s * c)));
}
while (d == 0);
printf ("one-time u = %d\n", u);
pprint ("V = uG", V);
sg.a = c; sg.b = d;
return sg;
}
// verification primitive
int verify (epnt W, long f, pair sg)
{
long c = sg.a, d = sg.b;
long t, c1, h1, h2;
dlong h;
epnt V, V2;
// domain check
t = (c > 0) && (c < e.r);
t &= (d > 0) && (d < e.r);
if (! t) return 0;
printf ("\nsignature verification\n");
h = exgcd (d, e.r);
h1 = modr(f * h);
h2 = modr(c * h);
printf ("h1,h2 = %d, %d\n", h1,h2);
pmul (&V, e.G, h1);
pmul (&V2, W, h2);
pprint ("h1G", V);
pprint ("h2W", V2);
padd (&V, V, V2);
pprint ("+ =", V);
if (isO (V)) return 0;
c1 = modr(V.x);
printf ("c' = %d\n", c1);
return (c1 == c);
}
// digital signature on message hash f, error bit d
void ec_dsa (long f, long d)
{
long i, s, t;
pair sg;
epnt W;
// parameter check
t = (disc() == 0);
t |= isO (e.G);
pmul (&W, e.G, e.r);
t |= ! isO (W);
t |= ! ison (e.G);
if (t) goto errmsg;
printf ("\nkey generation\n");
s = 1 + (long)(rnd() * (e.r - 1));
pmul (&W, e.G, s);
printf ("private key s = %d\n", s);
pprint ("public key W = sG", W);
// next highest power of 2 - 1
t = e.r;
for (i = 1; i < 32; i <<= 1)
t |= t >> i;
while (f > t) f >>= 1;
printf ("\naligned hash %x\n", f);
sg = signature (s, f);
if (inverr) goto errmsg;
printf ("signature c,d = %d, %d\n", sg.a, sg.b);
if (d > 0) {
while (d > t) d >>= 1;
f ^= d;
printf ("\ncorrupted hash %x\n", f);
}
t = verify (W, f, sg);
if (inverr) goto errmsg;
if (t)
printf ("Valid\n_____\n");
else
printf ("invalid\n_______\n");
return;
errmsg:
printf ("invalid parameter set\n");
printf ("_____________________\n");
}
void main (void)
{
typedef long eparm[6];
long d, f;
zerO.x = inf; zerO.y = 0;
srand(time(NULL));
// Test vectors: elliptic curve domain parameters,
// short Weierstrass model y^2 = x^3 + ax + b (mod N)
eparm *sp, sets[10] = {
// a, b, modulus N, base point G, order(G, E), cofactor
{355, 671, 1073741789, 13693, 10088, 1073807281},
{ 0, 7, 67096021, 6580, 779, 16769911}, // 4
{ -3, 1, 877073, 0, 1, 878159},
{ 0, 14, 22651, 63, 30, 151}, // 151
{ 3, 2, 5, 2, 1, 5},
// ecdsa may fail if...
// the base point is of composite order
{ 0, 7, 67096021, 2402, 6067, 33539822}, // 2
// the given order is a multiple of the true order
{ 0, 7, 67096021, 6580, 779, 67079644}, // 1
// the modulus is not prime (deceptive example)
{ 0, 7, 877069, 3, 97123, 877069},
// fails if the modulus divides the discriminant
{ 39, 387, 22651, 95, 27, 22651},
};
// Digital signature on message hash f,
// set d > 0 to simulate corrupted data
f = 0x789abcde; d = 0;
for (sp = sets; ; sp++) {
if (ellinit (*sp))
ec_dsa (f, d);
else
break;
}
}
|
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.
| #8086_Assembly | 8086 Assembly | ; this routine attempts to remove the directory and returns an error code if it cannot.
mov ax,seg dirname ;load into AX the segment where dirname is stored.
mov ds,ax ;load the segment register DS with the segment of dirname
mov dx,offset dirname ;load into DX the offset of dirname
mov ah,39h ;0x39 is the interrupt code for remove directory
int 21h ;sets carry if error is encountered. error code will be in AX.
;If carry is clear the remove was successful
jc error
mov ah,4Ch ;return function
mov al,0 ;required return code
int 21h ;return to DOS
error: ;put your error handler here
mov ah,4Ch ;return function
mov al,0 ;required return code
int 21h ;return to DOS
dirname db "GAMES",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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
function Empty (path : String) return String is
use Ada.Directories;
result : String := "Is empty.";
procedure check (ent : Directory_Entry_Type) is begin
if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
Empty.result := "Not empty";
end if;
end check;
begin
if not Exists (path) then return "Does not exist.";
elsif Kind (path) /= Directory then return "Not a Directory.";
end if;
Search (path, "", Process => check'Access);
return result;
end Empty;
begin
Put_Line (Empty ("."));
Put_Line (Empty ("./empty"));
Put_Line (Empty ("./emptydir.adb"));
Put_Line (Empty ("./foobar"));
end EmptyDir; |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #11l | 11l | BR 14
END |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Elixir | Elixir | iex(1)> x = 10 # bind
10
iex(2)> 10 = x # Pattern matching
10
iex(3)> x = 20 # rebound
20
iex(4)> ^x = 10 # pin operator ^
** (MatchError) no match of right hand side value: 10
|
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Erlang | Erlang | X = 10,
X = 20. |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Euphoria | Euphoria | constant n = 1
constant s = {1,2,3}
constant str = "immutable string" |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #F.23 | F# | let hello = "Hello!" |
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
| #Arturo | Arturo | entropy: function [s][
t: #[]
loop s 'c [
unless key? t c -> t\[c]: 0
t\[c]: t\[c] + 1
]
result: new 0
loop values t 'x ->
'result - (x//(size s)) * log x//(size s) 2
return result
]
print entropy "1223334444" |
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
| #AutoHotkey | AutoHotkey | MsgBox, % Entropy(1223334444)
Entropy(n)
{
a := [], len := StrLen(n), m := n
while StrLen(m)
{
s := SubStr(m, 1, 1)
m := RegExReplace(m, s, "", c)
a[s] := c
}
for key, val in a
{
m := Log(p := val / len)
e -= p * m / Log(2)
}
return, e
} |
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
| #Batch_File | Batch File |
@echo off
:: Pick 2 random, non-zero, 2-digit numbers to send to :_main
set /a param1=%random% %% 98 + 1
set /a param2=%random% %% 98 + 1
call:_main %param1% %param2%
pause>nul
exit /b
:: This is the main function that outputs the answer in the form of "%1 * %2 = %answer%"
:_main
setlocal enabledelayedexpansion
set l0=%1
set r0=%2
set leftcount=1
set lefttempcount=0
set rightcount=1
set righttempcount=0
:: Creates an array ("l[]") with the :_halve function. %l0% is the initial left number parsed
:: This section will loop until the most recent member of "l[]" is equal to 0
:left
set /a lefttempcount=%leftcount%-1
if !l%lefttempcount%!==1 goto right
call:_halve !l%lefttempcount%!
set l%leftcount%=%errorlevel%
set /a leftcount+=1
goto left
:: Creates an array ("r[]") with the :_double function, %r0% is the initial right number parsed
:: This section will loop until it has the same amount of entries as "l[]"
:right
set /a righttempcount=%rightcount%-1
if %rightcount%==%leftcount% goto both
call:_double !r%righttempcount%!
set r%rightcount%=%errorlevel%
set /a rightcount+=1
goto right
:both
:: Creates an boolean array ("e[]") corresponding with whether or not the respective "l[]" entry is even
for /l %%i in (0,1,%lefttempcount%) do (
call:_even !l%%i!
set e%%i=!errorlevel!
)
:: Adds up all entries of "r[]" based on the value of "e[]", respectively
set answer=0
for /l %%i in (0,1,%lefttempcount%) do (
if !e%%i!==1 (
set /a answer+=!r%%i!
:: Everything from this-----------------------------
set iseven%%i=KEEP
) else (
set iseven%%i=STRIKE
)
echo L: !l%%i! R: !r%%i! - !iseven%%i!
:: To this, is for cosmetics and is optional--------
)
echo %l0% * %r0% = %answer%
exit /b
:: These are the three functions being used. The output of these functions are expressed in the errorlevel that they return
:_halve
setlocal
set /a temp=%1/2
exit /b %temp%
:_double
setlocal
set /a temp=%1*2
exit /b %temp%
:_even
setlocal
set int=%1
set /a modint=%int% %% 2
exit /b %modint%
|
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.
| #Elena | Elena | import extensions;
import system'routines;
import system'collections;
import extensions'routines;
class EquilibriumEnumerator : Enumerator
{
int left;
int right;
int index;
Enumerator en;
constructor new(Enumerator en)
{
this en := en;
self.reset()
}
constructor new(Enumerable list)
<= new(list.enumerator());
constructor new(o)
<= new(cast Enumerable(o));
bool next()
{
index += 1;
while(en.next())
{
var element := en.get();
right -= element;
bool found := (left == right);
left += element;
if (found)
{
^ true
};
index += 1
};
^ false
}
reset()
{
en.reset();
left := 0;
right := en.summarize();
index := -1;
en.reset();
}
get() = index;
enumerable() => en;
}
public program()
{
EquilibriumEnumerator.new(new int[]{ -7, 1, 5, 2, -4, 3, 0 })
.forEach:printingLn
} |
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.
| #Elixir | Elixir | defmodule Equilibrium do
def index(list) do
last = length(list)
Enum.filter(0..last-1, fn i ->
Enum.sum(Enum.slice(list, 0, i)) == Enum.sum(Enum.slice(list, i+1..last))
end)
end
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
| #Haskell | Haskell | import System.Environment
main = do getEnv "HOME" >>= print -- get env var
getEnvironment >>= print -- get the entire environment as a list of (key, value) pairs |
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
| #hexiscript | hexiscript | println env "HOME"
println env "PATH"
println env "USER" |
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
| #HicEst | HicEst | CHARACTER string*255
string = "PATH="
SYSTEM(GEteNV = string) |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Prolog | Prolog | main:-
forall(between(2, 16, Base),
(Min_index is Base * 4, Max_index is Base * 6,
print_esthetic_numbers1(Base, Min_index, Max_index))),
print_esthetic_numbers2(1000, 9999, 16),
nl,
print_esthetic_numbers2(100000000, 130000000, 8).
print_esthetic_numbers1(Base, Min_index, Max_index):-
swritef(Format, '~%tr ', [Base]),
writef('Esthetic numbers in base %t from index %t through index %t:\n',
[Base, Min_index, Max_index]),
print_esthetic_numbers1(Base, Format, Min_index, Max_index, 0, 1).
print_esthetic_numbers1(Base, Format, Min_index, Max_index, M, I):-
I =< Max_index,
!,
next_esthetic_number(Base, M, N),
(I >= Min_index -> format(Format, [N]) ; true),
J is I + 1,
print_esthetic_numbers1(Base, Format, Min_index, Max_index, N, J).
print_esthetic_numbers1(_, _, _, _, _, _):-
write('\n\n').
print_esthetic_numbers2(Min, Max, Per_line):-
writef('Esthetic numbers in base 10 between %t and %t:\n', [Min, Max]),
M is Min - 1,
print_esthetic_numbers2(Max, Per_line, M, 0).
print_esthetic_numbers2(Max, Per_line, M, Count):-
next_esthetic_number(10, M, N),
N =< Max,
!,
write(N),
Count1 is Count + 1,
(0 is Count1 mod Per_line -> nl ; write(' ')),
print_esthetic_numbers2(Max, Per_line, N, Count1).
print_esthetic_numbers2(_, _, _, Count):-
writef('\nCount: %t\n', [Count]).
next_esthetic_number(Base, M, N):-
N is M + 1,
N < Base,
!.
next_esthetic_number(Base, M, N):-
A is M // Base,
B is A mod Base,
(B is M mod Base + 1, B + 1 < Base ->
N is M + 2
;
next_esthetic_number(Base, A, C),
D is C mod Base,
(D == 0 -> E = 1 ; E is D - 1),
N is C * Base + E). |
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.
| #EchoLisp | EchoLisp |
(define dim 250)
;; speed up n^5
(define (p5 n) (* n n n n n))
(remember 'p5) ;; memoize
;; build vector of all y^5 - x^5 diffs - length 30877
(define all-y^5-x^5
(for*/vector
[(x (in-range 1 dim)) (y (in-range (1+ x) dim))]
(- (p5 y) (p5 x))))
;; sort to use vector-search
(begin (vector-sort! < all-y^5-x^5) 'sorted)
;; find couple (x y) from y^5 - x^5
(define (x-y y^5-x^5)
(for*/fold (x-y null)
[(x (in-range 1 dim)) (y (in-range (1+ x ) dim))]
(when
(= (- (p5 y) (p5 x)) y^5-x^5)
(set! x-y (list x y))
(break #t)))) ; stop on first
;; search
(for*/fold (sol null)
[(x0 (in-range 1 dim)) (x1 (in-range (1+ x0) dim)) (x2 (in-range (1+ x1) dim))]
(set! sol (+ (p5 x0) (p5 x1) (p5 x2)))
(when
(vector-search sol all-y^5-x^5) ;; x0^5 + x1^5 + x2^5 = y^5 - x3^5 ???
(set! sol (append (list x0 x1 x2) (x-y sol))) ;; found
(break #t))) ;; stop on first
→ (27 84 110 133 144) ;; time 2.8 sec
|
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
| #Nanoquery | Nanoquery | def factorial(n)
result = 1
for i in range(1, n)
result = result * i
end
return 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.
| #Beads | Beads | beads 1 program 'Even or odd'
calc main_init
loop across:[-10, -5, 10, 5] val:v
log "{v}\todd:{is_odd(v)}\teven:{is_even(v)}" |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Phix | Phix | --
-- demo\rosetta\Euler_method.exw
-- =============================
--
with javascript_semantics
function ivp_euler(atom y, integer f, step, end_t)
sequence res = {}
for t=0 to end_t by step do
if remainder(t,10)==0 then res &= y end if
y += step * call_func(f,{t, y})
end for
return res
end function
function analytic()
sequence res = {}
for t=0 to 100 by 10 do
res &= 20 + 80 * exp(-0.07 * t)
end for
return res
end function
function cooling(atom /*t*/, temp)
return -0.07 * (temp - 20)
end function
constant x = tagset(100,0,10),
a = analytic(),
e2 = ivp_euler(100,cooling,2,100),
e5 = ivp_euler(100,cooling,5,100),
e10 = ivp_euler(100,cooling,10,100)
printf(1," Time: %s\n",{join(x,fmt:="%7d")})
printf(1,"Analytic: %s\n",{join(a,fmt:="%7.3f")})
printf(1," Step 2: %s\n",{join(e2,fmt:="%7.3f")})
printf(1," Step 5: %s\n",{join(e5,fmt:="%7.3f")})
printf(1," Step 10: %s\n",{join(e10,fmt:="%7.3f")})
-- and a simple plot
include pGUI.e
include IupGraph.e
function get_data(Ihandle /*graph*/)
return {{"NAMES",{"analytical","h=2","h=5","h=10"}},
{x,a,CD_BLUE},{x,e2,CD_GREEN},{x,e5,CD_BLACK},{x,e10,CD_RED}}
end function
IupOpen()
Ihandle graph = IupGraph(get_data,`RASTERSIZE=340x240,GRID=NO`)
IupSetAttributes(graph,`XTICK=20,XMIN=0,XMAX=100,XMARGIN=25`)
IupSetAttributes(graph,`YTICK=20,YMIN=20,YMAX=100`)
IupShow(IupDialog(graph,`TITLE="Euler Method",MINSIZE=260x200`))
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
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
| #GAP | GAP | # Built-in
Binomial(5, 3);
# 10 |
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
| #Go | Go | package main
import "fmt"
import "math/big"
func main() {
fmt.Println(new(big.Int).Binomial(5, 3))
fmt.Println(new(big.Int).Binomial(60, 30))
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #XLISP | XLISP | (DEFUN FIBONACCI (N)
(FLOOR (+ (/ (EXPT (/ (+ (SQRT 5) 1) 2) N) (SQRT 5)) 0.5))) |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Raku | Raku | say log(2) R/ [+] map -> \p { p * -log p }, $_.comb.Bag.values >>/>> +$_
given slurp($*PROGRAM-NAME).comb |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #REXX | REXX | /*REXX program calculates the "information entropy" for ~this~ REXX program. */
numeric digits length( e() ) % 2 - length(.) /*use 1/2 of the decimal digits of E. */
#= 0; @.= 0; $=; $$=; recs= sourceline() /*define some handy─dandy REXX vars. */
do m=1 for recs; $=$||sourceLine(m) /* [↓] obtain program source and ──► $*/
end /*m*/ /* [↑] $ str won't have any meta chars*/
L=length($) /*the byte length of this REXX program.*/
do j=1 for L; _= substr($, j, 1) /*process each character in $ string.*/
if @._==0 then do; #= # + 1 /*¿Character unique? Bump char counter*/
$$= $$ || _ /*add this character to the $$ list. */
end
@._= @._ + 1 /*keep track of this character's count.*/
end /*j*/ /* [↑] characters are all 8─bit bytes.*/
sum= 0 /*calculate info entropy for each char.*/
do i=1 for #; _= substr($$, i, 1) /*obtain a character from unique list. */
sum= sum - @._ / L * log2(@._ / L) /*add {negatively} the char entropies. */
end /*i*/
say ' program length: ' L /*pgm length doesn't include meta chars*/
say 'program statements: ' recs /*pgm statements are actually pgm lines*/
say ' unique characters: ' #; say /*characters are 8─bit bytes of the pgm*/
say 'The information entropy of this REXX program ──► ' format(sum,,12)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
e: e= 2.718281828459045235360287471352662497757247093699959574966967627724076630; return e
/*──────────────────────────────────────────────────────────────────────────────────────*/
log2: procedure; parse arg x 1 ox; ig= x>1.5; ii= 0; is= 1 - 2 * (ig\==1)
numeric digits digits()+5; call e /*the precision of E must be≥digits(). */
do while ig & ox>1.5 | \ig&ox<.5; _= e; do j=-1; iz= ox * _ ** -is
if j>=0 & (ig & iz<1 | \ig&iz>.5) then leave; _= _ * _; izz= iz; end /*j*/
ox=izz; ii=ii+is*2**j; end /*while*/; x= x * e** -ii -1; z= 0; _= -1; p= z
do k=1; _= -_ * x; z= z+_/k; if z=p then leave; p= z; end /*k*/
r= z + ii; if arg()==2 then return r; return r / log2(2,.) |
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).
| #11l | 11l | T Point
Float x, y
F (x = Float.infinity, y = Float.infinity)
.x = x
.y = y
F.const copy()
R Point(.x, .y)
F.const is_zero()
R .x > 1e20 | .x < -1e20
F neg()
R Point(.x, -.y)
F dbl()
I .is_zero()
R .copy()
I .y == 0
R Point()
V l = (3 * .x * .x) / (2 * .y)
V x = l * l - 2 * .x
R Point(x, l * (.x - x) - .y)
F add(q)
I .x == q.x & .y == q.y
R .dbl()
I .is_zero()
R q.copy()
I q.is_zero()
R .copy()
I q.x - .x == 0
R Point()
V l = (q.y - .y) / (q.x - .x)
V x = l * l - .x - q.x
R Point(x, l * (.x - x) - .y)
F mul(n)
V p = .copy()
V r = Point()
V i = 1
L i <= n
I i [&] n
r = r.add(p)
p = p.dbl()
i <<= 1
R r
F String()
R ‘(#.3, #.3)’.format(.x, .y)
V Point_b = 7
F show(s, p)
print(s‘ ’(I p.is_zero() {‘Zero’} E p))
F from_y(y)
V n = y * y - Point_b
V x = I n >= 0 {n ^ (1. / 3)} E -((-n) ^ (1. / 3))
R Point(x, y)
V a = from_y(1)
V b = from_y(2)
show(‘a =’, a)
show(‘b =’, b)
V c = a.add(b)
show(‘c = a + b =’, c)
V d = c.neg()
show(‘d = -c =’, d)
show(‘c + d =’, c.add(d))
show(‘a + b + d =’, a.add(b.add(d)))
show(‘a * 12345 =’, a.mul(12345)) |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Erlang | Erlang | type Fruit =
| Apple = 0
| Banana = 1
| Cherry = 2
let basket = [ Fruit.Apple ; Fruit.Banana ; Fruit.Cherry ]
Seq.iter (printfn "%A") basket |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #F.23 | F# | type Fruit =
| Apple = 0
| Banana = 1
| Cherry = 2
let basket = [ Fruit.Apple ; Fruit.Banana ; Fruit.Cherry ]
Seq.iter (printfn "%A") basket |
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
| #6502_Assembly | 6502 Assembly | EmptyString:
byte 0 |
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
| #68000_Assembly | 68000 Assembly | EmptyString:
DC.B 0
EVEN |
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining equation, together with 𝒪.
There is a rule for adding two points on an elliptic curve to give a third point.
This addition operation and the set of points E(ℤp) form a group with identity 𝒪.
It is this group that is used in the construction of elliptic curve cryptosystems.
The addition rule — which can be explained geometrically — is summarized as follows:
1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp).
2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪.
3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q.
Then R = P + Q = (xR, yR), where
xR = λ^2 - xP - xQ
yR = λ·(xP - xR) - yP,
with
λ = (yP - yQ) / (xP - xQ) if P ≠ Q,
(3·xP·xP + a) / 2·yP if P = Q (point doubling).
Remark: there already is a task page requesting “a simplified (without modular arithmetic)
version of the elliptic curve arithmetic”.
Here we do add modulo operations. If also the domain is changed from reals to rationals,
the elliptic curves are no longer continuous but break up into a finite number of distinct points.
In that form we use them to implement ECDSA:
Elliptic curve digital signature algorithm.
A digital signature is the electronic analogue of a hand-written signature
that convinces the recipient that a message has been sent intact by the presumed sender.
Anyone with access to the public key of the signer may verify this signature.
Changing even a single bit of a signed message will cause the verification procedure to fail.
ECDSA key generation. Party A does the following:
1. Select an elliptic curve E defined over ℤp.
The number of points in E(ℤp) should be divisible by a large prime r.
2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪).
3. Select a random integer s in the interval [1, r - 1].
4. Compute W = sG.
The public key is (E, G, r, W), the private key is s.
ECDSA signature computation. To sign a message m, A does the following:
1. Compute message representative f = H(m), using a
cryptographic hash function.
Note that f can be greater than r but not longer (measuring bits).
2. Select a random integer u in the interval [1, r - 1].
3. Compute V = uG = (xV, yV) and c ≡ xV mod r (goto (2) if c = 0).
4. Compute d ≡ u^-1·(f + s·c) mod r (goto (2) if d = 0).
The signature for the message m is the pair of integers (c, d).
ECDSA signature verification. To verify A's signature, B should do the following:
1. Obtain an authentic copy of A's public key (E, G, r, W).
Verify that c and d are integers in the interval [1, r - 1].
2. Compute f = H(m) and h ≡ d^-1 mod r.
3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r.
4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r.
Accept the signature if and only if c1 = c.
To be cryptographically useful, the parameter r should have at least 250 bits.
The basis for the security of elliptic curve cryptosystems
is the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size:
given two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G,
determine an integer k such that W = kG and 0 ≤ k < r.
Task.
The task is to write a toy version of the ECDSA, quasi the equal of a real-world
implementation, but utilizing parameters that fit into standard arithmetic types.
To keep things simple there's no need for key export or a hash function (just a sample
hash value and a way to tamper with it). The program should be lenient where possible
(for example: if it accepts a composite modulus N it will either function as expected,
or demonstrate the principle of elliptic curve factorization)
— but strict where required (a point G that is not on E will always cause failure).
Toy ECDSA is of course completely useless for its cryptographic purpose.
If this bothers you, please add a multiple-precision version.
Reference.
Elliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see:
7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.)
7.1 The EC setting
7.1.2 EC domain parameters
7.1.3 EC key pairs
7.2 Primitives
7.2.7 ECSP-DSA (p. 35)
7.2.8 ECVP-DSA (p. 36)
Annex A. Number-theoretic background
A.9 Elliptic curves: overview (p. 115)
A.10 Elliptic curves: algorithms (p. 121)
| #FreeBASIC | FreeBASIC |
'subject: Elliptic curve digital signature algorithm,
' toy version for small modulus N.
'tested : FreeBasic 1.05.0
'rational ec point
type epnt
as longint x, y
end type
'elliptic curve parameters
type curve
as long a, b
as longint N
as epnt G
as longint r
end type
'signature pair
type pair
as long a, b
end type
'longint for holding intermediate results,
'long variables in exgcd() for efficiency,
'maximum parameter size 2 * p.y (line 118)
'limits the modulus size to 30 bits.
'maximum modulus
const mxN = 1073741789
'max order G = mxN + 65536
const mxr = 1073807325
'symbolic infinity
const inf = -2147483647
'single global curve
dim shared as curve e
'point at infinity zerO
dim shared as epnt zerO
'impossible inverse mod N
dim shared as byte inverr
'return mod(v^-1, u)
Function exgcd (byval v as long, byval u as long) as long
dim as long q, t
dim as long r = 0, s = 1
if v < 0 then v += u
while v
q = u \ v
t = u - q * v
u = v: v = t
t = r - q * s
r = s: s = t
wend
if u <> 1 then
print " impossible inverse mod N, gcd ="; u
inverr = -1
end if
exgcd = r
End Function
'return mod(a, N)
Function modn (byval a as longint) as longint
a mod= e.N
if a < 0 then a += e.N
modn = a
End Function
'return mod(a, r)
Function modr (byval a as longint) as longint
a mod= e.r
if a < 0 then a += e.r
modr = a
End Function
'return the discriminant of E
Function disc as long
dim as longint c, a = e.a, b = e.b
c = 4 * modn(a * modn(a * a))
disc = modn(-16 * (c + 27 * modn(b * b)))
End Function
'return -1 if P = zerO
Function isO (byref p as epnt) as byte
isO = (p.x = inf and p.y = 0)
End Function
'return -1 if P is on curve E
Function ison (byref p as epnt) as byte
dim as long r, s
if not isO (p) then
r = modn(e.b + p.x * modn(e.a + p.x * p.x))
s = modn(p.y * p.y)
end if
ison = (r = s)
End Function
'full ec point addition
Sub padd (byref r as epnt, byref p as epnt, byref q as epnt)
dim as longint la, t
if isO (p) then r = q: exit sub
if isO (q) then r = p: exit sub
if p.x <> q.x then ' R := P + Q
t = p.y - q.y
la = modn(t * exgcd (p.x - q.x, e.N))
else ' P = Q, R := 2P
if (p.y = q.y) and (p.y <> 0) then
t = modn(3 * modn(p.x * p.x) + e.a)
la = modn(t * exgcd (2 * p.y, e.N))
else
r = zerO: exit sub ' P = -Q, R := O
end if
end if
t = modn(la * la - p.x - q.x)
r.y = modn(la * (p.x - t) - p.y)
r.x = t: if inverr then r = zerO
End Sub
'R:= multiple kP
Sub pmul (byref r as epnt, byref p as epnt, byval k as long)
dim as epnt s = zerO, q = p
while k
if k and 1 then padd (s, s, q)
if inverr then s = zerO: exit while
k shr= 1: padd (q, q, q)
wend
r = s
End Sub
'print point P with prefix f
Sub pprint (byref f as string, byref p as epnt)
dim as longint y = p.y
if isO (p) then
print f;" (0)"
else
if y > e.N - y then y -= e.N
print f;" (";str(p.x);",";y;")"
end if
End Sub
'initialize elliptic curve
Function ellinit (i() as long) as byte
dim as long a = i(0), b = i(1)
ellinit = 0: inverr = 0
e.N = i(2)
if (e.N < 5) or (e.N > mxN) then exit function
e.a = modn(a)
e.b = modn(b)
e.G.x = modn(i(3))
e.G.y = modn(i(4))
e.r = i(5)
if (e.r < 5) or (e.r > mxr) then exit function
print : ? "E: y^2 = x^3 + ";str(a);"x +";b;
print " (mod ";str(e.N);")"
pprint ("base point G", e.G)
print "order(G, E) ="; e.r
ellinit = -1
End Function
'signature primitive
Function signature (byval s as longint, byval f as long) as pair
dim as long c, d, u, u1
dim as pair sg
dim as epnt V
print : ? "signature computation"
do
do
u = 1 + int(rnd * (e.r - 1))
pmul (V, e.G, u)
c = modr(V.x)
loop while c = 0
u1 = exgcd (u, e.r)
d = modr(u1 * (f + modr(s * c)))
loop while d = 0
print "one-time u ="; u
pprint ("V = uG", V)
sg.a = c: sg.b = d
signature = sg
End Function
'verification primitive
Function verify (byref W as epnt, byval f as long, byref sg as pair) as byte
dim as long c = sg.a, d = sg.b
dim as long t, c1, h1, h2
dim as longint h
dim as epnt V, V2
verify = 0
'domain check
t = (c > 0) and (c < e.r)
t and= (d > 0) and (d < e.r)
if not t then exit function
print : ? "signature verification"
h = exgcd (d, e.r)
h1 = modr(f * h)
h2 = modr(c * h)
print "h1,h2 ="; h1;",";h2
pmul (V, e.G, h1)
pmul (V2, W, h2)
pprint ("h1G", V)
pprint ("h2W", V2)
padd (V, V, V2)
pprint ("+ =", V)
if isO (V) then exit function
c1 = modr(V.x)
print "c' ="; c1
verify = (c1 = c)
End Function
'digital signature on message hash f, error bit d
Sub ec_dsa (byval f as long, byval d as long)
dim as long i, s, t
dim as pair sg
dim as epnt W
'parameter check
t = (disc = 0)
t or= isO (e.G)
pmul (W, e.G, e.r)
t or= not isO (W)
t or= not ison (e.G)
if t then goto errmsg
print : ? "key generation"
s = 1 + int(rnd * (e.r - 1))
pmul (W, e.G, s)
print "private key s ="; s
pprint ("public key W = sG", W)
'next highest power of 2 - 1
t = e.r: i = 1
while i < 32
t or= t shr i: i shl= 1
wend
while f > t
f shr= 1: wend
print : ? "aligned hash "; hex(f)
sg = signature (s, f)
if inverr then goto errmsg
print "signature c,d ="; sg.a;",";sg.b
if d > 0 then
while d > t
d shr= 1: wend
f xor= d
print : ? "corrupted hash "; hex(f)
end if
t = verify (W, f, sg)
if inverr then goto errmsg
if t then
print "Valid" : ? "_____"
else
print "invalid" : ? "_______"
end if
exit sub
errmsg:
print "invalid parameter set"
print "_____________________"
End Sub
'main
dim as long d, f, t, eparm(5)
zerO.x = inf: zerO.y = 0
randomize timer
'Test vectors: elliptic curve domain parameters,
'short Weierstrass model y^2 = x^3 + ax + b (mod N)
' a, b, modulus N, base point G, order(G, E), cofactor
data 355, 671, 1073741789, 13693, 10088, 1073807281
data 0, 7, 67096021, 6580, 779, 16769911 ' 4
data -3, 1, 877073, 0, 1, 878159
data 0, 14, 22651, 63, 30, 151 ' 151
data 3, 2, 5, 2, 1, 5
'ecdsa may fail if...
'the base point is of composite order
data 0, 7, 67096021, 2402, 6067, 33539822 ' 2
'the given order is a multiple of the true order
data 0, 7, 67096021, 6580, 779, 67079644 ' 1
'the modulus is not prime (deceptive example)
data 0, 7, 877069, 3, 97123, 877069
'fails if the modulus divides the discriminant
data 39, 387, 22651, 95, 27, 22651
data 0, 0, 0
'Digital signature on message hash f,
'set d > 0 to simulate corrupted data
f = &h789ABCDE : d = 0
do
for t = 0 to 5
read eparm(t): next
if ellinit (eparm()) then
ec_dsa (f, d)
else
exit do
end if
loop
system
|
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.
| #ALGOL_68 | ALGOL 68 | # returns TRUE if the specified directory is empty, FALSE if it doesn't exist or is non-empty #
PROC is empty directory = ( STRING directory )BOOL:
IF NOT file is directory( directory )
THEN
# directory doesn't exist #
FALSE
ELSE
# directory is empty if it contains no files or just "." and possibly ".." #
[]STRING files = get directory( directory );
BOOL result := FALSE;
FOR f FROM LWB files TO UPB files
WHILE result := files[ f ] = "." OR files[ f ] = ".."
DO
SKIP
OD;
result
FI # is empty directory # ;
# test the is empty directory procedure #
# show whether the directories specified on the command line ( following "-" ) are empty or not #
BOOL directory name parameter := FALSE;
FOR i TO argc DO
IF argv( i ) = "-"
THEN
# marker to indicate directory names follow #
directory name parameter := TRUE
ELIF directory name parameter
THEN
# have a directory name - report whether it is emty or not #
print( ( argv( i ), " is ", IF is empty directory( argv( i ) ) THEN "empty" ELSE "not empty" FI, newline ) )
FI
OD |
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.
| #Arturo | Arturo | emptyDir?: function [folder]-> empty? list folder
print emptyDir? "." |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #360_Assembly | 360 Assembly | BR 14
END |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #6502_Assembly | 6502 Assembly | org $0801 ;start assembling at this address
db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00 ;required init code
rts ;return to basic |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Factor | Factor | TUPLE: range
{ from read-only } { length read-only } { step read-only } ; |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Forth | Forth |
256 constant one-hex-dollar
s" Hello world" 2constant hello \ "hello" holds the address and length of an anonymous string.
355 119 2constant ratio-pi \ 2constant can also define ratios (e.g. pi)
3.14159265e fconstant pi
|
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Fortran | Fortran | real, parameter :: pi = 3.141593 |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #FreeBASIC | FreeBASIC | #define IMMUT1 32767 'constants can be created in the preprocessor
dim as const uinteger IMMUT2 = 2222 'or explicitly declared as constants
|
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
| #AWK | AWK | #!/usr/bin/awk -f
{
for (i=1; i<= length($0); i++) {
H[substr($0,i,1)]++;
N++;
}
}
END {
for (i in H) {
p = H[i]/N;
E -= p * log(p);
}
print E/log(2);
} |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #BCPL | BCPL | get "libhdr"
let halve(i) = i>>1
and double(i) = i<<1
and even(i) = (i&1) = 0
let emul(x, y) = emulr(x, y, 0)
and emulr(x, y, ac) =
x=0 -> ac,
emulr(halve(x), double(y), even(x) -> ac, ac + y)
let start() be writef("%N*N", emul(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.
| #ERRE | ERRE |
PROGRAM EQUILIBRIUM
DIM LISTA[6]
PROCEDURE EQ(LISTA[]->RES$)
LOCAL I%,R,S,E$
FOR I%=0 TO UBOUND(LISTA,1) DO
S+=LISTA[I%]
END FOR
FOR I%=0 TO UBOUND(LISTA,1) DO
IF R=S-R-LISTA[I%] THEN E$+=STR$(I%)+"," END IF
R+=LISTA[I%]
END FOR
RES$=LEFT$(E$,LEN(E$)-1)
END PROCEDURE
BEGIN
LISTA[]=(-7,1,5,2,-4,3,0)
EQ(LISTA[]->RES$)
PRINT("Equilibrium indices are";RES$)
END PROGRAM
|
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #Euphoria | Euphoria | function equilibrium(sequence s)
integer lower_sum, higher_sum
sequence indices
lower_sum = 0
higher_sum = 0
for i = 1 to length(s) do
higher_sum += s[i]
end for
indices = {}
for i = 1 to length(s) do
higher_sum -= s[i]
if lower_sum = higher_sum then
indices &= i
end if
lower_sum += s[i]
end for
return indices
end function
? equilibrium({-7,1,5,2,-4,3,0}) |
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
| #i | i | software {
print(load("$HOME"))
print(load("$USER"))
print(load("$PATH"))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.