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/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.
| #Lua | Lua | T0 = 100
TR = 20
k = 0.07
delta_t = { 2, 5, 10 }
n = 100
NewtonCooling = function( t ) return -k * ( t - TR ) end
function Euler( f, y0, n, h )
local y = y0
for x = 0, n, h do
print( "", x, y )
y = y + h * f( y )
end
end
for i = 1, #delta_t do
print( "delta_t = ", delta_t[i] )
Euler( NewtonCooling, T0, n, delta_t[i] )
end
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
(
k
−
2
)
…
1
{\displaystyle {\binom {n}{k}}={\frac {n!}{(n-k)!k!}}={\frac {n(n-1)(n-2)\ldots (n-k+1)}{k(k-1)(k-2)\ldots 1}}}
See Also:
Combinations and permutations
Pascal's triangle
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Unimportant
Order Important
Without replacement
(
n
k
)
=
n
C
k
=
n
(
n
−
1
)
…
(
n
−
k
+
1
)
k
(
k
−
1
)
…
1
{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}
n
P
k
=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)
{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}
Task: Combinations
Task: Permutations
With replacement
(
n
+
k
−
1
k
)
=
n
+
k
−
1
C
k
=
(
n
+
k
−
1
)
!
(
n
−
1
)
!
k
!
{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}
n
k
{\displaystyle n^{k}}
Task: Combinations with repetitions
Task: Permutations with repetitions
| #dc | dc | [sx1q]sz[d0=zd1-lfx*]sf[skdlfxrlk-lfxlklfx*/]sb |
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
| #Delphi | Delphi | program Binomial;
{$APPTYPE CONSOLE}
function BinomialCoff(N, K: Cardinal): Cardinal;
var
L: Cardinal;
begin
if N < K then
Result:= 0 // Error
else begin
if K > N - K then
K:= N - K; // Optimization
Result:= 1;
L:= 0;
while L < K do begin
Result:= Result * (N - L);
Inc(L);
Result:= Result div L;
end;
end;
end;
begin
Writeln('C(5,3) is ', BinomialCoff(5, 3));
ReadLn;
end. |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #WDTE | WDTE | let memo fib n => n { > 1 => + (fib (- n 1)) (fib (- n 2)) }; |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Erlang | Erlang | #! /usr/bin/escript
-define(LOG2E, 1.44269504088896340735992).
main(_) ->
Self = escript:script_name(),
{ok, Contents} = file:read_file(Self),
io:format("My entropy is ~p~n", [entropy(Contents)]).
entropy(Data) ->
Frq = count(Data),
maps:fold(fun(_, C, E) ->
P = C / byte_size(Data),
E - P*math:log(P)
end, 0, Frq) * ?LOG2E.
count(Data) -> count(Data, 0, #{}).
count(Data, I, Frq) when I =:= byte_size(Data) -> Frq;
count(Data, I, Frq) ->
Chr = binary:at(Data, I),
case Frq of
#{Chr := K} -> count(Data, I+1, Frq #{Chr := K+1});
_ -> count(Data, I+1, Frq #{Chr => 1})
end.
|
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Factor | Factor | USING: assocs io io.encodings.utf8 io.files kernel math
math.functions math.statistics prettyprint sequences ;
IN: rosetta-code.entropy-narcissist
: entropy ( seq -- entropy )
[ length ] [ histogram >alist [ second ] map ] bi
[ swap / ] with map
[ dup log 2 log / * ] map-sum neg ;
"entropy-narcissist.factor" utf8 [
contents entropy .
] with-file-reader |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Arturo | Arturo | enum: [apple banana cherry]
print "as a block of words:"
inspect.muted enum
enum: ['apple 'banana 'cherry]
print "\nas a block of literals:"
print enum
enum: #[
apple: 1
banana: 2
cherry: 3
]
print "\nas a dictionary:"
print enum |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #ATS | ATS | datatype my_enum =
| value_a
| value_b
| value_c |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #AutoHotkey | AutoHotkey | fruit_%apple% = 0
fruit_%banana% = 1
fruit_%cherry% = 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.
| #6502_Assembly | 6502 Assembly | List:
byte $01,$02,$03,$04,$05 |
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.
| #68000_Assembly | 68000 Assembly | bit7 equ %10000000
bit6 equ %01000000
MOVE.B (A0),D0
AND.B #bit7,D0
;D0.B contains either $00 or $80 |
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.
| #8th | 8th |
123 const var, one-two-three
|
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.
| #ACL2 | ACL2 | (defconst *pi-approx* 22/7) |
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
| #AppleScript | AppleScript | on run
{ethMult(17, 34), ethMult("Rhind", 9)}
--> {578, "RhindRhindRhindRhindRhindRhindRhindRhind"}
end run
-- Int -> Int -> Int
-- or
-- Int -> String -> String
on ethMult(m, n)
script fns
property identity : missing value
property plus : missing value
on half(n) -- 1. half an integer (div 2)
n div 2
end half
on double(n) -- 2. double (add to self)
plus(n, n)
end double
on isEven(n) -- 3. is n even ? (mod 2 > 0)
(n mod 2) > 0
end isEven
on chooseFns(c)
if c is string then
set identity of fns to ""
set plus of fns to plusString of fns
else
set identity of fns to 0
set plus of fns to plusInteger of fns
end if
end chooseFns
on plusInteger(a, b)
a + b
end plusInteger
on plusString(a, b)
a & b
end plusString
end script
chooseFns(class of m) of fns
-- MAIN PROCESS OF CALCULATION
set o to identity of fns
if n < 1 then return o
repeat while (n > 1)
if isEven(n) of fns then -- 3. is n even ? (mod 2 > 0)
set o to plus(o, m) of fns
end if
set n to half(n) of fns -- 1. half an integer (div 2)
set m to double(m) of fns -- 2. double (add to self)
end repeat
return plus(o, m) of fns
end ethMult |
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.
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
call :equilibrium-index "-7 1 5 2 -4 3 0"
call :equilibrium-index "2 4 6"
call :equilibrium-index "2 9 2"
call :equilibrium-index "1 -1 1 -1 1 -1 1"
pause>nul
exit /b
%== The Function ==%
:equilibrium-index <sequence with quotes>
::Set the pseudo-array sequence...
set "seq=%~1"
set seq.length=0
for %%S in (!seq!) do (
set seq[!seq.length!]=%%S
set /a seq.length+=1
)
::Initialization of other variables...
set "equilms="
set /a last=seq.length - 1
::The main checking...
for /l %%e in (0,1,!last!) do (
set left=0
set right=0
for /l %%i in (0,1,!last!) do (
if %%i lss %%e (set /a left+=!seq[%%i]!)
if %%i gtr %%e (set /a right+=!seq[%%i]!)
)
if !left!==!right! (
if defined equilms (
set "equilms=!equilms! %%e"
) else (
set "equilms=%%e"
)
)
)
echo [!equilms!]
goto :EOF
%==/The 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
| #D | D | import std.stdio, std.process;
void main() {
auto home = 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
| #Delphi.2FPascal | Delphi/Pascal | program EnvironmentVariable;
{$APPTYPE CONSOLE}
uses SysUtils;
begin
WriteLn('Temp = ' + GetEnvironmentVariable('TEMP'));
end. |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #E | E | <unsafe:java.lang.System>.getenv("HOME") |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[EstheticNumbersRangeHelper, EstheticNumbersRange]
EstheticNumbersRangeHelper[power_, mima : {mi_, max_}, b_ : 10] := Module[{steps, cands},
steps = Tuples[{-1, 1}, power - 1];
steps = Accumulate[Prepend[#, 0]] & /@ steps;
cands = Table[Select[# + ConstantArray[s, power] & /@ steps, AllTrue[Between[{0, b - 1}]]], {s, 1, b - 1}];
cands //= Catenate;
cands //= Map[FromDigits[#, b] &];
cands = Select[cands, Between[mima]];
BaseForm[#, b] & /@ cands
]
EstheticNumbersRange[{min_, max_}, b_ : 10] := Module[{mi, ma},
{mi, ma} = Log[b, {min, max}];
mi //= Ceiling;
ma //= Ceiling;
ma = Max[ma, 1];
mi = Max[mi, 1];
Catenate[EstheticNumbersRangeHelper[#, {min, max}, b] & /@ Range[mi, ma]]
]
Table[{b, EstheticNumbersRange[{1, If[b == 2, 100000, If[b == 3, 100000, b^4]]}, b][[4 b ;; 6 b]]}, {b, 2, 16}] // Grid
EstheticNumbersRange[{1000, 9999}]
EstheticNumbersRange[{10^8, 1.3 10^8}] |
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.
| #Clojure | Clojure |
(ns test-p.core
(:require [clojure.math.numeric-tower :as math])
(:require [clojure.data.int-map :as i]))
(defn solve-power-sum [max-value max-sols]
" Finds solutions by using method approach of EchoLisp
Large difference is we store a dictionary of all combinations
of y^5 - x^5 with the x, y value so we can simply lookup rather than have to search "
(let [pow5 (mapv #(math/expt % 5) (range 0 (* 4 max-value))) ; Pow5 = Generate Lookup table for x^5
y5-x3 (into (i/int-map) (for [x (range 1 max-value) ; For x0^5 + x1^5 + x2^5 + x3^5 = y^5
y (range (+ 1 x) (* 4 max-value))] ; compute y5-x3 = set of all possible differnences
[(- (get pow5 y) (get pow5 x)) [x y]])) ; note: (get pow5 y) is closure for: pow5[y]
solutions-found (atom 0)]
(for [x0 (range 1 max-value) ; Search over x0, x1, x2 for sums equal y5-x3
x1 (range 1 x0)
x2 (range 1 x1)
:when (< @solutions-found max-sols)
:let [sum (apply + (map pow5 [x0 x1 x2]))] ; compute sum of items to the 5th power
:when (contains? y5-x3 sum)] ; check if sum is in set of differences
(do
(swap! solutions-found inc) ; increment counter for solutions found
(concat [x0 x1 x2] (get y5-x3 sum)))))) ; create result (since in set of differences)
; Output results with numbers in ascending order placing results into a set (i.e. #{}) so duplicates are discarded
; CPU i7 920 Quad Core @2.67 GHz clock Windows 10
(println (into #{} (map sort (solve-power-sum 250 1)))) ; MAX = 250, find only 1 value: Duration was 0.26 seconds
(println (into #{} (map sort (solve-power-sum 1000 1000))));MAX = 1000, high max-value so all solutions found: Time = 4.8 seconds
|
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | ВП П0 1 ИП0 * L0 03 С/П
|
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.
| #Asymptote | Asymptote | for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0) {
write(string(i), " is even");
} else {
write(string(i), " is odd");
}
} |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #Maple | Maple | with(Student[NumericalAnalysis]);
k := 0.07:
TR := 20:
Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 50); # step size = 2
Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 20); # step size = 5
Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 10); # step size = 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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
euler[step_, val_] := NDSolve[
{T'[t] == -0.07 (T[t] - 20), T[0] == 100},
T, {t, 0, 100},
Method -> "ExplicitEuler",
StartingStepSize -> step
][[1, 1, 2]][val]
|
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
| #Elixir | Elixir | defmodule RC do
def choose(n,k) when is_integer(n) and is_integer(k) and n>=0 and k>=0 and n>=k do
if k==0, do: 1, else: choose(n,k,1,1)
end
def choose(n,k,k,acc), do: div(acc * (n-k+1), k)
def choose(n,k,i,acc), do: choose(n, k, i+1, div(acc * (n-i+1), i))
end
IO.inspect RC.choose(5,3)
IO.inspect RC.choose(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
| #Erlang | Erlang |
choose(N, 0) -> 1;
choose(N, K) when is_integer(N), is_integer(K), (N >= 0), (K >= 0), (N >= K) ->
choose(N, K, 1, 1).
choose(N, K, K, Acc) ->
(Acc * (N-K+1)) div K;
choose(N, K, I, Acc) ->
choose(N, K, I+1, (Acc * (N-I+1)) div I).
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #WebAssembly | WebAssembly | (func $fibonacci_nth (param $n i32) (result i32)
;;Declare some local registers
(local $i i32)
(local $a i32)
(local $b i32)
;;Handle first 2 numbers as special cases
(if (i32.eq (get_local $n) (i32.const 0))
(return (i32.const 0))
)
(if (i32.eq (get_local $n) (i32.const 1))
(return (i32.const 1))
)
;;Initialize first two values
(set_local $i (i32.const 1))
(set_local $a (i32.const 0))
(set_local $b (i32.const 1))
(block
(loop
;;Add two previous numbers and store the result
local.get $a
local.get $b
i32.add
(set_local $a (get_local $b))
set_local $b
;;Increment counter i by one
(set_local $i
(i32.add
(get_local $i)
(i32.const 1)
)
)
;;Check if loop is done
(br_if 1 (i32.ge_u (get_local $i) (get_local $n)))
(br 0)
)
)
;;The result is stored in b, so push that to the stack
get_local $b
)
|
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #FreeBASIC | FreeBASIC | ' version 01-06-2016
' compile with: fbc -s console
' modified code from ENTROPY entry
Dim As Integer i, count, totalchar(255)
Dim As UByte buffer
Dim As Double prop, entropy
' command (0) returns the name of this program (including the path)
Dim As String slash, filename = Command(0)
Dim As Integer ff = FreeFile ' find first free filenumber
Open filename For Binary As #ff
If Err > 0 Then ' should not happen
Print "Error opening the file"
Beep : Sleep 5000, 1
End
End If
' will read 1 UByte from the file until it reaches the end of the file
For i = 1 To Lof(ff)
Get #ff, ,buffer
totalchar(buffer) += 1
count = count + 1
Next
For i = 0 To 255
If totalchar(i) = 0 Then Continue For
prop = totalchar(i) / count
entropy = entropy - (prop * Log (prop) / Log(2))
Next
' next lines are only compiled when compiling for Windows OS (32/64)
#Ifdef __FB_WIN32__
slash = chr(92)
print "Windows version"
#endif
#Ifdef __FB_LINUX__
slash = chr(47)
print "LINUX version"
#EndIf
i = InStrRev(filename, slash)
If i <> 0 Then filename = Right(filename, Len(filename)-i)
Print "My name is "; filename
Print : Print "The Entropy of myself is"; entropy
Print
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Go | Go | package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #AWK | AWK | fruit["apple"]=1; fruit["banana"]=2; fruit["cherry"]=3
fruit[1]="apple"; fruit[2]="banana"; fruit[3]="cherry"
i=0; apple=++i; banana=++i; cherry=++i; |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #BASIC | BASIC | REM Impossible. Can only be faked with arrays of strings.
OPTION BASE 1
DIM SHARED fruitsName$(1 TO 3)
DIM SHARED fruitsVal%( 1 TO 3)
fruitsName$[1] = "apple"
fruitsName$[2] = "banana"
fruitsName$[3] = "cherry"
fruitsVal%[1] = 1
fruitsVal%[2] = 2
fruitsVal%[3] = 3
REM OR GLOBAL CONSTANTS
DIM SHARED apple%, banana%, cherry%
apple% = 1
banana% = 2
cherry% = 3 |
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.
| #Ada | Ada | Foo : constant := 42;
Foo : constant Blahtype := 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.
| #ALGOL_68 | ALGOL 68 | INT max allowed = 20;
REAL pi = 3.1415 9265; # pi is constant that the compiler will enforce #
REF REAL var = LOC REAL; # var is a constant pointer to a local REAL address #
var := pi # constant pointer var has the REAL value referenced assigned pi # |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #AutoHotkey | AutoHotkey | MyData := new FinalBox("Immutable data")
MsgBox % "MyData.Data = " MyData.Data
MyData.Data := "This will fail to set"
MsgBox % "MyData.Data = " MyData.Data
Class FinalBox {
__New(FinalValue) {
ObjInsert(this, "proxy",{Data:FinalValue})
}
; override the built-in methods:
__Get(k) {
return, this["proxy",k]
}
__Set(p*) {
return
}
Insert(p*) {
return
}
Remove(p*) {
return
}
} |
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
| #Arturo | Arturo | halve: function [x]-> shr x 1
double: function [x]-> shl x 1
; even? already exists
ethiopian: function [x y][
prod: 0
while [x > 0][
unless even? x [prod: prod + y]
x: halve x
y: double y
]
return prod
]
print ethiopian 17 34
print ethiopian 2 3 |
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.
| #BBC_BASIC | BBC BASIC | DIM list(6)
list() = -7, 1, 5, 2, -4, 3, 0
PRINT "Equilibrium indices are " FNequilibrium(list())
END
DEF FNequilibrium(l())
LOCAL i%, r, s, e$
s = SUM(l())
FOR i% = 0 TO DIM(l(),1)
IF r = s - r - l(i%) THEN e$ += STR$(i%) + ","
r += l(i%)
NEXT
= LEFT$(e$) |
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
int list[] = {-7, 1, 5, 2, -4, 3, 0};
int eq_idx(int *a, int len, int **ret)
{
int i, sum, s, cnt;
/* alloc long enough: if we can afford the original list,
* we should be able to afford to this. Beats a potential
* million realloc() calls. Even if memory is a real concern,
* there's no garantee the result is shorter than the input anyway */
cnt = s = sum = 0;
*ret = malloc(sizeof(int) * len);
for (i = 0; i < len; i++)
sum += a[i];
for (i = 0; i < len; i++) {
if (s * 2 + a[i] == sum) {
(*ret)[cnt] = i;
cnt++;
}
s += a[i];
}
/* uncouraged way to use realloc since it can leak memory, for example */
*ret = realloc(*ret, cnt * sizeof(int));
return cnt;
}
int main()
{
int i, cnt, *idx;
cnt = eq_idx(list, sizeof(list) / sizeof(int), &idx);
printf("Found:");
for (i = 0; i < cnt; i++)
printf(" %d", idx[i]);
printf("\n");
return 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
| #Eiffel | Eiffel | class
APPLICATION
inherit
EXECUTION_ENVIRONMENT
create
make
feature {NONE} -- Initialization
make
-- Retrieve and print value for environment variable `USERNAME'.
do
print (get ("USERNAME"))
end
end |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Elixir | Elixir | System.get_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
| #Emacs_Lisp | Emacs Lisp | (getenv "HOME") |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Nim | Nim | import strformat
func isEsthetic(n, b: int64): bool =
if n == 0: return false
var i = n mod b
var n = n div b
while n > 0:
let j = n mod b
if abs(i - j) != 1:
return false
n = n div b
i = j
result = true
proc listEsths(n1, n2, m1, m2: int64; perLine: int; all: bool) =
var esths: seq[int64]
func dfs(n, m, i: int64) =
if i in n..m: esths.add i
if i == 0 or i > m: return
let d = i mod 10
let i1 = i * 10 + d - 1
let i2 = i1 + 2
case d
of 0:
dfs(n, m, i2)
of 9:
dfs(n, m, i1)
else:
dfs(n, m, i1)
dfs(n, m, i2)
for i in 0..9:
dfs(n2, m2, i)
echo &"Base 10: {esths.len} esthetic numbers between {n1} and {m1}:"
if all:
for i, esth in esths:
stdout.write esth
stdout.write if (i + 1) mod perLine == 0: '\n' else: ' '
echo()
else:
for i in 0..<perLine:
stdout.write esths[i], ' '
echo "\n............"
for i in esths.len - perLine .. esths.high:
stdout.write esths[i], ' '
echo()
echo()
proc toBase(n, b: int64): string =
const Digits = ['0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
if n == 0: return "0"
var n = n
while n > 0:
result.add Digits[n mod b]
n = n div b
for i in 0..<(result.len div 2):
swap result[i], result[result.high - i]
for b in 2..16:
echo &"Base {b}: {4 * b}th to {6 * b}th esthetic numbers:"
var n = 1i64
var c = 0i64
while c < 6 * b:
if n.isEsthetic(b):
inc c
if c >= 4 * b: stdout.write n.toBase(b), ' '
inc n
echo '\n'
# The following all use the obvious range limitations for the numbers in question.
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(100_000_000, 101_010_101, 130_000_000, 123_456_789, 9, true)
listEsths(100_000_000_000, 101_010_101_010, 130_000_000_000, 123_456_789_898, 7, false)
listEsths(100_000_000_000_000, 101_010_101_010_101, 130_000_000_000, 123_456_789_898_989, 5, false)
listEsths(100_000_000_000_000_000, 101_010_101_010_101_010, 130_000_000_000_000_000, 123_456_789_898_989_898, 4, false) |
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.
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. EULER.
DATA DIVISION.
FILE SECTION.
WORKING-STORAGE SECTION.
1 TABLE-LENGTH CONSTANT 250.
1 SEARCHING-FLAG PIC 9.
88 FINISHED-SEARCHING VALUE IS 1
WHEN SET TO FALSE IS 0.
1 CALC.
3 A PIC 999 USAGE COMPUTATIONAL-5.
3 B PIC 999 USAGE COMPUTATIONAL-5.
3 C PIC 999 USAGE COMPUTATIONAL-5.
3 D PIC 999 USAGE COMPUTATIONAL-5.
3 ABCD PIC 9(18) USAGE COMPUTATIONAL-5.
3 FIFTH-ROOT-OFFS PIC 999 USAGE COMPUTATIONAL-5.
3 POWER-COUNTER PIC 999 USAGE COMPUTATIONAL-5.
88 POWER-MAX VALUE TABLE-LENGTH.
1 PRETTY.
3 A PIC ZZ9.
3 FILLER VALUE "^5 + ".
3 B PIC ZZ9.
3 FILLER VALUE "^5 + ".
3 C PIC ZZ9.
3 FILLER VALUE "^5 + ".
3 D PIC ZZ9.
3 FILLER VALUE "^5 = ".
3 FIFTH-ROOT-OFFS PIC ZZ9.
3 FILLER VALUE "^5.".
1 FIFTH-POWER-TABLE OCCURS TABLE-LENGTH TIMES
ASCENDING KEY IS FIFTH-POWER
INDEXED BY POWER-INDEX.
3 FIFTH-POWER PIC 9(18) USAGE COMPUTATIONAL-5.
PROCEDURE DIVISION.
MAIN-PARAGRAPH.
SET FINISHED-SEARCHING TO FALSE.
PERFORM POWERS-OF-FIVE-TABLE-INIT.
PERFORM VARYING
A IN CALC
FROM 1 BY 1 UNTIL A IN CALC = TABLE-LENGTH
AFTER B IN CALC
FROM 1 BY 1 UNTIL B IN CALC = A IN CALC
AFTER C IN CALC
FROM 1 BY 1 UNTIL C IN CALC = B IN CALC
AFTER D IN CALC
FROM 1 BY 1 UNTIL D IN CALC = C IN CALC
IF FINISHED-SEARCHING
STOP RUN
END-IF
PERFORM POWER-COMPUTATIONS
END-PERFORM.
POWER-COMPUTATIONS.
MOVE ZERO TO ABCD IN CALC.
ADD FIFTH-POWER(A IN CALC)
FIFTH-POWER(B IN CALC)
FIFTH-POWER(C IN CALC)
FIFTH-POWER(D IN CALC)
TO ABCD IN CALC.
SET POWER-INDEX TO 1.
SEARCH ALL FIFTH-POWER-TABLE
WHEN FIFTH-POWER(POWER-INDEX) = ABCD IN CALC
MOVE POWER-INDEX TO FIFTH-ROOT-OFFS IN CALC
MOVE CORRESPONDING CALC TO PRETTY
DISPLAY PRETTY END-DISPLAY
SET FINISHED-SEARCHING TO TRUE
END-SEARCH
EXIT PARAGRAPH.
POWERS-OF-FIVE-TABLE-INIT.
PERFORM VARYING POWER-COUNTER FROM 1 BY 1 UNTIL POWER-MAX
COMPUTE FIFTH-POWER(POWER-COUNTER) =
POWER-COUNTER *
POWER-COUNTER *
POWER-COUNTER *
POWER-COUNTER *
POWER-COUNTER
END-COMPUTE
END-PERFORM.
EXIT PARAGRAPH.
END PROGRAM EULER.
|
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
| #ML.2FI | ML/I | MCSKIP "WITH" NL
"" Factorial - iterative
MCSKIP MT,<>
MCINS %.
MCDEF FACTORIAL WITHS ()
AS <MCSET T1=%A1.
MCSET T2=1
MCSET T3=1
%L1.MCGO L2 IF T3 GR T1
MCSET T2=T2*T3
MCSET T3=T3+1
MCGO L1
%L2.%T2.>
fact(1) is FACTORIAL(1)
fact(2) is FACTORIAL(2)
fact(3) is FACTORIAL(3)
fact(4) is FACTORIAL(4) |
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.
| #AutoHotkey | AutoHotkey | if ( int & 1 ){
; do odd stuff
}else{
; do even stuff
} |
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.
| #Maxima | Maxima | euler_method(f, y0, a, b, h):= block(
[t: a, y: y0, tg: [a], yg: [y0]],
unless t>=b do (
t: t + h,
y: y + f(t, y)*h,
tg: endcons(t, tg),
yg: endcons(y, yg)
),
[tg, yg]
);
/* initial temperature */
T0: 100;
/* environment of temperature */
Tr: 20;
/* the cooling constant */
k: 0.07;
/* end of integration */
tmax: 100;
/* analytical solution */
Tref(t):= Tr + (T0 - Tr)*exp(-k*t);
/* cooling rate */
dT(t, T):= -k*(T-Tr);
/* get numerical solution */
h: 10;
[tg, yg]: euler_method('dT, T0, 0, tmax, h);
/* plot analytical and numerical solution */
plot2d([Tref, [discrete, tg, yg]], ['t, 0, tmax],
[legend, "analytical", concat("h = ", h)],
[xlabel, "t / seconds"],
[ylabel, "Temperature / C"]);
|
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.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П2 С/П П3 С/П П4 ПП 19 ИП3 * ИП4
+ П4 С/П ИП2 ИП3 + П2 БП 05 ...
... ... ... ... ... ... ... ... ... В/О |
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
| #ERRE | ERRE | PROGRAM BINOMIAL
!$DOUBLE
PROCEDURE BINOMIAL(N,K->BIN)
LOCAL R,D
R=1 D=N-K
IF D>K THEN K=D D=N-K END IF
WHILE N>K DO
R*=N
N-=1
WHILE D>1 AND (R-D*INT(R/D))=0 DO
R/=D
D-=1
END WHILE
END WHILE
BIN=R
END PROCEDURE
BEGIN
BINOMIAL(5,3->BIN)
PRINT("Binomial (5,3) = ";BIN)
BINOMIAL(100,2->BIN)
PRINT("Binomial (100,2) = ";BIN)
BINOMIAL(33,17->BIN)
PRINT("Binomial (33,17) = ";BIN)
END PROGRAM
|
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
| #F.23 | F# |
let choose n k = List.fold (fun s i -> s * (n-i+1)/i ) 1 [1..k]
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Whitespace | Whitespace | |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Haskell | Haskell | import qualified Data.ByteString as BS
import Data.List
import System.Environment
(>>>) = flip (.)
main = getArgs >>= head >>> BS.readFile >>= BS.unpack >>> entropy >>> print
entropy = sort >>> group >>> map genericLength >>> normalize >>> map lg >>> sum
where lg c = -c * logBase 2 c
normalize c = let sc = sum c in map (/ sc) c |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #J | J | entropy=: +/@:-@(* 2&^.)@(#/.~ % #)
1!:2&2 entropy 1!:1 (4!:4 <'entropy') { 4!:3'' |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Java | Java |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EntropyNarcissist {
private static final String FILE_NAME = "src/EntropyNarcissist.java";
public static void main(String[] args) {
System.out.printf("Entropy of file \"%s\" = %.12f.%n", FILE_NAME, getEntropy(FILE_NAME));
}
private static double getEntropy(String fileName) {
Map<Character,Integer> characterCount = new HashMap<>();
int length = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));) {
int c = 0;
while ( (c = reader.read()) != -1 ) {
characterCount.merge((char) c, 1, (v1, v2) -> v1 + v2);
length++;
}
}
catch ( IOException e ) {
throw new RuntimeException(e);
}
double entropy = 0;
for ( char key : characterCount.keySet() ) {
double fraction = (double) characterCount.get(key) / length;
entropy -= fraction * Math.log(fraction);
}
return entropy / Math.log(2);
}
}
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Bracmat | Bracmat | fruits=apple+banana+cherry; |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #C | C | enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 }; |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #C.23 | C# | enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 }
enum fruits : int { apple = 0, banana = 1, cherry = 2 }
[FlagsAttribute]
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 } |
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.
| #BASIC | BASIC | CONST x = 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.
| #BBC_BASIC | BBC BASIC | DEF FNconst = 2.71828182845905
PRINT FNconst
FNconst = 1.234 : REM Reports 'Syntax error' |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Bracmat | Bracmat | myVar=immutable (m=mutable) immutable;
changed:?(myVar.m);
lst$myVar
|
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.
| #C | C | #define PI 3.14159265358979323
#define MINSIZE 10
#define MAXSIZE 100 |
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
| #11l | 11l | F entropy(source)
DefaultDict[Char, Int] hist
L(c) source
hist[c]++
V r = 0.0
L(v) hist.values()
V c = Float(v) / source.len
r -= c * log2(c)
R r
print(entropy(‘1223334444’)) |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #AutoHotkey | AutoHotkey | MsgBox % Ethiopian(17, 34) "`n" Ethiopian2(17, 34)
; func definitions:
half( x ) {
return x >> 1
}
double( x ) {
return x << 1
}
isEven( x ) {
return x & 1 == 0
}
Ethiopian( a, b ) {
r := 0
While (a >= 1) {
if !isEven(a)
r += b
a := half(a)
b := double(b)
}
return r
}
; or a recursive function:
Ethiopian2( a, b, r = 0 ) { ;omit r param on initial call
return a==1 ? r+b : Ethiopian2( half(a), double(b), !isEven(a) ? r+b : r )
} |
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.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static IEnumerable<int> EquilibriumIndices(IEnumerable<int> sequence)
{
var left = 0;
var right = sequence.Sum();
var index = 0;
foreach (var element in sequence)
{
right -= element;
if (left == right)
{
yield return index;
}
left += element;
index++;
}
}
static void Main()
{
foreach (var index in EquilibriumIndices(new[] { -7, 1, 5, 2, -4, 3, 0 }))
{
Console.WriteLine(index);
}
}
} |
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
| #Erlang | Erlang |
os:getenv( "HOME" ).
|
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Euphoria | Euphoria | puts(1,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
| #F.23 | F# | open System
[<EntryPoint>]
let main args =
printfn "%A" (Environment.GetEnvironmentVariable("PATH"))
0 |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Pascal | Pascal | program Esthetic;
{$IFDEF FPC}
{$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$codealign proc=16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils,//IntToStr
strutils;//Numb2USA aka commatize
const
ConvBase :array[0..15] of char= '0123456789ABCDEF';
maxBase = 16;
type
tErg = string[63];
tCnt = array[0..maxBase-1] of UInt64;
tDgtcnt = array[0..64] of tCnt;
//global
var
Dgtcnt :tDgtcnt;
procedure CalcDgtCnt(base:NativeInt;var Dgtcnt :tDgtcnt);
var
pCnt0,
pCnt1 : ^tCnt;
i,j,SumCarry: NativeUInt;
begin
fillchar(Dgtcnt,SizeOf(Dgtcnt),#0);
pCnt0 := @Dgtcnt[0];
//building count for every first digit of digitcount:
//example :count numbers starting "1" of lenght 13
For i := 0 to Base-1 do
pCnt0^[i] := 1;
For j := 1 to High(Dgtcnt) do
Begin
pCnt1 := @Dgtcnt[j];
//0 -> followed only by solutions of 1
pCnt1^[0] := pCnt0^[1];
//base-1 -> followed only by solutions of Base-2
pCnt1^[base-1] := pCnt0^[base-2];
//followed by solutions for i-1 and i+1
For i := 1 to base-2 do
pCnt1^[i]:= pCnt0^[i-1]+pCnt0^[i+1];
//next row aka digitcnt
pCnt0:= pCnt1;
end;
//converting to sum up each digit
//example :count numbers starting "1" of lenght 13
//-> count of all est. numbers from 1 to "1" with max lenght 13
//delete leading "0"
For j := 0 to High(Dgtcnt) do //High(Dgtcnt)
Dgtcnt[j,0] := 0;
SumCarry := Uint64(0);
For j := 0 to High(Dgtcnt) do
Begin
pCnt0 := @Dgtcnt[j];
For i := 0 to base-1 do
begin
SumCarry +=pCnt0^[i];
pCnt0^[i] :=SumCarry;
end;
end;
end;
function ConvToBaseStr(n,base:NativeUint):tErg;
var
idx,dgt,rst : Uint64;
Begin
IF n = 0 then
Begin
result := ConvBase[0];
EXIT;
end;
idx := High(result);
repeat
rst := n div base;
dgt := n-rst*base;
result[idx] := ConvBase[dgt];
dec(idx);
n := rst;
until n=0;
rst := High(result)-idx;
move(result[idx+1],result[1],rst);
setlength(result,rst);
end;
function isEsthetic(n,base:Uint64):boolean;
var
lastdgt,
dgt,
rst : Uint64;
Begin
result := true;
IF n >= Base then
Begin
rst := n div base;
Lastdgt := n-rst*base;
n := rst;
repeat
rst := n div base;
dgt := n-rst*base;
IF sqr(lastDgt-dgt)<> 1 then
Begin
result := false;
EXIT;
end;
lastDgt := dgt;
n := rst;
until n = 0;
end;
end;
procedure Task1;
var
i,base,cnt : NativeInt;
Begin
cnt := 0;
For base := 2 to 16 do
Begin
CalcDgtCnt(base,Dgtcnt);
writeln(4*base,'th through ',6*base,'th esthetic numbers in base ',base);
cnt := 0;
i := 0;
repeat
inc(i);
if isEsthetic(i,base) then
inc(cnt);
until cnt >= 4*base;
repeat
if isEsthetic(i,base) then
Begin
write(ConvToBaseStr(i,base),' ');
inc(cnt);
end;
inc(i);
until cnt > 6*base;
writeln;
end;
writeln;
end;
procedure Task2;
var
i : NativeInt;
begin
write(' There are ',Dgtcnt[4][0]-Dgtcnt[3][0],' esthetic numbers');
writeln(' between 1000 and 9999 ');
For i := 1000 to 9999 do
Begin
if isEsthetic(i,10) then
write(i:5);
end;
writeln;writeln;
end;
procedure Task3(Pot10: NativeInt);
//calculating esthetic numbers starting with "1" and Pot10+1 digits
var
i : NativeInt;
begin
write(' There are ',Numb2USA(IntToStr(Dgtcnt[Pot10][1]-Dgtcnt[Pot10][0])):26,' esthetic numbers');
writeln(' between 1e',Pot10,' and 1.3e',Pot10);
if Pot10 = 8 then
Begin
For i := 100*1000*1000 to 110*1000*1000-1 do
Begin
if isEsthetic(i,10) then
write(i:10);
end;
writeln;
//Jump over "11"
For i := 120*1000*1000 to 130*1000*1000-1 do
Begin
if isEsthetic(i,10) then
write(i:10);
end;
writeln;writeln;
end;
end;
var
i:NativeInt;
BEGIN
Task1;
//now only base 10 is used
CalcDgtCnt(10,Dgtcnt);
Task2;
For i := 2 to 20 do
Task3(3*i+2);
writeln;
write(' There are ',Numb2USA(IntToStr(Dgtcnt[64][0])),' esthetic numbers');
writeln(' with max 65 digits ');
writeln;
writeln(' The count of numbers with 64 digits like https://oeis.org/A090994');
writeln(Numb2USA(IntToStr(Dgtcnt[64][0]-Dgtcnt[63][0])):28);
end.
|
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.
| #Common_Lisp | Common Lisp |
(ql:quickload :alexandria)
(let ((fifth-powers (mapcar #'(lambda (x) (expt x 5))
(alexandria:iota 250))))
(loop named outer for x0 from 1 to (length fifth-powers) do
(loop for x1 from 1 below x0 do
(loop for x2 from 1 below x1 do
(loop for x3 from 1 below x2 do
(let ((x-sum (+ (nth x0 fifth-powers)
(nth x1 fifth-powers)
(nth x2 fifth-powers)
(nth x3 fifth-powers))))
(if (member x-sum fifth-powers)
(return-from outer (list x0 x1 x2 x3 (round (expt x-sum 0.2)))))))))))
|
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Modula-2 | Modula-2 | MODULE Factorial;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
PROCEDURE Factorial(n : CARDINAL) : CARDINAL;
VAR result : CARDINAL;
BEGIN
result := 1;
WHILE n#0 DO
result := result * n;
DEC(n)
END;
RETURN result
END Factorial;
VAR
buf : ARRAY[0..63] OF CHAR;
n : CARDINAL;
BEGIN
FOR n:=0 TO 10 DO
FormatString("%2c! = %7c\n", buf, n, Factorial(n));
WriteString(buf)
END;
ReadChar
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.
| #AWK | AWK | function isodd(x) {
return (x%2)!=0;
}
function iseven(x) {
return (x%2)==0;
} |
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.
| #Nim | Nim | import strutils
proc euler(f: proc (x,y: float): float; y0, a, b, h: float) =
var (t,y) = (a,y0)
while t < b:
echo formatFloat(t, ffDecimal, 3), " ", formatFloat(y, ffDecimal, 3)
t += h
y += h * f(t,y)
proc newtoncooling(time, temp: float): float =
-0.07 * (temp - 20)
euler(newtoncooling, 100.0, 0.0, 100.0, 10.0) |
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.
| #Objeck | Objeck |
class EulerMethod {
T0 : static : Float;
TR : static : Float;
k : static : Float;
delta_t : static : Float[];
n : static : Float;
function : Main(args : String[]) ~ Nil {
T0 := 100;
TR := 20;
k := 0.07;
delta_t := [2.0, 5.0, 10.0];
n := 100;
f := NewtonCooling(Float) ~ Float;
for(i := 0; i < delta_t->Size(); i+=1;) {
IO.Console->Print("delta_t = ")->PrintLine(delta_t[i]);
Euler(f, T0, n->As(Int), delta_t[i]);
};
}
function : native : NewtonCooling(t : Float) ~ Float {
return -1 * k * (t-TR);
}
function : native : Euler(f : (Float) ~ Float, y : Float, n : Int, h : Float) ~ Nil {
for(x := 0; x<=n; x+=h;) {
IO.Console->Print("\t")->Print(x)->Print("\t")->PrintLine(y);
y += h * f(y);
};
}
}
|
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
| #Factor | Factor |
: fact ( n -- n-factorial )
dup 0 = [ drop 1 ] [ dup 1 - fact * ] if ;
: choose ( n k -- n-choose-k )
2dup - [ fact ] tri@ * / ;
! outputs 10
5 3 choose .
! alternative using folds
USE: math.ranges
! (product [n..k+1] / product [n-k..1])
: choose-fold ( n k -- n-choose-k )
2dup 1 + [a,b] product -rot - 1 [a,b] product / ;
|
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
| #Fermat | Fermat | Bin(5,3) |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Wrapl | Wrapl | DEF fib() (
VAR seq <- [0, 1]; EVERY SUSP seq:values;
REP SUSP seq:put(seq:pop + seq[1])[-1];
); |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Julia | Julia | using DataStructures
entropy(s) = -sum(x -> x / length(s) * log2(x / length(s)), values(counter(s)))
println("self-entropy: ", entropy(read(Base.source_path(), String))) |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Kotlin | Kotlin | // version 1.1.0 (entropy_narc.kt)
fun log2(d: Double) = Math.log(d) / Math.log(2.0)
fun shannon(s: String): Double {
val counters = mutableMapOf<Char, Int>()
for (c in s) {
if (counters.containsKey(c)) counters[c] = counters[c]!! + 1
else counters.put(c, 1)
}
val nn = s.length.toDouble()
var sum = 0.0
for (key in counters.keys) {
val term = counters[key]!! / nn
sum += term * log2(term)
}
return -sum
}
fun main(args: Array<String>) {
val prog = java.io.File("entropy_narc.kt").readText()
println("This program's entropy is ${"%18.16f".format(shannon(prog))}")
} |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Lua | Lua | function getFile (filename)
local inFile = io.open(filename, "r")
local fileContent = inFile:read("*all")
inFile:close()
return fileContent
end
function log2 (x) return math.log(x) / math.log(2) end
function entropy (X)
local N, count, sum, i = X:len(), {}, 0
for char = 1, N do
i = X:sub(char, char)
if count[i] then
count[i] = count[i] + 1
else
count[i] = 1
end
end
for n_i, count_i in pairs(count) do
sum = sum + count_i / N * log2(count_i / N)
end
return -sum
end
print(entropy(getFile(arg[0]))) |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #C.2B.2B | C++ | enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 }; |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Clojure | Clojure | ; a set of keywords
(def fruits #{:apple :banana :cherry})
; a predicate to test "fruit" membership
(defn fruit? [x] (contains? fruits x))
; if you need a value associated with each fruit
(def fruit-value (zipmap fruits (iterate inc 1)))
(println (fruit? :apple))
(println (fruit-value :banana)) |
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.
| #C.23 | C# | readonly DateTime now = DateTime.Now; |
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.
| #C.2B.2B | C++ | #include <iostream>
class MyOtherClass
{
public:
const int m_x;
MyOtherClass(const int initX = 0) : m_x(initX) { }
};
int main()
{
MyOtherClass mocA, mocB(7);
std::cout << mocA.m_x << std::endl; // displays 0, the default value given for MyOtherClass's constructor.
std::cout << mocB.m_x << std::endl; // displays 7, the value we provided for the constructor for mocB.
// Uncomment this, and the compile will fail; m_x is a const member.
// mocB.m_x = 99;
return 0;
} |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #Ada | Ada | with Ada.Text_IO, Ada.Float_Text_IO, Ada.Numerics.Elementary_Functions;
procedure Count_Entropy is
package TIO renames Ada.Text_IO;
Count: array(Character) of Natural := (others => 0);
Sum: Natural := 0;
Line: String := "1223334444";
begin
for I in Line'Range loop -- count the characters
Count(Line(I)) := Count(Line(I))+1;
Sum := Sum + 1;
end loop;
declare -- compute the entropy and print it
function P(C: Character) return Float is (Float(Count(C)) / Float(Sum));
use Ada.Numerics.Elementary_Functions, Ada.Float_Text_IO;
Result: Float := 0.0;
begin
for Ch in Character loop
Result := Result -
(if P(Ch)=0.0 then 0.0 else P(Ch) * Log(P(Ch), Base => 2.0));
end loop;
Put(Result, Fore => 1, Aft => 5, Exp => 0);
end;
end Count_Entropy; |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #AutoIt | AutoIt |
Func Halve($x)
Return Int($x/2)
EndFunc
Func Double($x)
Return ($x*2)
EndFunc
Func IsEven($x)
Return (Mod($x,2) == 0)
EndFunc
; this version also supports negative parameters
Func Ethiopian($nPlier, $nPlicand, $bTutor = True)
Local $nResult = 0
If ($nPlier < 0) Then
$nPlier =- $nPlier
$nPlicand =- $nPlicand
ElseIf ($nPlicand > 0) And ($nPlier > $nPlicand) Then
$nPlier = $nPlicand
$nPlicand = $nPlier
EndIf
If $bTutor Then _
ConsoleWrite(StringFormat("Ethiopian multiplication of %d by %d...\n", $nPlier, $nPlicand))
While ($nPlier >= 1)
If Not IsEven($nPlier) Then
$nResult += $nPlicand
If $bTutor Then ConsoleWrite(StringFormat("%d\t%d\tKeep\n", $nPlier, $nPlicand))
Else
If $bTutor Then ConsoleWrite(StringFormat("%d\t%d\tStrike\n", $nPlier, $nPlicand))
EndIf
$nPlier = Halve($nPlier)
$nPlicand = Double($nPlicand)
WEnd
If $bTutor Then ConsoleWrite(StringFormat("Answer = %d\n", $nResult))
Return $nResult
EndFunc
MsgBox(0, "Ethiopian multiplication of 17 by 34", Ethiopian(17, 34) )
|
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
A
2
=
5
{\displaystyle A_{2}=5}
A
3
=
2
{\displaystyle A_{3}=2}
A
4
=
−
4
{\displaystyle A_{4}=-4}
A
5
=
3
{\displaystyle A_{5}=3}
A
6
=
0
{\displaystyle A_{6}=0}
3 is an equilibrium index, because:
A
0
+
A
1
+
A
2
=
A
4
+
A
5
+
A
6
{\displaystyle A_{0}+A_{1}+A_{2}=A_{4}+A_{5}+A_{6}}
6 is also an equilibrium index, because:
A
0
+
A
1
+
A
2
+
A
3
+
A
4
+
A
5
=
0
{\displaystyle A_{0}+A_{1}+A_{2}+A_{3}+A_{4}+A_{5}=0}
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence
A
{\displaystyle A}
.
Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
template <typename T>
std::vector<size_t> equilibrium(T first, T last)
{
typedef typename std::iterator_traits<T>::value_type value_t;
value_t left = 0;
value_t right = std::accumulate(first, last, value_t(0));
std::vector<size_t> result;
for (size_t index = 0; first != last; ++first, ++index)
{
right -= *first;
if (left == right)
{
result.push_back(index);
}
left += *first;
}
return result;
}
template <typename T>
void print(const T& value)
{
std::cout << value << "\n";
}
int main()
{
const int data[] = { -7, 1, 5, 2, -4, 3, 0 };
std::vector<size_t> indices(equilibrium(data, data + 7));
std::for_each(indices.begin(), indices.end(), print<size_t>);
} |
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
| #Factor | Factor | "HOME" os-env print |
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
| #Forth | Forth | s" HOME" getenv type |
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
| #Fortran | Fortran | program show_home
implicit none
character(len=32) :: home_val ! The string value of the variable HOME
integer :: home_len ! The actual length of the value
integer :: stat ! The status of the value:
! 0 = ok
! 1 = variable does not exist
! -1 = variable is not long enought to hold the result
call get_environment_variable('HOME', home_val, home_len, stat)
if (stat == 0) then
write(*,'(a)') 'HOME = '//trim(home_val)
else
write(*,'(a)') 'No HOME to go to!'
end if
end program show_home |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers are included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
Task
Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
Use that routine to find esthetic numbers in bases 2 through 16 and display, here on this page, the esthectic numbers from index (base × 4) through index (base × 6), inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1000 and 9999.
Stretch: Find and display, here on this page, the base 10 esthetic numbers with a magnitude between 1.0e8 and 1.3e8.
Related task
numbers with equal rises and falls
See also
OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
Numbers Aplenty - Esthetic numbers
Geeks for Geeks - Stepping numbers
| #Perl | Perl | use 5.020;
use warnings;
use experimental qw(signatures);
use ntheory qw(fromdigits todigitstring);
sub generate_esthetic ($root, $upto, $callback, $base = 10) {
my $v = fromdigits($root, $base);
return if ($v > $upto);
$callback->($v);
my $t = $root->[-1];
__SUB__->([@$root, $t + 1], $upto, $callback, $base) if ($t + 1 < $base);
__SUB__->([@$root, $t - 1], $upto, $callback, $base) if ($t - 1 >= 0);
}
sub between_esthetic ($from, $upto, $base = 10) {
my @list;
foreach my $k (1 .. $base - 1) {
generate_esthetic([$k], $upto,
sub($n) { push(@list, $n) if ($n >= $from) }, $base);
}
sort { $a <=> $b } @list;
}
sub first_n_esthetic ($n, $base = 10) {
for (my $m = $n * $n ; 1 ; $m *= $base) {
my @list = between_esthetic(1, $m, $base);
return @list[0 .. $n - 1] if @list >= $n;
}
}
foreach my $base (2 .. 16) {
say "\n$base-esthetic numbers at indices ${\(4*$base)}..${\(6*$base)}:";
my @list = first_n_esthetic(6 * $base, $base);
say join(' ', map { todigitstring($_, $base) } @list[4*$base-1 .. $#list]);
}
say "\nBase 10 esthetic numbers between 1,000 and 9,999:";
for (my @list = between_esthetic(1e3, 1e4) ; @list ;) {
say join(' ', splice(@list, 0, 20));
}
say "\nBase 10 esthetic numbers between 100,000,000 and 130,000,000:";
for (my @list = between_esthetic(1e8, 1.3e8) ; @list ;) {
say join(' ', splice(@list, 0, 9));
} |
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.
| #D | D | import std.stdio, std.range, std.algorithm, std.typecons;
auto eulersSumOfPowers() {
enum maxN = 250;
auto pow5 = iota(size_t(maxN)).map!(i => ulong(i) ^^ 5).array.assumeSorted;
foreach (immutable x0; 1 .. maxN)
foreach (immutable x1; 1 .. x0)
foreach (immutable x2; 1 .. x1)
foreach (immutable x3; 1 .. x2) {
immutable powSum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3];
if (pow5.contains(powSum))
return tuple(x0, x1, x2, x3, pow5.countUntil(powSum));
}
assert(false);
}
void main() {
writefln("%d^5 + %d^5 + %d^5 + %d^5 == %d^5", eulersSumOfPowers[]);
} |
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
| #Modula-3 | Modula-3 | PROCEDURE FactIter(n: CARDINAL): CARDINAL =
VAR
result := n;
counter := n - 1;
BEGIN
FOR i := counter TO 1 BY -1 DO
result := result * i;
END;
RETURN result;
END FactIter; |
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.
| #BaCon | BaCon | ' Even or odd
OPTION MEMTYPE int
SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim
n = IIF$(dim < 2, 0, VAL(arg$[1]))
PRINT n, " is ", IIF$(EVEN(n), "even", "odd") |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #OCaml | OCaml | (* Euler integration by recurrence relation.
* Given a function, and stepsize, provides a function of (t,y) which
* returns the next step: (t',y'). *)
let euler f ~step (t,y) = ( t+.step, y +. step *. f t y )
(* newton_cooling doesn't use time parameter, so _ is a placeholder *)
let newton_cooling ~k ~tr _ y = -.k *. (y -. tr)
(* analytic solution for Newton cooling *)
let analytic_solution ~k ~tr ~t0 t = tr +. (t0 -. tr) *. exp (-.k *. t) |
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
| #Forth | Forth | : choose ( n k -- nCk ) 1 swap 0 ?do over i - i 1+ */ loop nip ;
5 3 choose . \ 10
33 17 choose . \ 1166803110 |
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
| #Fortran | Fortran | program test_choose
implicit none
write (*, '(i0)') choose (5, 3)
contains
function factorial (n) result (res)
implicit none
integer, intent (in) :: n
integer :: res
integer :: i
res = product ((/(i, i = 1, n)/))
end function factorial
function choose (n, k) result (res)
implicit none
integer, intent (in) :: n
integer, intent (in) :: k
integer :: res
res = factorial (n) / (factorial (k) * factorial (n - k))
end function choose
end program test_choose |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Wren | Wren | // iterative (quick)
var fibItr = Fn.new { |n|
if (n < 2) return n
var a = 0
var b = 1
for (i in 2..n) {
var c = a + b
a = b
b = c
}
return b
}
// recursive (slow)
var fibRec
fibRec = Fn.new { |n|
if (n < 2) return n
return fibRec.call(n-1) + fibRec.call(n-2)
}
System.print("Iterative: %(fibItr.call(36))")
System.print("Recursive: %(fibRec.call(36))") |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Nim | Nim | import os, math, strutils, tables
let execName = getAppFilename().splitPath().tail
let srcName = execName & ".nim"
func entropy(str: string): float =
var counts: CountTable[char]
for ch in str:
counts.inc(ch)
for count in counts.values:
result -= count / str.len * log2(count / str.len)
echo "Source file entropy: ", srcName.readFile().entropy().formatFloat(ffDecimal, 5)
echo "Binary file entropy: ", execName.readFile().entropy().formatFloat(ffDecimal, 5) |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #PARI.2FGP | PARI/GP | entropy(s)=s=Vec(s);my(v=vecsort(s,,8));-sum(i=1,#v,(x->x*log(x))(sum(j=1,#s,v[i]==s[j])/#s))/log(2);
entropy(Str(entropy)) |
http://rosettacode.org/wiki/Entropy/Narcissist | Entropy/Narcissist |
Task
Write a computer program that computes and shows its own entropy.
Related Tasks
Fibonacci_word
Entropy
| #Perl | Perl | #!/usr/bin/perl
use strict ;
use warnings ;
use feature 'say' ;
sub log2 {
my $number = shift ;
return log( $number ) / log( 2 ) ;
}
open my $fh , "<" , $ARGV[ 0 ] or die "Can't open $ARGV[ 0 ]$!\n" ;
my %frequencies ;
my $totallength = 0 ;
while ( my $line = <$fh> ) {
chomp $line ;
next if $line =~ /^$/ ;
map { $frequencies{ $_ }++ } split( // , $line ) ;
$totallength += length ( $line ) ;
}
close $fh ;
my $infocontent = 0 ;
for my $letter ( keys %frequencies ) {
my $content = $frequencies{ $letter } / $totallength ;
$infocontent += $content * log2( $content ) ;
}
$infocontent *= -1 ;
say "The information content of the source file is $infocontent !" ; |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Common_Lisp | Common Lisp | ;; symbol to number
(defconstant +apple+ 0)
(defconstant +banana+ 1)
(defconstant +cherry+ 2)
;; number to symbol
(defun index-fruit (i)
(aref #(+apple+ +banana+ +cherry+) i)) |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Computer.2Fzero_Assembly | Computer/zero Assembly | LDA 4 ;load from memory address 4
STP
NOP
NOP
byte 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.