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/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.
#Groovy
Groovy
def isDirEmpty = { dirName -> def dir = new File(dirName) dir.exists() && dir.directory && (dir.list() as List).empty }
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#ArnoldC
ArnoldC
IT'S SHOWTIME YOU HAVE BEEN TERMINATED
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Arturo
Arturo
 
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.
#Ring
Ring
  # Project : Enforced immutability   x = 10 assert( x = 10) assert( x = 100 )  
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.
#Ruby
Ruby
msg = "Hello World" msg << "!" puts msg #=> Hello World!   puts msg.frozen? #=> false msg.freeze puts msg.frozen? #=> true begin msg << "!" rescue => e p e #=> #<RuntimeError: can't modify frozen String> end   puts msg #=> Hello World! msg2 = msg   # The object is frozen, not the variable. msg = "hello world" # A new object was assigned to the variable.   puts msg.frozen? #=> false puts msg2.frozen? #=> true
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.
#Rust
Rust
let x = 3; x += 2;
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.
#Scala
Scala
val pi = 3.14159 val msg = "Hello World"
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is : H 2 ( X ) = − ∑ i = 1 n c o u n t i N log 2 ⁡ ( c o u n t i N ) {\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)} where c o u n t i {\displaystyle count_{i}} is the count of character n i {\displaystyle n_{i}} . For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer. This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where S = k B N H {\displaystyle S=k_{B}NH} where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis. The "total", "absolute", or "extensive" information entropy is S = H 2 N {\displaystyle S=H_{2}N} bits This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have S = N log 2 ⁡ ( 16 ) {\displaystyle S=N\log _{2}(16)} bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits. The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data. Two other "entropies" are useful: Normalized specific entropy: H n = H 2 ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}} which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923. Normalized total (extensive) entropy: S n = H 2 N ∗ log ⁡ ( 2 ) log ⁡ ( n ) {\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}} which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23. Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information". In keeping with Landauer's limit, the physics entropy generated from erasing N bits is S = H 2 N k B ln ⁡ ( 2 ) {\displaystyle S=H_{2}Nk_{B}\ln(2)} if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents. Related tasks Fibonacci_word Entropy/Narcissist
#Crystal
Crystal
# Method to calculate sum of Float64 array def sum(array : Array(Float64)) res = 0 array.each do |n| res += n end res end   # Method to calculate which char appears how often def histogram(source : String) hist = {} of Char => Int32 l = 0 source.each_char do |e| if !hist.has_key? e hist[e] = 0 end hist[e] += 1 end return Tuple.new(source.size, hist) end   # Method to calculate entropy from histogram def entropy(hist : Hash(Char, Int32), l : Int32) elist = [] of Float64 hist.each do |el| v = el[1] c = v / l elist << (-c * Math.log(c, 2)) end return sum elist end   source = "1223334444" hist_res = histogram source l = hist_res[0] h = hist_res[1] puts ".[Results]." puts "Length: " + l.to_s puts "Entropy: " + (entropy h, l).to_s
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
#CoffeeScript
CoffeeScript
  halve = (n) -> Math.floor n / 2 double = (n) -> n * 2 is_even = (n) -> n % 2 == 0   multiply = (a, b) -> prod = 0 while a > 0 prod += b if !is_even a a = halve a b = double b prod   # tests do -> for i in [0..100] for j in [0..100] throw Error("broken for #{i} * #{j}") if multiply(i,j) != i * j  
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.
#jq
jq
# The index origin is 0 in jq. def equilibrium_indices: def indices(a; mx): def report: # [i, headsum, tailsum] .[0] as $i | if $i == mx then empty # all done else .[1] as $h | (.[2] - a[$i]) as $t | (if $h == $t then $i else empty end), ( [ $i + 1, $h + a[$i], $t ] | report ) end; [0, 0, (a|add)] | report; . as $in | indices($in; $in|length);
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.
#Julia
Julia
function equindex2pass(data::Array) rst = Vector{Int}(0) suml, sumr, ddelayed = 0, sum(data), 0 for (i, d) in enumerate(data) suml += ddelayed sumr -= d ddelayed = d if suml == sumr push!(rst, i) end end return rst end   @show equindex2pass([1, -1, 1, -1, 1, -1, 1]) @show equindex2pass([1, 2, 2, 1]) @show equindex2pass([-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
#OCaml
OCaml
Sys.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
#Oforth
Oforth
System getEnv("PATH") println
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
#Oz
Oz
{System.showInfo "This is where Mozart is installed: "#{OS.getEnv 'OZHOME'}}
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
#PARI.2FGP
PARI/GP
getenv("HOME")
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.
#Haskell
Haskell
import Data.List import Data.List.Ordered   main :: IO () main = print $ head [(x0,x1,x2,x3,x4) | -- choose x0, x1, x2, x3 -- so that 250 < x3 < x2 < x1 < x0 x3 <- [1..250-1], x2 <- [1..x3-1], x1 <- [1..x2-1], x0 <- [1..x1-1],   let p5Sum = x0^5 + x1^5 + x2^5 + x3^5,   -- lazy evaluation of powers of 5 let p5List = [i^5|i <- [1..]],   -- is sum a power of 5 ? member p5Sum p5List,   -- which power of 5 is sum ? let Just x4 = elemIndex p5Sum p5List ]
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
#Oberon
Oberon
  MODULE Factorial; IMPORT Out;   VAR i: INTEGER;   PROCEDURE Iterative(n: LONGINT): LONGINT; VAR i, r: LONGINT; BEGIN ASSERT(n >= 0); r := 1; FOR i := n TO 2 BY -1 DO r := r * i END; RETURN r END Iterative;   PROCEDURE Recursive(n: LONGINT): LONGINT; VAR r: LONGINT; BEGIN ASSERT(n >= 0); r := 1; IF n > 1 THEN r := n * Recursive(n - 1) END; RETURN r END Recursive;   BEGIN FOR i := 0 TO 9 DO Out.String("Iterative ");Out.Int(i,0);Out.String('! =');Out.Int(Iterative(i),0);Out.Ln; END; Out.Ln; FOR i := 0 TO 9 DO Out.String("Recursive ");Out.Int(i,0);Out.String('! =');Out.Int(Recursive(i),0);Out.Ln; END END 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.
#Component_Pascal
Component Pascal
  MODULE EvenOdd; IMPORT StdLog,Args,Strings;   PROCEDURE BitwiseOdd(i: INTEGER): BOOLEAN; BEGIN RETURN 0 IN BITS(i) END BitwiseOdd;   PROCEDURE Odd(i: INTEGER): BOOLEAN; BEGIN RETURN (i MOD 2) # 0 END Odd;   PROCEDURE CongruenceOdd(i: INTEGER): BOOLEAN; BEGIN RETURN ((i -1) MOD 2) = 0 END CongruenceOdd;   PROCEDURE Do*; VAR p: Args.Params; i,done,x: INTEGER; BEGIN Args.Get(p); StdLog.String("Builtin function: ");StdLog.Ln;i := 0; WHILE i < p.argc DO Strings.StringToInt(p.args[i],x,done); StdLog.String(p.args[i] + " is:> "); IF ODD(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END; StdLog.Ln;INC(i) END; StdLog.String("Bitwise: ");StdLog.Ln;i:= 0; WHILE i < p.argc DO Strings.StringToInt(p.args[i],x,done); StdLog.String(p.args[i] + " is:> "); IF BitwiseOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END; StdLog.Ln;INC(i) END; StdLog.String("Module: ");StdLog.Ln;i := 0; WHILE i < p.argc DO Strings.StringToInt(p.args[i],x,done); StdLog.String(p.args[i] + " is:> "); IF Odd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END; StdLog.Ln;INC(i) END; StdLog.String("Congruences: ");StdLog.Ln;i := 0; WHILE i < p.argc DO Strings.StringToInt(p.args[i],x,done); StdLog.String(p.args[i] + " is:> "); IF CongruenceOdd(x) THEN StdLog.String("odd") ELSE StdLog.String("even") END; StdLog.Ln;INC(i) END; END Do;  
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.
#Smalltalk
Smalltalk
ODESolver>>eulerOf: f init: y0 from: a to: b step: h | t y | t := a. y := y0. [ t < b ] whileTrue: [ Transcript show: t asString, ' ' , (y printShowingDecimalPlaces: 3); cr. t := t + h. y := y + (h * (f value: t value: y)) ]   ODESolver new eulerOf: [:time :temp| -0.07 * (temp - 20)] init: 100 from: 0 to: 100 step: 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
#Lasso
Lasso
define binomial(n::integer,k::integer) => { #k == 0 ? return 1 local(result = 1) loop(#k) => { #result = #result * (#n - loop_count + 1) / loop_count } return #result } // Tests binomial(5, 3) binomial(5, 4) binomial(60, 30)
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
#Liberty_BASIC
Liberty BASIC
  ' [RC] Binomial Coefficients   print "Binomial Coefficient of "; 5; " and "; 3; " is ",BinomialCoefficient( 5, 3) n =1 +int( 10 *rnd( 1)) k =1 +int( n *rnd( 1)) print "Binomial Coefficient of "; n; " and "; k; " is ",BinomialCoefficient( n, k)   end   function BinomialCoefficient( n, k) BinomialCoefficient =factorial( n) /factorial( n -k) /factorial( k) end function   function factorial( n) if n <2 then f =1 else f =n *factorial( n -1) end if factorial =f end function    
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbers should be in order. Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes. The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer. See also   Wikipedia, Emirp.   The Prime Pages, emirp.   Wolfram MathWorld™, Emirp.   The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
#C.2B.2B
C++
#include <vector> #include <iostream> #include <algorithm> #include <sstream> #include <string> #include <cmath>   bool isPrime ( int number ) { if ( number <= 1 ) return false ; if ( number == 2 ) return true ; for ( int i = 2 ; i <= std::sqrt( number ) ; i++ ) { if ( number % i == 0 ) return false ; } return true ; }   int reverseNumber ( int n ) { std::ostringstream oss ; oss << n ; std::string numberstring ( oss.str( ) ) ; std::reverse ( numberstring.begin( ) , numberstring.end( ) ) ; return std::stoi ( numberstring ) ; }   bool isEmirp ( int n ) { return isPrime ( n ) && isPrime ( reverseNumber ( n ) ) && n != reverseNumber ( n ) ; }   int main( ) { std::vector<int> emirps ; int i = 1 ; while ( emirps.size( ) < 20 ) { if ( isEmirp( i ) ) { emirps.push_back( i ) ; } i++ ; } std::cout << "The first 20 emirps:\n" ; for ( int i : emirps ) std::cout << i << " " ; std::cout << '\n' ; int newstart = 7700 ; while ( newstart < 8001 ) { if ( isEmirp ( newstart ) ) std::cout << newstart << '\n' ; newstart++ ; } while ( emirps.size( ) < 10000 ) { if ( isEmirp ( i ) ) { emirps.push_back( i ) ; } i++ ; } std::cout << "the 10000th emirp is " << emirps[9999] << " !\n" ;   return 0 ; }
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).
#PARI.2FGP
PARI/GP
e=ellinit([0,7]); a=[-6^(1/3),1] b=[-3^(1/3),2] c=elladd(e,a,b) d=ellneg(e,c) elladd(e,c,d) elladd(e,elladd(e,a,b),d) ellmul(e,a,12345)
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:   y 2 = x 3 + a x + b {\displaystyle y^{2}=x^{3}+ax+b} a and b are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters:   a=0,   b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it. To do so we define an   internal composition   rule with an additive notation +,   such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:   P + Q + R = 0 Here   0   (zero)   is the infinity point,   for which the x and y values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry. We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition. This was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such: Given any three aligned points P, Q and R,   we define the sum   S = P + Q   as the point (possibly the infinity point) such that   S, R   and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet). S is thus defined as the symmetric of R towards the x axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the a and b parameters of secp256k1, i.e. respectively zero and seven. Hint:   You might need to define a "doubling" function, that returns P+P for any given point P. Extra credit:   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point P and integer n,   the point P + P + ... + P     (n times).
#Perl
Perl
package EC; { our ($A, $B) = (0, 7); package EC::Point; sub new { my $class = shift; bless [ @_ ], $class } sub zero { bless [], shift } sub x { shift->[0] }; sub y { shift->[1] }; sub double { my $self = shift; return $self unless @$self; my $L = (3 * $self->x**2) / (2*$self->y); my $x = $L**2 - 2*$self->x; bless [ $x, $L * ($self->x - $x) - $self->y ], ref $self; } use overload '==' => sub { my ($p, $q) = @_; $p->x == $q->x and $p->y == $q->y }, '+' => sub { my ($p, $q) = @_; return $p->double if $p == $q; return $p unless @$q; return $q unless @$p; my $slope = ($q->y - $p->y) / ($q->x - $p->x); my $x = $slope**2 - $p->x - $q->x; bless [ $x, $slope * ($p->x - $x) - $p->y ], ref $p; }, q{""} => sub { my $self = shift; return @$self ? sprintf "EC-point at x=%f, y=%f", @$self : 'EC point at infinite'; } }   package Test; my $p = +EC::Point->new(-($EC::B - 1)**(1/3), 1); my $q = +EC::Point->new(-($EC::B - 4)**(1/3), 2); my $s = $p + $q, "\n"; print "$_\n" for $p, $q, $s; print "check alignment... "; print abs(($q->x - $p->x)*(-$s->y - $p->y) - ($q->y - $p->y)*($s->x - $p->x)) < 0.001 ? "ok" : "wrong";
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Metafont
Metafont
vardef enum(expr first)(text t) = save ?; ? := first; forsuffixes e := t: e := ?; ?:=?+1; endfor enddef;
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Modula-3
Modula-3
TYPE Fruit = {Apple, Banana, Cherry};
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Nemerle
Nemerle
enum Fruit { |apple |banana |cherry }   enum Season { |winter = 1 |spring = 2 |summer = 3 |autumn = 4 }
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Ruby
Ruby
size = 100 eca = ElemCellAutomat.new("1"+"0"*(size-1), 30) eca.take(80).map{|line| line[0]}.each_slice(8){|bin| p bin.join.to_i(2)}
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Rust
Rust
  //Assuming the code from the Elementary cellular automaton task is in the namespace. fn main() { struct WolfGen(ElementaryCA); impl WolfGen { fn new() -> WolfGen { let (_, ca) = ElementaryCA::new(30); WolfGen(ca) } fn next(&mut self) -> u8 { let mut out = 0; for i in 0..8 { out |= ((1 & self.0.next())<<i)as u8; } out } } let mut gen = WolfGen::new(); for _ in 0..10 { print!("{} ", gen.next()); } }  
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Scheme
Scheme
  ; uses SRFI-1 library http://srfi.schemers.org/srfi-1/srfi-1.html   (define (random-r30 n) (let ((r30 (vector 0 1 1 1 1 0 0 0))) (fold (lambda (x y ls) (if (= x 1) (cons (* x y) ls) (cons (+ (car ls) (* x y)) (cdr ls)))) '() (circular-list 1 2 4 8 16 32 64 128) (unfold-right (lambda (x) (zero? (car x))) cadr (lambda (x) (cons (- (car x) 1) (evolve (cdr x) r30))) (cons (* 8 n) (cons 1 (make-list 79 0))))))) ; list   (random-r30 10)  
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BASIC
BASIC
10 LET A$="" 20 IF A$="" THEN PRINT "THE STRING IS EMPTY" 30 IF A$<>"" THEN PRINT "THE STRING IS NOT EMPTY" 40 END
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
#Batch_File
Batch File
  @echo off ::set "var" as a blank string. set var= ::check if "var" is a blank string. if not defined var echo Var is a blank string. ::Alternatively, if %var%@ equ @ echo Var is a blank string. ::check if "var" is not a blank string. if defined var echo Var is defined. ::Alternatively, if %var%@ neq @ echo Var is not a blank string.  
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#Haskell
Haskell
import System.Directory (getDirectoryContents) import System.Environment (getArgs)     isEmpty x = getDirectoryContents x >>= return . f . (== [".", ".."]) where f True = "Directory is empty" f False = "Directory is not empty"   main = getArgs >>= isEmpty . (!! 0) >>= putStrLn
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() every dir := "." | "./empty" do write(dir, if isdirempty(dir) then " is empty" else " is not empty") end   procedure isdirempty(s) #: succeeds if directory s is empty (and a directory) local d,f if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { while f := read(d) do if f == ("."|"..") then next else fail close(d) return s } else stop(s," is not a directory or will not open") end
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Asymptote
Asymptote
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#AutoHotkey
AutoHotkey
#Persistent
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.
#Scheme
Scheme
(define-syntax define-constant (syntax-rules () ((_ id v) (begin (define _id v) (define-syntax id (make-variable-transformer (lambda (stx) (syntax-case stx (set!) ((set! id _) (raise (syntax-violation 'set! "Cannot redefine constant" stx #'id))) ((id . args) #'(_id . args)) (id #'_id)))))))))
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.
#Seed7
Seed7
const integer: foo is 42; const string: bar is "bar"; const blahtype: blah is blahvalue;
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.
#Sidef
Sidef
define PI = 3.14159; # compile-time defined constant const MSG = "Hello world!"; # run-time defined 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.
#SuperCollider
SuperCollider
// you can freeze any object. b = [1, 2, 3]; b[1] = 100; // returns [1, 100, 3] b.freeze; // make b immutable b[1] = 2; // throws an error ("Attempted write to immutable object.")
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
#D
D
import std.stdio, std.algorithm, std.math;   double entropy(T)(T[] s) pure nothrow if (__traits(compiles, s.sort())) { immutable sLen = s.length; return s .sort() .group .map!(g => g[1] / double(sLen)) .map!(p => -p * p.log2) .sum; }   void main() { "1223334444"d.dup.entropy.writeln; }
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
#ColdFusion
ColdFusion
<cffunction name="double"> <cfargument name="number" type="numeric" required="true"> <cfset answer = number * 2> <cfreturn answer> </cffunction>   <cffunction name="halve"> <cfargument name="number" type="numeric" required="true"> <cfset answer = int(number / 2)> <cfreturn answer> </cffunction>   <cffunction name="even"> <cfargument name="number" type="numeric" required="true"> <cfset answer = number mod 2> <cfreturn answer> </cffunction>   <cffunction name="ethiopian"> <cfargument name="Number_A" type="numeric" required="true"> <cfargument name="Number_B" type="numeric" required="true"> <cfset Result = 0>   <cfloop condition = "Number_A GTE 1"> <cfif even(Number_A) EQ 1> <cfset Result = Result + Number_B> </cfif> <cfset Number_A = halve(Number_A)> <cfset Number_B = double(Number_B)> </cfloop> <cfreturn Result> </cffunction>     <cfoutput>#ethiopian(17,34)#</cfoutput>
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.
#K
K
f:{&{(+/y# x)=+/(y+1)_x}[x]'!#x}   f -7 1 5 2 -4 3 0 3 6   f 2 4 6 !0   f 2 9 2 ,1   f 1 -1 1 -1 1 -1 1 0 1 2 3 4 5 6
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.
#Kotlin
Kotlin
// version 1.1   fun equilibriumIndices(a: IntArray): MutableList<Int> { val ei = mutableListOf<Int>() if (a.isEmpty()) return ei // empty list val sumAll = a.sumBy { it } var sumLeft = 0 var sumRight: Int for (i in 0 until a.size) { sumRight = sumAll - sumLeft - a[i] if (sumLeft == sumRight) ei.add(i) sumLeft += a[i] } return ei }   fun main(args: Array<String>) { val a = intArrayOf(-7, 1, 5, 2, -4, 3, 0) val ei = equilibriumIndices(a) when (ei.size) { 0 -> println("There are no equilibrium indices") 1 -> println("The only equilibrium index is : ${ei[0]}") else -> println("The equilibrium indices are : ${ei.joinToString(", ")}") } }
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
#Perl
Perl
print $ENV{HOME}, "\n";
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
#Phix
Phix
without js -- none such in a browser, that I know of ?getenv("PATH")
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#PHP
PHP
$_ENV['HOME']
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#PicoLisp
PicoLisp
: (sys "TERM") -> "xterm"   : (sys "SHELL") -> "/bin/bash"
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.
#J
J
require 'stats' (#~ (= <.)@((+/"1)&.:(^&5)))1+4 comb 248 27 84 110 133
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
#Objeck
Objeck
bundle Default { class Fact { function : Main(args : String[]) ~ Nil { 5->Factorial()->PrintLine(); } } }
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.
#Crystal
Crystal
#Using bitwise shift def isEven_bShift(n) n == ((n >> 1) << 1) end def isOdd_bShift(n) n != ((n >> 1) << 1) end #Using modulo operator def isEven_mod(n) (n % 2) == 0 end def isOdd_mod(n) (n % 2) != 0 end # Using bitwise "and" def isEven_bAnd(n) (n & 1) == 0 end def isOdd_bAnd(n) (n & 1) != 0 end   puts isEven_bShift(7) puts isOdd_bShift(7)   puts isEven_mod(12) puts isOdd_mod(12)   puts isEven_bAnd(21) puts isOdd_bAnd(21)  
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.
#D
D
void main() { import std.stdio, std.bigint;   foreach (immutable i; -5 .. 6) writeln(i, " ", i & 1, " ", i % 2, " ", i.BigInt % 2); }
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.
#Swift
Swift
import Foundation   let numberFormat = " %7.3f" let k = 0.07 let initialTemp = 100.0 let finalTemp = 20.0 let startTime = 0 let endTime = 100   func ivpEuler(function: (Double, Double) -> Double, initialValue: Double, step: Int) { print(String(format: " Step %2d: ", step), terminator: "") var y = initialValue for t in stride(from: startTime, through: endTime, by: step) { if t % 10 == 0 { print(String(format: numberFormat, y), terminator: "") } y += Double(step) * function(Double(t), y) } print() }   func analytic() { print(" Time: ", terminator: "") for t in stride(from: startTime, through: endTime, by: 10) { print(String(format: " %7d", t), terminator: "") } print("\nAnalytic: ", terminator: "") for t in stride(from: startTime, through: endTime, by: 10) { let temp = finalTemp + (initialTemp - finalTemp) * exp(-k * Double(t)) print(String(format: numberFormat, temp), terminator: "") } print() }   func cooling(t: Double, temp: Double) -> Double { return -k * (temp - finalTemp) }   analytic() ivpEuler(function: cooling, initialValue: initialTemp, step: 2) ivpEuler(function: cooling, initialValue: initialTemp, step: 5) ivpEuler(function: cooling, initialValue: initialTemp, step: 10)
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.
#Tcl
Tcl
proc euler {f y0 a b h} { puts "computing $f over \[$a..$b\], step $h" set y [expr {double($y0)}] for {set t [expr {double($a)}]} {$t < $b} {set t [expr {$t + $h}]} { puts [format "%.3f\t%.3f" $t $y] set y [expr {$y + $h * double([$f $t $y])}] } puts "done" }
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
#Logo
Logo
to choose :n :k if :k = 0 [output 1] output (choose :n :k-1) * (:n - :k + 1) / :k end   show choose 5 3  ; 10 show choose 60 30 ; 1.18264581564861e+17
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
#Lua
Lua
function Binomial( n, k ) if k > n then return nil end if k > n/2 then k = n - k end -- (n k) = (n n-k)   numer, denom = 1, 1 for i = 1, k do numer = numer * ( n - i + 1 ) denom = denom * i end return numer / denom end
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbers should be in order. Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes. The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer. See also   Wikipedia, Emirp.   The Prime Pages, emirp.   Wolfram MathWorld™, Emirp.   The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
#Clojure
Clojure
(defn emirp? [v] (let [a (biginteger v) b (biginteger (clojure.string/reverse (str v)))] (and (not= a b) (.isProbablePrime a 16) (.isProbablePrime b 16))))   ; Generate the output (println "first20: " (clojure.string/join " " (take 20 (filter emirp? (iterate inc 0))))) (println "7700-8000: " (clojure.string/join " " (filter emirp? (range 7700 8000)))) (println "10,000: " (nth (filter emirp? (iterate inc 0)) 9999))    
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).
#Phix
Phix
with javascript_semantics constant X=1, Y=2, bCoeff=7, INF = 1e300*1e300 type point(object pt) return sequence(pt) and length(pt)=2 and atom(pt[X]) and atom(pt[Y]) end type function zero() point pt = {INF, INF} return pt end function function is_zero(point p) return p[X]>1e20 or p[X]<-1e20 end function function neg(point p) p = {p[X], -p[Y]} return p end function function dbl(point p) point r = p if not is_zero(p) then atom L = (3*p[X]*p[X])/(2*p[Y]) atom x = L*L-2*p[X] r = {x, L*(p[X]-x)-p[Y]} end if return r end function function add(point p, point q) if p==q then return dbl(p) end if if is_zero(p) then return q end if if is_zero(q) then return p end if atom L = (q[Y]-p[Y])/(q[X]-p[X]) atom x = L*L-p[X]-q[X] point r = {x, L*(p[X]-x)-p[Y]} return r end function function mul(point p, integer n) point r = zero() integer i = 1 while i<=n do if and_bits(i, n) then r = add(r, p) end if p = dbl(p) i = i*2 end while return r end function procedure show(string s, point p) puts(1, s&iff(is_zero(p)?"Zero\n":sprintf("(%.3f, %.3f)\n", p))) end procedure function cbrt(atom c) return iff(c>=0?power(c,1/3):-power(-c,1/3)) end function function from_y(atom y) point r = {cbrt(y*y-bCoeff), y} return r end function point a, b, c, d a = from_y(1) b = from_y(2) c = add(a, b) d = neg(c) show("a = ", a) show("b = ", b) show("c = a + b = ", c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345))
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Nim
Nim
# Simple declaration. type Fruits1 = enum aApple, aBanana, aCherry   # Specifying values (accessible using "ord"). type Fruits2 = enum bApple = 0, bBanana = 2, bCherry = 5   # Enumerations with a scope which prevent name conflict. type Fruits3 {.pure.} = enum Apple, Banana, Cherry type Fruits4 {.pure.} = enum Apple = 3, Banana = 8, Cherry = 10 var x = Fruits3.Apple # Need to qualify as there are several possible "Apple".   # Using vertical presentation and specifying string representation. type Fruits5 = enum cApple = "Apple" cBanana = "Banana" cCherry = "Cherry" echo cApple # Will display "Apple".   # Specifying values and/or string representation. type Fruits6 = enum Apple = (1, "apple") Banana = 3 # implicit name is "Banana". Cherry = "cherry" # implicit value is 4.
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Objeck
Objeck
  enum Color := -3 { Red, White, Blue }   enum Dog { Pug, Boxer, Terrier }  
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Objective-C
Objective-C
typedef NS_ENUM(NSInteger, fruits) { apple, banana, cherry };   typedef NS_ENUM(NSInteger, fruits) { apple = 0, banana = 1, cherry = 2 };
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Sidef
Sidef
var auto = Automaton(30, [1] + 100.of(0));   10.times { var sum = 0; 8.times { sum = (2*sum + auto.cells[0]); auto.next; }; say sum; };
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Tcl
Tcl
oo::class create RandomGenerator { superclass ElementaryAutomaton variable s constructor {stateLength} { next 30 set s [split 1[string repeat 0 $stateLength] ""] }   method rand {} { set bits {} while {[llength $bits] < 8} { lappend bits [lindex $s 0] set s [my evolve $s] } return [scan [join $bits ""] %b] } }
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#Wren
Wren
import "/big" for BigInt   var n = 64   var pow2 = Fn.new { |x| BigInt.one << x }   var evolve = Fn.new { |state, rule| for (p in 0..9) { var b = BigInt.zero for (q in 7..0) { var st = state.copy() b = b | ((st & 1) << q) state = BigInt.zero for (i in 0...n) { var t1 = (i > 0) ? st >> (i-1) : st >> 63 var t2 = (i == 0) ? st << 1 : (i == 1) ? st << 63 : st << (n+1-i) var t3 = (t1 | t2) & 7 if ((pow2.call(t3) & rule) != BigInt.zero) state = state | pow2.call(i) } } System.write(" %(b)") } System.print() }   evolve.call(BigInt.one, 30)
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
#BBC_BASIC
BBC BASIC
REM assign an empty string to a variable: var$ = ""   REM Check that a string is empty: IF var$ = "" THEN PRINT "String is empty"   REM Check that a string is not empty: IF var$ <> "" THEN PRINT "String is not empty"  
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BQN
BQN
•Show "" •Show 0 = ≠ "" •Show 0 ≠ ≠ "" •Show "" ≡ ⟨⟩
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.
#J
J
require 'dir' empty_dir=: 0 = '/*' #@dir@,~ ]
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.
#Java
Java
import java.nio.file.Paths; //... other class code here public static boolean isEmptyDir(String dirName){ return Paths.get(dirName).toFile().listFiles().length == 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.
#JavaScript
JavaScript
// Node.js v14.15.4 const { readdirSync } = require("fs"); const emptydir = (path) => readdirSync(path).length == 0;   // tests, run like node emptydir.js [directories] for (let i = 2; i < process.argv.length; i ++) { let dir = process.argv[i]; console.log(`${dir}: ${emptydir(dir) ? "" : "not "}empty`) }
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#AutoIt
AutoIt
;nothing
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Avail
Avail
Module "a" Body
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.
#Swift
Swift
let a = 1 a = 1 // error: a is immutable var b = 1 b = 1
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.
#Tcl
Tcl
proc constant {varName {value ""}} { upvar 1 $varName var # Allow application of immutability to an existing variable, e.g., a procedure argument if {[llength [info frame 0]] == 2} {set value $var} else {set var $value} trace add variable var write [list apply {{val v1 v2 op} { upvar 1 $v1 var set var $val; # Restore to what it should be return -code error "immutable" }} $value] }
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.
#UNIX_Shell
UNIX Shell
PIE=APPLE readonly PIE
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.
#XPL0
XPL0
define Pi=3.14; Pi:= 3.15; \causes a compile error: statement starting with a constant  
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
#Delphi
Delphi
  program Entropytest;   uses StrUtils, Math;   type FArray = array of CARDINAL;   var strng: string = '1223334444';   // list unique characters in a string function uniquechars(str: string): string; var n: CARDINAL; begin Result := ''; for n := 1 to length(str) do if (PosEx(str[n], str, n) > 0) and (PosEx(str[n], Result, 1) = 0) then Result := Result + str[n]; end;   // obtain a list of character-frequencies for a string // given a string containing its unique characters function frequencies(str, ustr: string): FArray; var u, s, p, o: CARDINAL; begin SetLength(Result, Length(ustr) + 1); p := 0; for u := 1 to length(ustr) do for s := 1 to length(str) do begin o := p; p := PosEx(ustr[u], str, s); if (p > o) then INC(Result[u]); end; end;   // Obtain the Shannon entropy of a string function entropy(s: string): EXTENDED; var pf: FArray; us: string; i, l: CARDINAL; begin us := uniquechars(s); pf := frequencies(s, us); l := length(s); Result := 0.0; for i := 1 to length(us) do Result := Result - pf[i] / l * log2(pf[i] / l); end;   begin Writeln('Entropy of "', strng, '" is ', entropy(strng): 2: 5, ' bits.'); readln; 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
#Common_Lisp
Common Lisp
(defun ethiopian-multiply (l r) (flet ((halve (n) (floor n 2)) (double (n) (* n 2)) (even-p (n) (zerop (mod n 2)))) (do ((product 0 (if (even-p l) product (+ product r))) (l l (halve l)) (r r (double r))) ((zerop l) product))))
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.
#Liberty_BASIC
Liberty BASIC
  a(0)=-7 a(1)=1 a(2)=5 a(3)=2 a(4)=-4 a(5)=3 a(6)=0   print "EQ Indices are ";EQindex$("a",0,6)   wait   function EQindex$(b$,mini,maxi) if mini>=maxi then exit function sum=0 for i = mini to maxi sum=sum+eval(b$;"(";i;")") next sumA=0:sumB=sum for i = mini to maxi sumB = sumB - eval(b$;"(";i;")") if sumA=sumB then EQindex$=EQindex$+str$(i)+", " sumA = sumA + eval(b$;"(";i;")") next if len(EQindex$)>0 then EQindex$=mid$(EQindex$, 1, len(EQindex$)-2) 'remove last ", " end function  
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
#Pike
Pike
write("%s\n", 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
#PowerShell
PowerShell
$Env:Path
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Prolog
Prolog
 ?- getenv('TEMP', Temp).
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
#PureBasic
PureBasic
GetEnvironmentVariable("Name")
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.
#Java
Java
public class eulerSopConjecture {   static final int MAX_NUMBER = 250;   public static void main( String[] args ) { boolean found = false; long[] fifth = new long[ MAX_NUMBER ];   for( int i = 1; i <= MAX_NUMBER; i ++ ) { long i2 = i * i; fifth[ i - 1 ] = i2 * i2 * i; } // for i   for( int a = 0; a < MAX_NUMBER && ! found ; a ++ ) { for( int b = a; b < MAX_NUMBER && ! found ; b ++ ) { for( int c = b; c < MAX_NUMBER && ! found ; c ++ ) { for( int d = c; d < MAX_NUMBER && ! found ; d ++ ) { long sum = fifth[a] + fifth[b] + fifth[c] + fifth[d]; int e = java.util.Arrays.binarySearch( fifth, sum ); found = ( e >= 0 ); if( found ) { // the value at e is a fifth power System.out.print( (a+1) + "^5 + " + (b+1) + "^5 + " + (c+1) + "^5 + " + (d+1) + "^5 = " + (e+1) + "^5" ); } // if found;; } // for d } // for c } // for b } // for a } // main   } // eulerSopConjecture
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
#OCaml
OCaml
let rec factorial n = if n <= 0 then 1 else n * factorial (n-1)
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#DCL
DCL
$! in DCL, for integers, the least significant bit determines the logical value, where 1 is true and 0 is false $ $ i = -5 $ loop1: $ if i then $ write sys$output i, " is odd" $ if .not. i then $ write sys$output i, " is even" $ i = i + 1 $ if i .le. 6 then $ goto loop1
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.
#VBA
VBA
Private Sub ivp_euler(f As String, y As Double, step As Integer, end_t As Integer) Dim t As Integer Debug.Print " Step "; step; ": ", Do While t <= end_t If t Mod 10 = 0 Then Debug.Print Format(y, "0.000"), y = y + step * Application.Run(f, y) t = t + step Loop Debug.Print End Sub   Sub analytic() Debug.Print " Time: ", For t = 0 To 100 Step 10 Debug.Print " "; t, Next t Debug.Print Debug.Print "Analytic: ", For t = 0 To 100 Step 10 Debug.Print Format(20 + 80 * Exp(-0.07 * t), "0.000"), Next t Debug.Print End Sub   Private Function cooling(temp As Double) As Double cooling = -0.07 * (temp - 20) End Function   Public Sub euler_method() Dim r_cooling As String r_cooling = "cooling" analytic ivp_euler r_cooling, 100, 2, 100 ivp_euler r_cooling, 100, 5, 100 ivp_euler r_cooling, 100, 10, 100 End Sub
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
#Maple
Maple
convert(binomial(n,k),factorial);   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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
(Local) In[1]:= Binomial[5,3] (Local) Out[1]= 10
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbers should be in order. Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes. The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer. See also   Wikipedia, Emirp.   The Prime Pages, emirp.   Wolfram MathWorld™, Emirp.   The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
#Common_Lisp
Common Lisp
(defun primep (n) "Is N prime?" (and (> n 1) (or (= n 2) (oddp n)) (loop for i from 3 to (isqrt n) by 2 never (zerop (rem n i)))))   (defun reverse-digits (n) (labels ((next (n v) (if (zerop n) v (multiple-value-bind (q r) (truncate n 10) (next q (+ (* v 10) r)))))) (next n 0)))   (defun emirp (&key (count nil) (start 10) (end nil) (print-all nil)) (do* ((n start (1+ n)) (c count) ) ((or (and count (<= c 0)) (and end (>= n end)))) (when (and (primep n) (not (= n (reverse-digits n))) (primep (reverse-digits n))) (when print-all (format t "~a " n)) (when count (decf c)) )))     (progn (format t "First 20 emirps: ") (emirp :count 20 :print-all t) (format t "~%Emirps between 7700 and 8000: ") (emirp :start 7700 :end 8000 :print-all t) (format t "~%The 10,000'th emirp: ") (emirp :count 10000 :print-all nil) )  
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).
#PicoLisp
PicoLisp
(scl 16) (load "@lib/math.l") (setq *B 7) (de from_y (Y) (let (A (* 1.0 (- (* Y Y) *B)) B (pow (abs A) (*/ 1.0 1.0 3.0)) ) (list (if (gt0 A) B (- B)) (* Y 1.0) ) ) ) (de prn (P) (if (is_zero P) "Zero" (pack (round (car P) 3) " " (round (cadr P) 3) ) ) ) (de neg (P) (list (car P) (*/ -1.0 (cadr P) 1.0)) ) (de is_zero (P) (or (=T (car P)) (=T (cadr P)) (> (length (car P)) 20) ) ) (de dbl (P) (if (is_zero P) P (let (Y (*/ 1.0 (*/ 3.0 (car P) (car P) (** 1.0 2)) (*/ 2.0 (cadr P) 1.0) ) X (- (*/ Y Y 1.0) (*/ 2.0 (car P) 1.0) ) ) (list X (- (*/ Y (- (car P) X) 1.0) (cadr P) ) ) ) ) ) (de add (A B) (cond ((= A B) (dbl A)) ((is_zero A) B) ((is_zero B) A) (T (let Z (- (car B) (car A)) (if (=0 Z) (list T T) (let (Y (*/ 1.0 (- (cadr B) (cadr A)) Z) X (- (*/ Y Y 1.0) (car A) (car B)) ) (list X (- (*/ Y (- (car A) X) 1.0) (cadr A) ) ) ) ) ) ) ) ) (de mul (P N) (let R (list T T) (for (I 1 (>= N I) (* I 2)) (when (gt0 (& I N)) (setq R (add R P)) ) (setq P (dbl P)) ) R ) ) (setq A (from_y 1) B (from_y 2) ) (prinl "A: " (prn A)) (prinl "B: " (prn B)) (setq C (add A B)) (prinl "C: " (prn C)) (setq D (neg C)) (prinl "D: " (prn D)) (prinl "D + C: " (prn (add C D))) (prinl "A + B + D: " (prn (add A (add B D)))) (prinl "A * 12345: " (prn (mul A 12345)))
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:   y 2 = x 3 + a x + b {\displaystyle y^{2}=x^{3}+ax+b} a and b are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters:   a=0,   b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it. To do so we define an   internal composition   rule with an additive notation +,   such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:   P + Q + R = 0 Here   0   (zero)   is the infinity point,   for which the x and y values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry. We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition. This was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such: Given any three aligned points P, Q and R,   we define the sum   S = P + Q   as the point (possibly the infinity point) such that   S, R   and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet). S is thus defined as the symmetric of R towards the x axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the a and b parameters of secp256k1, i.e. respectively zero and seven. Hint:   You might need to define a "doubling" function, that returns P+P for any given point P. Extra credit:   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point P and integer n,   the point P + P + ... + P     (n times).
#Python
Python
#!/usr/bin/env python3   class Point: b = 7 def __init__(self, x=float('inf'), y=float('inf')): self.x = x self.y = y   def copy(self): return Point(self.x, self.y)   def is_zero(self): return self.x > 1e20 or self.x < -1e20   def neg(self): return Point(self.x, -self.y)   def dbl(self): if self.is_zero(): return self.copy() try: L = (3 * self.x * self.x) / (2 * self.y) except ZeroDivisionError: return Point() x = L * L - 2 * self.x return Point(x, L * (self.x - x) - self.y)   def add(self, q): if self.x == q.x and self.y == q.y: return self.dbl() if self.is_zero(): return q.copy() if q.is_zero(): return self.copy() try: L = (q.y - self.y) / (q.x - self.x) except ZeroDivisionError: return Point() x = L * L - self.x - q.x return Point(x, L * (self.x - x) - self.y)   def mul(self, n): p = self.copy() r = Point() i = 1 while i <= n: if i&n: r = r.add(p) p = p.dbl() i <<= 1 return r   def __str__(self): return "({:.3f}, {:.3f})".format(self.x, self.y)   def show(s, p): print(s, "Zero" if p.is_zero() else p)   def from_y(y): n = y * y - Point.b x = n**(1./3) if n>=0 else -((-n)**(1./3)) return Point(x, y)   # demonstrate a = from_y(1) b = from_y(2) show("a =", a) show("b =", b) c = a.add(b) show("c = a + b =", c) 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.
#OCaml
OCaml
type fruit = | Apple | Banana | Cherry
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Oforth
Oforth
[ $apple, $banana, $cherry ] const: Fruits
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Ol
Ol
  (define fruits '{ apple 0 banana 1 cherry 2}) ; or (define fruits { 'apple 0 'banana 1 'cherry 2})   ; getting enumeration value: (print (get fruits 'apple -1)) ; ==> 0 ; or simply (print (fruits 'apple)) ; ==> 0 ; or simply with default (for non existent enumeration key) value (print (fruits 'carrot -1)) ; ==> -1   ; simple function to create enumeration with autoassigning values (define (make-enumeration . args) (fold (lambda (ff arg i) (put ff arg i)) #empty args (iota (length args))))   (print (make-enumeration 'apple 'banana 'cherry)) ; ==> '#ff((apple . 0) (banana . 1) (cherry . 2))  
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. Reference Cellular automata: Is Rule 30 random? (PDF).
#zkl
zkl
fcn rule(n){ n=n.toString(2); "00000000"[n.len() - 8,*] + n } fcn applyRule(rule,cells){ cells=String(cells[-1],cells,cells[0]); // wrap edges (cells.len() - 2).pump(String,'wrap(n){ rule[7 - cells[n,3].toInt(2)] }) } fcn rand30{ var r30=rule(30), cells="0"*63 + 1; // 64 bits (8 bytes), arbitrary n:=0; do(8){ n=n*2 + cells[-1]; // append bit 0 cells=applyRule(r30,cells); // next state } n }
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
#Bracmat
Bracmat
( :?a & (b=) & abra:?c & (d=cadabra) & !a: { a is empty string } & !b: { b is also empty string } & !c:~ { c is not an empty string } & !d:~ { neither is d an empty string } )  
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Burlesque
Burlesque
  blsq ) "" "" blsq ) ""nu 1 blsq ) "a"nu 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.
#Julia
Julia
# v0.6.0 isemptydir(dir::AbstractString) = isempty(readdir(dir))   @show isemptydir(".") @show isemptydir("/home")  
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.
#Kotlin
Kotlin
// version 1.1.4   import java.io.File   fun main(args: Array<String>) { val dirPath = "docs" // or whatever val isEmpty = (File(dirPath).list().isEmpty()) println("$dirPath is ${if (isEmpty) "empty" else "not empty"}") }
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
#Lasso
Lasso
dir('has_content') -> isEmpty '<br />' dir('no_content') -> isEmpty