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/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
| #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
if *envars = 0 then envars := ["HOME", "TRACE", "BLKSIZE","STRSIZE","COEXPSIZE","MSTKSIZE", "IPATH","LPATH","NOERRBUF"]
every v := !sort(envars) do
write(v," = ",image(getenv(v))|"* not set *")
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
| #J | J | 2!:5'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
| #Python | Python | from collections import deque
from itertools import dropwhile, islice, takewhile
from textwrap import wrap
from typing import Iterable, Iterator
Digits = str # Alias for the return type of to_digits()
def esthetic_nums(base: int) -> Iterator[int]:
"""Generate the esthetic number sequence for a given base
>>> list(islice(esthetic_nums(base=10), 20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65]
"""
queue: deque[tuple[int, int]] = deque()
queue.extendleft((d, d) for d in range(1, base))
while True:
num, lsd = queue.pop()
yield num
new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)
num *= base # Shift num left one digit
queue.extendleft((num + d, d) for d in new_lsds)
def to_digits(num: int, base: int) -> Digits:
"""Return a representation of an integer as digits in a given base
>>> to_digits(0x3def84f0ce, base=16)
'3def84f0ce'
"""
digits: list[str] = []
while num:
num, d = divmod(num, base)
digits.append("0123456789abcdef"[d])
return "".join(reversed(digits)) if digits else "0"
def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:
"""Pretty print an iterable which returns strings
>>> pprint_it(map(str, range(20)), indent=0, width=40)
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19
<BLANKLINE>
"""
joined = ", ".join(it)
lines = wrap(joined, width=width - indent)
for line in lines:
print(f"{indent*' '}{line}")
print()
def task_2() -> None:
nums: Iterator[int]
for base in range(2, 16 + 1):
start, stop = 4 * base, 6 * base
nums = esthetic_nums(base)
nums = islice(nums, start - 1, stop) # start and stop are 1-based indices
print(
f"Base-{base} esthetic numbers from "
f"index {start} through index {stop} inclusive:\n"
)
pprint_it(to_digits(num, base) for num in nums)
def task_3(lower: int, upper: int, base: int = 10) -> None:
nums: Iterator[int] = esthetic_nums(base)
nums = dropwhile(lambda num: num < lower, nums)
nums = takewhile(lambda num: num <= upper, nums)
print(
f"Base-{base} esthetic numbers with "
f"magnitude between {lower:,} and {upper:,}:\n"
)
pprint_it(to_digits(num, base) for num in nums)
if __name__ == "__main__":
print("======\nTask 2\n======\n")
task_2()
print("======\nTask 3\n======\n")
task_3(1_000, 9_999)
print("======\nTask 4\n======\n")
task_3(100_000_000, 130_000_000)
|
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.
| #Elixir | Elixir | defmodule Euler do
def sum_of_power(max \\ 250) do
{p5, sum2} = setup(max)
sk = Enum.sort(Map.keys(sum2))
Enum.reduce(Enum.sort(Map.keys(p5)), Map.new, fn p,map ->
sum(sk, p5, sum2, p, map)
end)
end
defp setup(max) do
Enum.reduce(1..max, {%{}, %{}}, fn i,{p5,sum2} ->
i5 = i*i*i*i*i
add = for j <- i..max, into: sum2, do: {i5 + j*j*j*j*j, [i,j]}
{Map.put(p5, i5, i), add}
end)
end
defp sum([], _, _, _, map), do: map
defp sum([s|_], _, _, p, map) when p<=s, do: map
defp sum([s|t], p5, sum2, p, map) do
if sum2[p - s],
do: sum(t, p5, sum2, p, Map.put(map, Enum.sort(sum2[s] ++ sum2[p-s]), p5[p])),
else: sum(t, p5, sum2, p, map)
end
end
Enum.each(Euler.sum_of_power, fn {k,v} ->
IO.puts Enum.map_join(k, " + ", fn i -> "#{i}**5" end) <> " = #{v}**5"
end) |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Neko | Neko | var factorial = function(number) {
var i = 1;
var result = 1;
while(i <= number) {
result *= i;
i += 1;
}
return result;
};
$print(factorial(10)); |
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.
| #Befunge | Befunge | &2%52**"E"+,@ |
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.
| #BQN | BQN |
odd ← 2⊸|
!0 ≡ odd 12
!1 ≡ odd 31 |
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.
| #PicoLisp | PicoLisp | (load "@lib/math.l")
(de euler (F Y A B H)
(while (> B A)
(prinl (round A) " " (round Y))
(inc 'Y (*/ H (F A Y) 1.0))
(inc 'A H) ) )
(de newtonCoolingLaw (A B)
(*/ -0.07 (- B 20.) 1.0) )
(euler newtonCoolingLaw 100.0 0 100.0 2.0)
(euler newtonCoolingLaw 100.0 0 100.0 5.0)
(euler newtonCoolingLaw 100.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.
| #PL.2FI | PL/I | test: procedure options (main); /* 3 December 2012 */
declare (x, y, z) float;
declare (T0 initial (100), Tr initial (20)) float;
declare k float initial (0.07);
declare t fixed binary;
declare h fixed binary;
x, y, z = T0;
/* Step size is 2 seconds */
h = 2;
put skip data (h);
put skip list (' t By formula', 'By Euler');
do t = 0 to 100 by 2;
put skip edit (t, Tr + (T0 - Tr)/exp(k*t), x) (f(3), 2 f(17,10));
x = x + h*f(t, x);
end;
/* Step size is 5 seconds */
h = 5;
put skip data (h);
put skip list (' t By formula', 'By Euler');
do t = 0 to 100 by 5;
put skip edit ( t, Tr + (T0 - Tr)/exp(k*t), y) (f(3), 2 f(17,10));
y = y + h*f(t, y);
end;
/* Step size is 10 seconds */
h = 10;
put skip data (h);
put skip list (' t By formula', 'By Euler');
do t = 0 to 100 by 10;
put skip edit (t, Tr + (T0 - Tr)/exp(k*t), z) (f(3), 2 f(17,10));
z = z + h*f(t, z);
end;
f: procedure (dummy, T) returns (float);
declare dummy fixed binary;
declare T float;
return ( -k*(T - Tr) );
end f;
end test; |
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
| #Golfscript | Golfscript | ;5 3 # Set up demo input
{),(;{*}*}:f; # Define a factorial function
[email protected]@/\@-f/ |
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
| #Groovy | Groovy | def factorial = { x ->
assert x > -1
x == 0 ? 1 : (1..x).inject(1G) { BigInteger product, BigInteger factor -> product *= factor }
}
def combinations = { n, k ->
assert k >= 0
assert n >= k
factorial(n).intdiv(factorial(k)*factorial(n-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
| #Xojo | Xojo | Function fibo(n As Integer) As UInt64
Dim noOne As UInt64 = 1
Dim noTwo As UInt64 = 1
Dim sum As UInt64
For i As Integer = 3 To n
sum = noOne + noTwo
noTwo = noOne
noOne = sum
Next
Return noOne
End Function |
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
| #Ruby | Ruby | def entropy(s)
counts = s.each_char.tally
size = s.size.to_f
counts.values.reduce(0) do |entropy, count|
freq = count / size
entropy - freq * Math.log2(freq)
end
end
s = File.read(__FILE__)
p entropy(s)
|
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
| #Rust | Rust | use std::fs::File;
use std::io::{Read, BufReader};
fn entropy<I: IntoIterator<Item = u8>>(iter: I) -> f32 {
let mut histogram = [0u64; 256];
let mut len = 0u64;
for b in iter {
histogram[b as usize] += 1;
len += 1;
}
histogram
.iter()
.cloned()
.filter(|&h| h > 0)
.map(|h| h as f32 / len as f32)
.map(|ratio| -ratio * ratio.log2())
.sum()
}
fn main() {
let name = std::env::args().nth(0).expect("Could not get program name.");
let file = BufReader::new(File::open(name).expect("Could not read file."));
println!("Entropy is {}.", entropy(file.bytes().flatten()));
} |
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
| #Sidef | Sidef | func entropy(s) {
[0,
s.chars.freq.values.map {|c|
var f = c/s.len
f * f.log2
}...
]«-»
}
say entropy(File(__FILE__).open_r.slurp) |
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
| #Tcl | Tcl | proc entropy {str} {
set log2 [expr log(2)]
foreach char [split $str ""] {dict incr counts $char}
set entropy 0.0
foreach count [dict values $counts] {
set freq [expr {$count / double([string length $str])}]
set entropy [expr {$entropy - $freq * log($freq)/$log2}]
}
return $entropy
}
puts [format "entropy = %.5f" [entropy [read [open [info script]]]]] |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:
y
2
=
x
3
+
a
x
+
b
{\displaystyle y^{2}=x^{3}+ax+b}
a and b are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation +, such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:
P + Q + R = 0
Here 0 (zero) is the infinity point, for which the x and y values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points P, Q and R, we define the sum S = P + Q as the point (possibly the infinity point) such that S, R and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
S is thus defined as the symmetric of R towards the x axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the a and b parameters of secp256k1, i.e. respectively zero and seven.
Hint: You might need to define a "doubling" function, that returns P+P for any given point P.
Extra credit: define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point P and integer n, the point P + P + ... + P (n times).
| #C | C | #include <stdio.h>
#include <math.h>
#define C 7
typedef struct { double x, y; } pt;
pt zero(void) { return (pt){ INFINITY, INFINITY }; }
// should be INFINITY, but numeric precision is very much in the way
int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }
pt neg(pt p) { return (pt){ p.x, -p.y }; }
pt dbl(pt p) {
if (is_zero(p)) return p;
pt r;
double L = (3 * p.x * p.x) / (2 * p.y);
r.x = L * L - 2 * p.x;
r.y = L * (p.x - r.x) - p.y;
return r;
}
pt add(pt p, pt q) {
if (p.x == q.x && p.y == q.y) return dbl(p);
if (is_zero(p)) return q;
if (is_zero(q)) return p;
pt r;
double L = (q.y - p.y) / (q.x - p.x);
r.x = L * L - p.x - q.x;
r.y = L * (p.x - r.x) - p.y;
return r;
}
pt mul(pt p, int n) {
int i;
pt r = zero();
for (i = 1; i <= n; i <<= 1) {
if (i & n) r = add(r, p);
p = dbl(p);
}
return r;
}
void show(const char *s, pt p) {
printf("%s", s);
printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y);
}
pt from_y(double y) {
pt r;
r.x = pow(y * y - C, 1.0/3);
r.y = y;
return r;
}
int main(void) {
pt a, b, c, d;
a = from_y(1);
b = from_y(2);
show("a = ", a);
show("b = ", b);
show("c = a + b = ", c = add(a, b));
show("d = -c = ", d = neg(c));
show("c + d = ", add(c, d));
show("a + b + d = ", add(a, add(b, d)));
show("a * 12345 = ", mul(a, 12345));
return 0;
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Factor | Factor | IN: scratchpad { "sun" "mon" "tue" "wed" "thur" "fri" "sat" } <enum>
--- Data stack:
T{ enum f ~array~ }
IN: scratchpad [ 1 swap at ] [ keys ] bi
--- Data stack:
"mon"
{ 0 1 2 3 4 5 6 } |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Fantom | Fantom |
// create an enumeration with named constants
enum class Fruits { apple, banana, orange }
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Forth | Forth | 0 CONSTANT apple
1 CONSTANT banana
2 CONSTANT cherry
... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.
The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant.
You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.
For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.
Reference
Cellular automata: Is Rule 30 random? (PDF).
| #11l | 11l | V n = 64
F pow2(x)
R UInt64(1) << x
F evolve(UInt64 =state; rule)
L 10
V b = UInt64(0)
L(q) (7 .. 0).step(-1)
V st = state
b [|]= (st [&] 1) << q
state = 0
L(i) 0 .< :n
V t = ((st >> (i - 1)) [|] (st << (:n + 1 - i))) [&] 7
I (rule [&] pow2(t)) != 0
state [|]= pow2(i)
print(‘ ’b, end' ‘’)
print()
evolve(1, 30) |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8th | 8th | "" var, str |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AArch64_Assembly | AArch64 Assembly | str: .asciz "" |
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining equation, together with 𝒪.
There is a rule for adding two points on an elliptic curve to give a third point.
This addition operation and the set of points E(ℤp) form a group with identity 𝒪.
It is this group that is used in the construction of elliptic curve cryptosystems.
The addition rule — which can be explained geometrically — is summarized as follows:
1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp).
2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪.
3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q.
Then R = P + Q = (xR, yR), where
xR = λ^2 - xP - xQ
yR = λ·(xP - xR) - yP,
with
λ = (yP - yQ) / (xP - xQ) if P ≠ Q,
(3·xP·xP + a) / 2·yP if P = Q (point doubling).
Remark: there already is a task page requesting “a simplified (without modular arithmetic)
version of the elliptic curve arithmetic”.
Here we do add modulo operations. If also the domain is changed from reals to rationals,
the elliptic curves are no longer continuous but break up into a finite number of distinct points.
In that form we use them to implement ECDSA:
Elliptic curve digital signature algorithm.
A digital signature is the electronic analogue of a hand-written signature
that convinces the recipient that a message has been sent intact by the presumed sender.
Anyone with access to the public key of the signer may verify this signature.
Changing even a single bit of a signed message will cause the verification procedure to fail.
ECDSA key generation. Party A does the following:
1. Select an elliptic curve E defined over ℤp.
The number of points in E(ℤp) should be divisible by a large prime r.
2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪).
3. Select a random integer s in the interval [1, r - 1].
4. Compute W = sG.
The public key is (E, G, r, W), the private key is s.
ECDSA signature computation. To sign a message m, A does the following:
1. Compute message representative f = H(m), using a
cryptographic hash function.
Note that f can be greater than r but not longer (measuring bits).
2. Select a random integer u in the interval [1, r - 1].
3. Compute V = uG = (xV, yV) and c ≡ xV mod r (goto (2) if c = 0).
4. Compute d ≡ u^-1·(f + s·c) mod r (goto (2) if d = 0).
The signature for the message m is the pair of integers (c, d).
ECDSA signature verification. To verify A's signature, B should do the following:
1. Obtain an authentic copy of A's public key (E, G, r, W).
Verify that c and d are integers in the interval [1, r - 1].
2. Compute f = H(m) and h ≡ d^-1 mod r.
3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r.
4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r.
Accept the signature if and only if c1 = c.
To be cryptographically useful, the parameter r should have at least 250 bits.
The basis for the security of elliptic curve cryptosystems
is the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size:
given two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G,
determine an integer k such that W = kG and 0 ≤ k < r.
Task.
The task is to write a toy version of the ECDSA, quasi the equal of a real-world
implementation, but utilizing parameters that fit into standard arithmetic types.
To keep things simple there's no need for key export or a hash function (just a sample
hash value and a way to tamper with it). The program should be lenient where possible
(for example: if it accepts a composite modulus N it will either function as expected,
or demonstrate the principle of elliptic curve factorization)
— but strict where required (a point G that is not on E will always cause failure).
Toy ECDSA is of course completely useless for its cryptographic purpose.
If this bothers you, please add a multiple-precision version.
Reference.
Elliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see:
7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.)
7.1 The EC setting
7.1.2 EC domain parameters
7.1.3 EC key pairs
7.2 Primitives
7.2.7 ECSP-DSA (p. 35)
7.2.8 ECVP-DSA (p. 36)
Annex A. Number-theoretic background
A.9 Elliptic curves: overview (p. 115)
A.10 Elliptic curves: algorithms (p. 121)
| #Go | Go | package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"fmt"
"log"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
check(err)
fmt.Println("Private key:\nD:", priv.D)
pub := priv.Public().(*ecdsa.PublicKey)
fmt.Println("\nPublic key:")
fmt.Println("X:", pub.X)
fmt.Println("Y:", pub.Y)
msg := "Rosetta Code"
fmt.Println("\nMessage:", msg)
hash := sha256.Sum256([]byte(msg)) // as [32]byte
hexHash := fmt.Sprintf("0x%x", binary.BigEndian.Uint32(hash[:]))
fmt.Println("Hash :", hexHash)
r, s, err := ecdsa.Sign(rand.Reader, priv, hash[:])
check(err)
fmt.Println("\nSignature:")
fmt.Println("R:", r)
fmt.Println("S:", s)
valid := ecdsa.Verify(&priv.PublicKey, hash[:], r, s)
fmt.Println("\nSignature verified:", valid)
} |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #AutoHotkey | AutoHotkey | MsgBox % isDir_empty(A_ScriptDir)?"true":"false"
isDir_empty(p) {
Loop, %p%\* , 1
return 0
return 1
} |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #AWK | AWK |
# syntax: GAWK -f EMPTY_DIRECTORY.AWK
BEGIN {
n = split("C:\\TEMP3,C:\\NOTHERE,C:\\AWK\\FILENAME,C:\\WINDOWS",arr,",")
for (i=1; i<=n; i++) {
printf("'%s' %s\n",arr[i],is_dir(arr[i]))
}
exit(0)
}
function is_dir(path, cmd,dots,entries,msg,rec,valid_dir) {
cmd = sprintf("DIR %s 2>NUL",path) # MS-Windows
while ((cmd | getline rec) > 0) {
if (rec ~ /[0-9]:[0-5][0-9]/) {
if (rec ~ / (\.|\.\.)$/) { # . or ..
dots++
continue
}
entries++
}
if (rec ~ / Dir\(s\) .* bytes free$/) {
valid_dir = 1
}
}
close(cmd)
if (valid_dir == 0) {
msg = "does not exist"
}
else if (valid_dir == 1 && entries == 0) {
msg = "is an empty directory"
}
else if (dots == 0 && entries == 1) {
msg = "is a file"
}
else {
msg = sprintf("is a directory with %d entries",entries)
}
return(msg)
}
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #68000_Assembly | 68000 Assembly | forever:
MOVE.B D0,$300001
JMP forever |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #8051_Assembly | 8051 Assembly | ORG RESET
jmp $ |
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.
| #Go | Go | package main
func main() {
s := "immutable"
s[0] = 'a'
} |
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.
| #Haskell | Haskell | pi = 3.14159
msg = "Hello World" |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #Icon_and_Unicon | Icon and Unicon | $define "1234" |
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.
| #J | J | B=: A=: 'this is a test'
A=: '*' 2 3 5 7} A
A
th** *s*a test
B
this is a test |
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
| #BASIC | BASIC | 10 DEF FN L(X)=LOG(X)/LOG(2)
20 S$="1223334444"
30 U$=""
40 FOR I=1 TO LEN(S$)
50 K=0
60 FOR J=1 TO LEN(U$)
70 IF MID$(U$,J,1)=MID$(S$,I,1) THEN K=1
80 NEXT J
90 IF K=0 THEN U$=U$+MID$(S$,I,1)
100 NEXT I
110 DIM R(LEN(U$)-1)
120 FOR I=1 TO LEN(U$)
130 C=0
140 FOR J=1 TO LEN(S$)
150 IF MID$(U$,I,1)=MID$(S$,J,1) THEN C=C+1
160 NEXT J
170 R(I-1)=(C/LEN(S$))*FN L(C/LEN(S$))
180 NEXT I
190 E=0
200 FOR I=0 TO LEN(U$)-1
210 E=E-R(I)
220 NEXT I
230 PRINT E |
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
| #BBC_BASIC | BBC BASIC | REM >entropy
PRINT FNentropy("1223334444")
END
:
DEF FNentropy(x$)
LOCAL unique$, count%, n%, ratio(), u%, i%, j%
unique$ = ""
n% = LEN x$
FOR i% = 1 TO n%
IF INSTR(unique$, MID$(x$, i%, 1)) = 0 THEN unique$ += MID$(x$, i%, 1)
NEXT
u% = LEN unique$
DIM ratio(u% - 1)
FOR i% = 1 TO u%
count% = 0
FOR j% = 1 TO n%
IF MID$(unique$, i%, 1) = MID$(x$, j%, 1) THEN count% += 1
NEXT
ratio(i% - 1) = (count% / n%) * FNlogtwo(count% / n%)
NEXT
= -SUM(ratio())
:
DEF FNlogtwo(n)
= LN n / LN 2 |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Bracmat | Bracmat | ( (halve=.div$(!arg.2))
& (double=.2*!arg)
& (isEven=.mod$(!arg.2):0)
& ( mul
= a b as bs newbs result
. !arg:(?as.?bs)
& whl
' ( !as:? (%@:~1:?a)
& !as halve$!a:?as
& !bs:? %@?b
& !bs double$!b:?bs
)
& :?newbs
& whl
' ( !as:%@?a ?as
& !bs:%@?b ?bs
& (isEven$!a|!newbs !b:?newbs)
)
& 0:?result
& whl
' (!newbs:%@?b ?newbs&!b+!result:?result)
& !result
)
& out$(mul$(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.
| #Factor | Factor | USE: math.vectors
: accum-left ( seq id quot -- seq ) accumulate nip ; inline
: accum-right ( seq id quot -- seq ) [ <reversed> ] 2dip accum-left <reversed> ; inline
: equilibrium-indices ( seq -- inds )
0 [ + ] [ accum-left ] [ accum-right ] 3bi [ = ] 2map
V{ } swap dup length iota [ [ suffix ] curry [ ] if ] 2each ; |
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.
| #Fortran | Fortran | program Equilibrium
implicit none
integer :: array(7) = (/ -7, 1, 5, 2, -4, 3, 0 /)
call equil_index(array)
contains
subroutine equil_index(a)
integer, intent(in) :: a(:)
integer :: i
do i = 1, size(a)
if(sum(a(1:i-1)) == sum(a(i+1:size(a)))) write(*,*) i
end do
end subroutine
end program |
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
| #Java | Java | System.getenv("HOME") // get env var
System.getenv() // get the entire environment as a Map of keys to values |
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
| #JavaScript | JavaScript | var shell = new ActiveXObject("WScript.Shell");
var env = shell.Environment("PROCESS");
WScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT')); |
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
| #Joy | Joy | "HOME" getenv. |
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
| #Raku | Raku | use Lingua::EN::Numbers;
sub esthetic($base = 10) {
my @s = ^$base .map: -> \s {
((s - 1).base($base) if s > 0), ((s + 1).base($base) if s < $base - 1)
}
flat [ (1 .. $base - 1)».base($base) ],
{ [ flat .map: { $_ xx * Z~ flat @s[.comb.tail.parse-base($base)] } ] } … *
}
for 2 .. 16 -> $b {
put "\n{(4 × $b).&ordinal-digit} through {(6 × $b).&ordinal-digit} esthetic numbers in base $b";
put esthetic($b)[(4 × $b - 1) .. (6 × $b - 1)]».fmt('%3s').batch(16).join: "\n"
}
my @e10 = esthetic;
put "\nBase 10 esthetic numbers between 1,000 and 9,999:";
put @e10.&between(1000, 9999).batch(20).join: "\n";
put "\nBase 10 esthetic numbers between {1e8.Int.&comma} and {1.3e8.Int.&comma}:";
put @e10.&between(1e8.Int, 1.3e8.Int).batch(9).join: "\n";
sub between (@array, Int $lo, Int $hi) {
my $top = @array.first: * > $hi, :k;
@array[^$top].grep: * > $lo
} |
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.
| #ERRE | ERRE | PROGRAM EULERO
CONST MAX=250
!$DOUBLE
FUNCTION POW5(X)
POW5=X*X*X*X*X
END FUNCTION
!$INCLUDE="PC.LIB"
BEGIN
CLS
FOR X0=1 TO MAX DO
FOR X1=1 TO X0 DO
FOR X2=1 TO X1 DO
FOR X3=1 TO X2 DO
LOCATE(3,1) PRINT(X0;X1;X2;X3)
SUM=POW5(X0)+POW5(X1)+POW5(X2)+POW5(X3)
S1=INT(SUM^0.2#+0.5#)
IF SUM=POW5(S1) THEN PRINT(X0,X1,X2,X3,S1) END IF
END FOR
END FOR
END FOR
END FOR
END PROGRAM |
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
| #Nemerle | Nemerle | using System;
using System.Console;
module Program
{
Main() : void
{
WriteLine("Factorial of which number?");
def number = long.Parse(ReadLine());
WriteLine("Using Fold : Factorial of {0} is {1}", number, FactorialFold(number));
WriteLine("Using Match: Factorial of {0} is {1}", number, FactorialMatch(number));
WriteLine("Iterative : Factorial of {0} is {1}", number, FactorialIter(number));
}
FactorialFold(number : long) : long
{
$[1L..number].FoldLeft(1L, _ * _ )
}
FactorialMatch(number : long) : long
{
|0L => 1L
|n => n * FactorialMatch(n - 1L)
}
FactorialIter(number : long) : long
{
mutable accumulator = 1L;
for (mutable factor = 1L; factor <= number; factor++)
{
accumulator *= factor;
}
accumulator //implicit return
}
} |
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.
| #Bracmat | Bracmat | ( ( even
=
. @( !arg
: ?
[-2
( 0
| 2
| 4
| 6
| 8
)
)
)
& (odd=.~(even$!arg))
& ( eventest
=
. out
$ (!arg is (even$!arg&|not) even)
)
& ( oddtest
=
. out
$ (!arg is (odd$!arg&|not) odd)
)
& eventest$5556
& oddtest$5556
& eventest$857234098750432987502398457089435
& oddtest$857234098750432987502398457089435
) |
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.
| #Brainf.2A.2A.2A | Brainf*** | ,[>,----------] Read until newline
++< Get a 2 and move into position
[->-[>+>>]> Do
[+[-<+>]>+>>] divmod
<<<<<] magic
>[-]<++++++++ Clear and get an 8
[>++++++<-] to get a 48
>[>+<-]>. to get n % 2 to ASCII and print |
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.
| #PowerShell | PowerShell |
function euler (${f}, ${y}, $y0, $t0, $tEnd) {
function f-euler ($tn, $yn, $h) {
$yn + $h*(f $tn $yn)
}
function time ($t0, $h, $tEnd) {
$end = [MATH]::Floor(($tEnd - $t0)/$h)
foreach ($_ in 0..$end) { $_*$h + $t0 }
}
$time = time $t0 10 $tEnd
$time5 = time $t0 5 $tEnd
$time2 = time $t0 2 $tEnd
$yn10 = $yn5 = $yn2 = $y0
$i2 = $i5 = 0
foreach ($tn10 in $time) {
while($time2[$i2] -ne $tn10) {
$i2++
$yn2 = (f-euler $time2[$i2] $yn2 2)
}
while($time5[$i5] -ne $tn10) {
$i5++
$yn5 = (f-euler $time5[$i5] $yn5 5)
}
[pscustomobject]@{
t = "$tn10"
Analytical = "$("{0:N5}" -f (y $tn10))"
"Euler h = 2" = "$("{0:N5}" -f $yn2)"
"Euler h = 5" = "$("{0:N5}" -f $yn5)"
"Euler h = 10" = "$("{0:N5}" -f $yn10)"
"Error h = 2" = "$("{0:N5}" -f [MATH]::abs($yn2 - (y $tn10)))"
"Error h = 5" = "$("{0:N5}" -f [MATH]::abs($yn5 - (y $tn10)))"
"Error h = 10" = "$("{0:N5}" -f [MATH]::abs($yn10 - (y $tn10)))"
}
$yn10 = (f-euler $tn10 $yn10 10)
}
}
$k, $yr, $y0, $t0, $tEnd = 0.07, 20, 100, 0, 100
function f ($t, $y) {
-$k *($y - $yr)
}
function y ($t) {
$yr + ($y0 - $yr)*[MATH]::Exp(-$k*$t)
}
euler f y $y0 $t0 $tEnd | Format-Table -AutoSize
|
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
| #GW-BASIC | GW-BASIC | 10 REM BINOMIAL CALCULATOR
20 INPUT "N? ", N
30 INPUT "P? ", P
40 GOSUB 70
50 PRINT C
60 END
70 C = 0
80 IF N < 0 OR P<0 OR P > N THEN RETURN
90 IF P < N\2 THEN P = N - P
100 C = 1
110 FOR I = N TO P+1 STEP -1
120 C=C*I
130 NEXT I
140 FOR I = 1 TO N-P
150 C=C/I
160 NEXT I
170 RETURN |
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
| #XPL0 | XPL0 | func Fib1(N); \Return Nth Fibonacci number using iteration
int N;
int Fn, F0, F1;
[F0:= 0; F1:= 1; Fn:= N;
while N > 1 do
[Fn:= F0 + F1;
F0:= F1;
F1:= Fn;
N:= N-1;
];
return Fn;
];
func Fib2(N); \Return Nth Fibonacci number using recursion
int N;
return if N < 2 then N else Fib2(N-1) + Fib2(N-2);
int N;
[for N:= 0 to 20 do [IntOut(0, Fib1(N)); ChOut(0, ^ )];
CrLf(0);
for N:= 0 to 20 do [IntOut(0, Fib2(N)); ChOut(0, ^ )];
CrLf(0);
] |
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
| #Vlang | Vlang | import os
import math
fn main() {
println("Binary file entropy: ${entropy(os.args[0])?}")
}
fn entropy(file string) ?f64 {
d := os.read_bytes(file)?
mut f := [256]f64{}
for b in d {
f[b]++
}
mut hm := 0.0
for c in f {
if c > 0 {
hm += c * math.log2(c)
}
}
l := f64(d.len)
return math.log2(l) - hm/l
} |
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
| #Wren | Wren | import "os" for Process
import "io" for File
var args = Process.allArguments
var s = File.read(args[1]).trim()
var m = {}
for (c in s) {
var d = m[c]
m[c] = (d) ? d + 1 : 1
}
var hm = 0
for (k in m.keys) {
var c = m[k]
hm = hm + c * c.log2
}
var l = s.count
System.print(l.log2 - hm/l) |
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
| #zkl | zkl | fcn entropy(text){
text.pump(Void,fcn(c,freq){ c=c.toAsc(); freq[c]=freq[c]+1; freq }
.fp1((0).pump(256,List,(0.0).create.fp(0)).copy()))
.filter() // remove all zero entries
.apply('/(text.len())) // (num of char)/len
.apply(fcn(p){-p*p.log()}) // |p*ln(p)|
.sum(0.0)/(2.0).log(); // sum * ln(e)/ln(2) to convert to log2
}
entropy(File("entropy.zkl").read().text).println(); |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbers should be in order.
Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.
The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.
See also
Wikipedia, Emirp.
The Prime Pages, emirp.
Wolfram MathWorld™, Emirp.
The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
| #11l | 11l | F reversed(Int =n)
V result = 0
L
result = 10 * result + n % 10
n I/= 10
I n == 0
R result
V limit = 1'000'000
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
F is_emirp(n)
I !:is_prime[n]
R 0B
V r = reversed(n)
R r != n & :is_prime[r]
print(‘First 20 emirps:’, end' ‘’)
V count = 0
L(n) 0 .< limit
I is_emirp(n)
print(‘ ’n, end' ‘’)
I ++count == 20
L.break
print()
print(‘Emirps between 7700 and 8000:’, end' ‘’)
L(n) 7700..8000
I is_emirp(n)
print(‘ ’n, end' ‘’)
print()
count = 0
L(n) 0 .< limit
I is_emirp(n)
I ++count == 10000
print(‘The 10000th emirp: ’n)
L.break |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:
y
2
=
x
3
+
a
x
+
b
{\displaystyle y^{2}=x^{3}+ax+b}
a and b are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation +, such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:
P + Q + R = 0
Here 0 (zero) is the infinity point, for which the x and y values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points P, Q and R, we define the sum S = P + Q as the point (possibly the infinity point) such that S, R and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
S is thus defined as the symmetric of R towards the x axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the a and b parameters of secp256k1, i.e. respectively zero and seven.
Hint: You might need to define a "doubling" function, that returns P+P for any given point P.
Extra credit: define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point P and integer n, the point P + P + ... + P (n times).
| #C.2B.2B | C++ | #include <cmath>
#include <iostream>
using namespace std;
// define a type for the points on the elliptic curve that behaves
// like a built in type.
class EllipticPoint
{
double m_x, m_y;
static constexpr double ZeroThreshold = 1e20;
static constexpr double B = 7; // the 'b' in y^2 = x^3 + a * x + b
// 'a' is 0
void Double() noexcept
{
if(IsZero())
{
// doubling zero is still zero
return;
}
// based on the property of the curve, the line going through the
// current point and the negative doubled point is tangent to the
// curve at the current point. wikipedia has a nice diagram.
if(m_y == 0)
{
// at this point the tangent to the curve is vertical.
// this point doubled is 0
*this = EllipticPoint();
}
else
{
double L = (3 * m_x * m_x) / (2 * m_y);
double newX = L * L - 2 * m_x;
m_y = L * (m_x - newX) - m_y;
m_x = newX;
}
}
public:
friend std::ostream& operator<<(std::ostream&, const EllipticPoint&);
// Create a point that is initialized to Zero
constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {}
// Create a point based on the yCoordiante. For a curve with a = 0 and b = 7
// there is only one x for each y
explicit EllipticPoint(double yCoordinate) noexcept
{
m_y = yCoordinate;
m_x = cbrt(m_y * m_y - B);
}
// Check if the point is 0
bool IsZero() const noexcept
{
// when the elliptic point is at 0, y = +/- infinity
bool isNotZero = abs(m_y) < ZeroThreshold;
return !isNotZero;
}
// make a negative version of the point (p = -q)
EllipticPoint operator-() const noexcept
{
EllipticPoint negPt;
negPt.m_x = m_x;
negPt.m_y = -m_y;
return negPt;
}
// add a point to this one ( p+=q )
EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept
{
if(IsZero())
{
*this = rhs;
}
else if (rhs.IsZero())
{
// since rhs is zero this point does not need to be
// modified
}
else
{
double L = (rhs.m_y - m_y) / (rhs.m_x - m_x);
if(isfinite(L))
{
double newX = L * L - m_x - rhs.m_x;
m_y = L * (m_x - newX) - m_y;
m_x = newX;
}
else
{
if(signbit(m_y) != signbit(rhs.m_y))
{
// in this case rhs == -lhs, the result should be 0
*this = EllipticPoint();
}
else
{
// in this case rhs == lhs.
Double();
}
}
}
return *this;
}
// subtract a point from this one (p -= q)
EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept
{
*this+= -rhs;
return *this;
}
// multiply the point by an integer (p *= 3)
EllipticPoint& operator*=(int rhs) noexcept
{
EllipticPoint r;
EllipticPoint p = *this;
if(rhs < 0)
{
// change p * -rhs to -p * rhs
rhs = -rhs;
p = -p;
}
for (int i = 1; i <= rhs; i <<= 1)
{
if (i & rhs) r += p;
p.Double();
}
*this = r;
return *this;
}
};
// add points (p + q)
inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept
{
lhs += rhs;
return lhs;
}
// subtract points (p - q)
inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept
{
lhs += -rhs;
return lhs;
}
// multiply by an integer (p * 3)
inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept
{
lhs *= rhs;
return lhs;
}
// multiply by an integer (3 * p)
inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept
{
rhs *= lhs;
return rhs;
}
// print the point
ostream& operator<<(ostream& os, const EllipticPoint& pt)
{
if(pt.IsZero()) cout << "(Zero)\n";
else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n";
return os;
}
int main(void) {
const EllipticPoint a(1), b(2);
cout << "a = " << a;
cout << "b = " << b;
const EllipticPoint c = a + b;
cout << "c = a + b = " << c;
cout << "a + b - c = " << a + b - c;
cout << "a + b - (b + a) = " << a + b - (b + a) << "\n";
cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a;
cout << "a * 12345 = " << a * 12345;
cout << "a * -12345 = " << a * -12345;
cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345;
cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345);
cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n";
const EllipticPoint zero;
EllipticPoint g;
cout << "g = zero = " << g;
cout << "g += a = " << (g+=a);
cout << "g += zero = " << (g+=zero);
cout << "g += b = " << (g+=b);
cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n";
EllipticPoint special(0); // the point where the curve crosses the x-axis
cout << "special = " << special; // this has the minimum possible value for x
cout << "special *= 2 = " << (special*=2); // doubling it gives zero
return 0;
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Fortran | Fortran | enum, bind(c)
enumerator :: one=1, two, three, four, five
enumerator :: six, seven, nine=9
end enum |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Free_Pascal | Free Pascal | ' FB 1.05.0 Win64
Enum Animals
Cat
Dog
Zebra
End Enum
Enum Dogs
Bulldog = 1
Terrier = 2
WolfHound = 4
End Enum
Print Cat, Dog, Zebra
Print Bulldog, Terrier, WolfHound
Sleep |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Enum Animals
Cat
Dog
Zebra
End Enum
Enum Dogs
Bulldog = 1
Terrier = 2
WolfHound = 4
End Enum
Print Cat, Dog, Zebra
Print Bulldog, Terrier, WolfHound
Sleep |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.
The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant.
You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.
For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.
Reference
Cellular automata: Is Rule 30 random? (PDF).
| #C | C | #include <stdio.h>
#include <limits.h>
typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))
void evolve(ull state, int rule)
{
int i, p, q, b;
for (p = 0; p < 10; p++) {
for (b = 0, q = 8; q--; ) {
ull st = state;
b |= (st&1) << q;
for (state = i = 0; i < N; i++)
if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
state |= B(i);
}
printf(" %d", b);
}
putchar('\n');
return;
}
int main(void)
{
evolve(1, 30);
return 0;
} |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.
The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant.
You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.
For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.
Reference
Cellular automata: Is Rule 30 random? (PDF).
| #C.2B.2B | C++ | #include <bitset>
#include <stdio.h>
#define SIZE 80
#define RULE 30
#define RULE_TEST(x) (RULE & 1 << (7 & (x)))
void evolve(std::bitset<SIZE> &s) {
int i;
std::bitset<SIZE> t(0);
t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );
t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] );
for (i = 1; i < SIZE-1; i++)
t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );
for (i = 0; i < SIZE; i++) s[i] = t[i];
}
void show(std::bitset<SIZE> s) {
int i;
for (i = SIZE; i--; ) printf("%c", s[i] ? '#' : ' ');
printf("|\n");
}
unsigned char byte(std::bitset<SIZE> &s) {
unsigned char b = 0;
int i;
for (i=8; i--; ) {
b |= s[0] << i;
evolve(s);
}
return b;
}
int main() {
int i;
std::bitset<SIZE> state(1);
for (i=10; i--; )
printf("%u%c", byte(state), i ? ' ' : '\n');
return 0;
} |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ACL2 | ACL2 | (= (length str) 0) |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Action.21 | Action! | PROC CheckIsEmpty(CHAR ARRAY s)
PrintF("'%S' is empty? ",s)
IF s(0)=0 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
PROC Main()
CHAR ARRAY str1,str2
str1=""
str2="text"
CheckIsEmpty(str1)
CheckIsEmpty(str2)
RETURN |
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining equation, together with 𝒪.
There is a rule for adding two points on an elliptic curve to give a third point.
This addition operation and the set of points E(ℤp) form a group with identity 𝒪.
It is this group that is used in the construction of elliptic curve cryptosystems.
The addition rule — which can be explained geometrically — is summarized as follows:
1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp).
2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪.
3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q.
Then R = P + Q = (xR, yR), where
xR = λ^2 - xP - xQ
yR = λ·(xP - xR) - yP,
with
λ = (yP - yQ) / (xP - xQ) if P ≠ Q,
(3·xP·xP + a) / 2·yP if P = Q (point doubling).
Remark: there already is a task page requesting “a simplified (without modular arithmetic)
version of the elliptic curve arithmetic”.
Here we do add modulo operations. If also the domain is changed from reals to rationals,
the elliptic curves are no longer continuous but break up into a finite number of distinct points.
In that form we use them to implement ECDSA:
Elliptic curve digital signature algorithm.
A digital signature is the electronic analogue of a hand-written signature
that convinces the recipient that a message has been sent intact by the presumed sender.
Anyone with access to the public key of the signer may verify this signature.
Changing even a single bit of a signed message will cause the verification procedure to fail.
ECDSA key generation. Party A does the following:
1. Select an elliptic curve E defined over ℤp.
The number of points in E(ℤp) should be divisible by a large prime r.
2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪).
3. Select a random integer s in the interval [1, r - 1].
4. Compute W = sG.
The public key is (E, G, r, W), the private key is s.
ECDSA signature computation. To sign a message m, A does the following:
1. Compute message representative f = H(m), using a
cryptographic hash function.
Note that f can be greater than r but not longer (measuring bits).
2. Select a random integer u in the interval [1, r - 1].
3. Compute V = uG = (xV, yV) and c ≡ xV mod r (goto (2) if c = 0).
4. Compute d ≡ u^-1·(f + s·c) mod r (goto (2) if d = 0).
The signature for the message m is the pair of integers (c, d).
ECDSA signature verification. To verify A's signature, B should do the following:
1. Obtain an authentic copy of A's public key (E, G, r, W).
Verify that c and d are integers in the interval [1, r - 1].
2. Compute f = H(m) and h ≡ d^-1 mod r.
3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r.
4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r.
Accept the signature if and only if c1 = c.
To be cryptographically useful, the parameter r should have at least 250 bits.
The basis for the security of elliptic curve cryptosystems
is the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size:
given two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G,
determine an integer k such that W = kG and 0 ≤ k < r.
Task.
The task is to write a toy version of the ECDSA, quasi the equal of a real-world
implementation, but utilizing parameters that fit into standard arithmetic types.
To keep things simple there's no need for key export or a hash function (just a sample
hash value and a way to tamper with it). The program should be lenient where possible
(for example: if it accepts a composite modulus N it will either function as expected,
or demonstrate the principle of elliptic curve factorization)
— but strict where required (a point G that is not on E will always cause failure).
Toy ECDSA is of course completely useless for its cryptographic purpose.
If this bothers you, please add a multiple-precision version.
Reference.
Elliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see:
7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.)
7.1 The EC setting
7.1.2 EC domain parameters
7.1.3 EC key pairs
7.2 Primitives
7.2.7 ECSP-DSA (p. 35)
7.2.8 ECVP-DSA (p. 36)
Annex A. Number-theoretic background
A.9 Elliptic curves: overview (p. 115)
A.10 Elliptic curves: algorithms (p. 121)
| #Julia | Julia | module ToyECDSA
using SHA
import Base.in, Base.==, Base.+, Base.*
export ECDSA_Key, ECDSA_Public_Key, genkey, ECDSA_sign, isverifiedECDSA
# T will be BigInt in most applications
struct CurveFP{T}
p::T
a::T
b::T
CurveFP(p, a::T, b::T) where T <: Number = new{T}(p, a, b)
end
struct PointEC{T}
curve::CurveFP{T}
x::T
y::T
order::Union{Number, Nothing}
function PointEC(curve, x::T, y::T, order=nothing) where T <: Number
@assert((x, y) in curve)
new{T}(curve, x, y, order)
end
end
struct PointINF end
const INFINITY = PointINF()
function ==(point_a::PointEC, point_b::PointEC)
if point_a.curve == point_b.curve && point_a.x == point_b.x && point_a.y == point_b.y
return true
end
return false
end
function ==(curve_a::CurveFP, curve_b::CurveFP)
if curve_a.a == curve_b.a && curve_a.b == curve_b.b && curve_a.p == curve_b.p
return true
end
return false
end
+(point_a::PointINF, point_b::PointINF) = point_b
+(point_a::PointINF, point_b::PointEC) = point_b
+(point_a::PointEC, point_b::PointINF) = point_a
function +(point_a::PointEC, point_b::PointEC)
@assert(point_a.curve == point_b.curve)
if point_a.x == point_b.x
if (point_a.y + point_b.y) % point_a.curve.p == 0
return INFINITY
else
return double(point_a)
end
end
p = point_a.curve.p
λ = (point_a.y - point_b.y) * invmod(point_a.x - point_b.x, p)
xr = mod(λ * λ - point_a.x - point_b.x, p)
yr = mod(λ * (point_a.x - xr) - point_a.y, p)
return PointEC(point_a.curve, xr, yr, point_a.order)
end
*(point_a::PointINF, int_b::Number) = INFINITY
*(int_b::Number, point_a::PointINF) = INFINITY
*(int_b::Number, point_a::PointEC) = point_a * int_b
function *(point_a::PointEC, int_b::Number)
leftmost_bit(x) = big"2"^Int(trunc(log(2, x)))
if point_a.order != nothing
int_b %= point_a.order
end
if int_b == 0
return INFINITY
end
int_3b = 3 * int_b
negative_a = PointEC(point_a.curve, point_a.x, -point_a.y, point_a.order)
i = BigInt(leftmost_bit(int_3b) ÷ 2)
result = point_a
while i > 1
result = double(result)
if (int_3b & i) != 0 && (int_b & i) == 0
result += point_a
end
if (int_3b & i) == 0 && (int_b & i) != 0
result += negative_a
end
i ÷= 2
end
return result
end
in(z::Tuple, curve::CurveFP) = (z[2]^2 - (z[1]^3 + curve.a*z[1] + curve.b)) % curve.p == 0
in(x::Number,y::Number, curve::CurveFP) = (y^2 -(x^3 + curve.a*x + curve.b)) % curve.p == 0
in(p::PointEC, curve::CurveFP) = (p.y^2 - (p.x^3 + curve.a * p.x + curve.b)) % curve.p == 0
in(point::PointINF, curve::CurveFP) = true
double(point_a::PointINF) = INFINITY
function double(point_a::PointEC)
a, p = point_a.curve.a, point_a.curve.p
l = mod((3 * point_a.x^2 + a) * invmod(2 * point_a.y, p), p)
x3 = mod(l^2 - 2 * point_a.x, p)
y3 = mod(l * (point_a.x - x3) - point_a.y, p)
return PointEC(point_a.curve, x3, y3, point_a.order)
end
const secp256k1 = ( # use the Bitcoin ECDSA curve
p = big"0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F",
a = big"0x0",
b = big"0x7",
r = big"0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141",
Gx = big"0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798",
Gy = big"0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",
)
@assert((secp256k1.Gy^2 - secp256k1.Gx^3 - 7) % secp256k1.p == 0)
function generatemultiplier(stdcurve)
return foldl((x, y) -> 16 * BigInt(x) + y, rand(0:16, ndigits(stdcurve.r - 1, base=16)))
end
struct ECDSA_Key
E::CurveFP
secret::BigInt
G::PointEC
r::BigInt
W::PointEC
end
struct ECDSA_Public_Key
E::CurveFP
G::PointEC
r::BigInt
W::PointEC
end
function genkey(curve=secp256k1) # default: use Bitcoin standard EC curve secp256k1
E = CurveFP(curve.p, curve.a, curve.b)
s = generatemultiplier(curve)
G = PointEC(E, curve.Gx, curve.Gy, curve.r)
W = s * G
return ECDSA_Key(E, s, G, curve.r, W)
end
aspublickey(k::ECDSA_Key) = ECDSA_Public_Key(k.E, k.G, k.r, k.W)
privatekey(k::ECDSA_Key) = k.secret
function ECDSA_sign(m::String, key::ECDSA_Key, digestfunction=sha256)
r, f = key.r, digestfunction(codeunits(m)) # f = H(m)
# order of curve points length must be >= sha digest length (in bytes)
@assert(ndigits(r, base=16) >= length(f))
c, d, bindigest = BigInt(0), BigInt(0), foldl((x, y) -> 16 * BigInt(x) + y, f)
while c == 0 || d == 0
u = generatemultiplier(secp256k1)
V = u * key.G
c = mod(V.x, r)
d = mod((invmod(u, r) * (bindigest + key.secret * c)), r)
end
return aspublickey(key), c, d
end
function isverifiedECDSA(m::String, publickey, c, d, digestfunction=sha256)
if 1 <= c < publickey.r && 1 <= d < publickey.r
r, f = publickey.r, digestfunction(codeunits(m))
h, bindigest = invmod(d, r), foldl((x, y) -> 16 * BigInt(x) + y, f)
h1, h2 = mod(bindigest * h, r), mod(c * h, r)
verifierpoint = h1 * publickey.G + h2 * publickey.W
return mod(verifierpoint.x, r) == c
end
return false
end
end # module
using .ToyECDSA
const key = genkey()
const msg = "Bill says this is an elliptic curve digital signature algorithm."
const altered = "Bill says this isn't an elliptic curve digital signature algorithm."
publickey, c, d = ECDSA_sign(msg, key)
println("ECDSA of message <$msg> verified: ", isverifiedECDSA(msg, publickey, c, d))
println("ECDSA of message <$altered> verified: ", isverifiedECDSA(altered, publickey, c, d))
|
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining equation, together with 𝒪.
There is a rule for adding two points on an elliptic curve to give a third point.
This addition operation and the set of points E(ℤp) form a group with identity 𝒪.
It is this group that is used in the construction of elliptic curve cryptosystems.
The addition rule — which can be explained geometrically — is summarized as follows:
1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp).
2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪.
3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q.
Then R = P + Q = (xR, yR), where
xR = λ^2 - xP - xQ
yR = λ·(xP - xR) - yP,
with
λ = (yP - yQ) / (xP - xQ) if P ≠ Q,
(3·xP·xP + a) / 2·yP if P = Q (point doubling).
Remark: there already is a task page requesting “a simplified (without modular arithmetic)
version of the elliptic curve arithmetic”.
Here we do add modulo operations. If also the domain is changed from reals to rationals,
the elliptic curves are no longer continuous but break up into a finite number of distinct points.
In that form we use them to implement ECDSA:
Elliptic curve digital signature algorithm.
A digital signature is the electronic analogue of a hand-written signature
that convinces the recipient that a message has been sent intact by the presumed sender.
Anyone with access to the public key of the signer may verify this signature.
Changing even a single bit of a signed message will cause the verification procedure to fail.
ECDSA key generation. Party A does the following:
1. Select an elliptic curve E defined over ℤp.
The number of points in E(ℤp) should be divisible by a large prime r.
2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪).
3. Select a random integer s in the interval [1, r - 1].
4. Compute W = sG.
The public key is (E, G, r, W), the private key is s.
ECDSA signature computation. To sign a message m, A does the following:
1. Compute message representative f = H(m), using a
cryptographic hash function.
Note that f can be greater than r but not longer (measuring bits).
2. Select a random integer u in the interval [1, r - 1].
3. Compute V = uG = (xV, yV) and c ≡ xV mod r (goto (2) if c = 0).
4. Compute d ≡ u^-1·(f + s·c) mod r (goto (2) if d = 0).
The signature for the message m is the pair of integers (c, d).
ECDSA signature verification. To verify A's signature, B should do the following:
1. Obtain an authentic copy of A's public key (E, G, r, W).
Verify that c and d are integers in the interval [1, r - 1].
2. Compute f = H(m) and h ≡ d^-1 mod r.
3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r.
4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r.
Accept the signature if and only if c1 = c.
To be cryptographically useful, the parameter r should have at least 250 bits.
The basis for the security of elliptic curve cryptosystems
is the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size:
given two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G,
determine an integer k such that W = kG and 0 ≤ k < r.
Task.
The task is to write a toy version of the ECDSA, quasi the equal of a real-world
implementation, but utilizing parameters that fit into standard arithmetic types.
To keep things simple there's no need for key export or a hash function (just a sample
hash value and a way to tamper with it). The program should be lenient where possible
(for example: if it accepts a composite modulus N it will either function as expected,
or demonstrate the principle of elliptic curve factorization)
— but strict where required (a point G that is not on E will always cause failure).
Toy ECDSA is of course completely useless for its cryptographic purpose.
If this bothers you, please add a multiple-precision version.
Reference.
Elliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see:
7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.)
7.1 The EC setting
7.1.2 EC domain parameters
7.1.3 EC key pairs
7.2 Primitives
7.2.7 ECSP-DSA (p. 35)
7.2.8 ECVP-DSA (p. 36)
Annex A. Number-theoretic background
A.9 Elliptic curves: overview (p. 115)
A.10 Elliptic curves: algorithms (p. 121)
| #Nim | Nim | import math, random, strformat
const
MaxN = 1073741789 # Maximum modulus.
MaxR = MaxN + 65536 # Maximum order "g".
Infinity = int64.high # Symbolic infinity.
type
Point = tuple[x, y: int64]
Curve = object
a, b: int64
n: int64
g: Point
r: int64
Pair = tuple[a, b: int64]
Parameters = tuple[a, b, n, gx, gy, r: int]
const ZerO: Point = (Infinity, 0i64)
type
InversionError = object of ValueError
InvalidParamError = object of ValueError
template `%`(a, n: int64): int64 =
## To simplify the writing.
floorMod(a, n)
proc exgcd(v, u: int64): int64 =
## Return 1/v mod u.
var u = u
var v = v
if v < 0: v += u
var r = 0i64
var s = 1i64
while v != 0:
let q = u div v
u = u mod v
swap u, v
r -= q * s
swap r, s
if u != 1:
raise newException(InversionError, "impossible inverse mod N, gcd = " & $u)
result = r
func discr(e: Curve): int64 =
## Return the discriminant of "e".
let c = e.a * e.a % e.n * e.a % e.n * 4
result = -16 * (e.b * e.b % e.n * 27 + c) % e.n
func isO(p: Point): bool =
## Return true if "p" is zero.
p.x == Infinity and p.y == 0
func isOn(e: Curve; p: Point): bool =
## Return true if "p" is on curve "e".
if p.isO: return true
let r = ((e.a + p.x * p.x) % e.n * p.x + e.b) % e.n
let s = p.y * p.y % e.n
result = r == s
proc add(e: Curve; p, q: Point): Point =
## Full Point addition.
if p.isO: return q
if q.isO: return p
var la: int64
if p.x != q.x:
la = (p.y - q.y) * exgcd(p.x - q.x, e.n) % e.n
elif p.y == q.y and p.y != 0:
la = (p.x * p.x % e.n * 3 + e.a) % e.n * exgcd(2 * p.y, e.n) % e.n
else:
return ZerO
result.x = (la * la - p.x - q.x) % e.n
result.y = (la * (p.x - result.x) - p.y) % e.n
proc mul(e: Curve; p: Point; k: int64): Point =
## Return "kp".
var q = p
var k = k
result = ZerO
while k != 0:
if (k and 1) != 0:
result = e.add(result, q)
q = e.add(q, q)
k = k shr 1
proc print(e: Curve; prefix: string; p: Point) =
## Print a point with a prefix.
var y = p.y
if p.isO:
echo prefix, " (0)"
else:
if y > e.n - y: y -= e.n
echo prefix, &" ({p.x}, {y})"
proc initCurve(params: Parameters): Curve =
## Initialize the curve.
result.n = params.n
if result.n notin 5..MaxN:
raise newException(ValueError, "invalid value for N: " & $result.n)
result.a = params.a.int64 % result.n
result.b = params.b.int64 % result.n
result.g.x = params.gx.int64 % result.n
result.g.y = params.gy.int64 % result.n
result.r = params.r
if result.r notin 5..MaxR:
raise newException(ValueError, "invalid value for r: " & $result.r)
echo &"\nE: y^2 = x^3 + {result.a}x + {result.b} (mod {result.n})"
result.print("base point G", result.g)
echo &"order(G, E) = {result.r}"
proc rnd(): float =
## Return a pseudorandom number in range [0..1[.
while true:
result = rand(1.0)
if result != 1: break
proc signature(e: Curve; s, f: int64): Pair =
## Compute the signature.
var
c, d = 0i64
u: int64
v: Point
echo "Signature computation"
while true:
while true:
u = 1 + int64(rnd() * float(e.r - 1))
v = e.mul(e.g, u)
c = v.x % e.r
if c != 0: break
d = exgcd(u, e.r) * (f + s * c % e.r) % e.r
if d != 0: break
echo "one-time u = ", u
e.print("V = uG", v)
result = (c, d)
proc verify(e: Curve; w: Point; f: int64; sg: Pair): bool =
## Verify a signature.
# Domain check.
if sg.a notin 1..<e.r or sg.b notin 1..<e.r:
return false
echo "\nsignature verification"
let h = exgcd(sg.b, e.r)
let h1 = f * h % e.r
let h2 = sg.a * h % e.r
echo &"h1, h2 = {h1}, {h2}"
var v = e.mul(e.g, h1)
let v2 = e.mul(w, h2)
e.print("h1G", v)
e.print("h2W", v2)
v = e.add(v, v2)
e.print("+ =", v)
if v.isO: return false
let c1 = v.x % e.r
echo "c’ = ", c1
result = c1 == sg.a
proc ecdsa(e: Curve; f: int64; d: int) =
## Build digital signature for message hash "f" with error bit "d".
# Parameter check.
var w = e.mul(e.g, e.r)
if e.discr() == 0 or e.g.isO or not w.isO or not e.isOn(e.g):
raise newException(InvalidParamError, "invalid parameter set")
echo "\nkey generation"
let s = 1 + int64(rnd() * float(e.r - 1))
w = e.mul(e.g, s)
echo "private key s = ", s
e.print("public key W = sG", w)
# Find next highest power of two minus one.
var t = e.r
var i = 1
while i < 64:
t = t or t shr i
i = i shl 1
var f = f
while f > t: f = f shr 1
echo &"\naligned hash {f:x}"
let sg = e.signature(s, f)
echo &"signature c, d = {sg.a}, {sg.b}"
var d = d
if d > 0:
while d > t: d = d shr 1
f = f xor d
echo &"\ncorrupted hash {f:x}"
echo if e.verify(w, f, sg): "Valid" else: "Invalid"
when isMainModule:
randomize()
# Test vectors: elliptic curve domain parameters,
# short Weierstrass model y^2 = x^3 + ax + b (mod N)
const Sets = [
# a, b, modulus N, base point G, order(G, E), cofactor
(355, 671, 1073741789, 13693, 10088, 1073807281),
( 0, 7, 67096021, 6580, 779, 16769911),
( -3, 1, 877073, 0, 1, 878159),
( 0, 14, 22651, 63, 30, 151),
( 3, 2, 5, 2, 1, 5),
# ECDSA may fail if...
# the base point is of composite order
( 0, 7, 67096021, 2402, 6067, 33539822),
# the given order is of composite order
( 0, 7, 67096021, 6580, 779, 67079644),
# the modulus is not prime (deceptive example)
( 0, 7, 877069, 3, 97123, 877069),
# fails if the modulus divides the discriminant
( 39, 387, 22651, 95, 27, 22651)
]
# Digital signature on message hash f,
# set d > 0 to simulate corrupted data.
let f = 0x789abcdei64
let d = 0
for s in Sets:
let e = initCurve(s)
try:
e.ecdsa(f, d)
except ValueError:
echo getCurrentExceptionMsg()
echo "——————————————" |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #BaCon | BaCon | FUNCTION check$(dir$)
IF FILEEXISTS(dir$) THEN
RETURN IIF$(LEN(WALK$(dir$, 127, ".+", FALSE)), " is NOT empty.", " is empty." )
ELSE
RETURN " doesn't exist."
ENDIF
ENDFUNCTION
dir$ = "bla"
PRINT "Directory '", dir$, "'", check$(dir$)
dir$ = "/mnt"
PRINT "Directory '", dir$, "'", check$(dir$)
dir$ = "."
PRINT "Directory '", dir$, "'", check$(dir$) |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #Batch_File | Batch File | @echo off
if "%~1"=="" exit /b 3
set "samp_path=%~1"
set "tst_var="
%== Store the current directory of the CMD ==%
for /f %%T in ('cd') do set curr_dir=%%T
%== Go to the samp_path ==%
cd %samp_path% 2>nul ||goto :folder_not_found
%== The current directory is now samp_path ==%
%== Scan what is inside samp_path ==%
for /f "usebackq delims=" %%D in (
`dir /b 2^>nul ^& dir /b /ah 2^>nul`
) do set "tst_var=1"
if "%tst_var%"=="1" (
echo "%samp_path%" is NOT empty.
cd %curr_dir%
exit /b 1
) else (
echo "%samp_path%" is empty.
cd %curr_dir%
exit /b 0
)
:folder_not_found
echo Folder not found.
exit /b 2 |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #8086_Assembly | 8086 Assembly | .model small ;.exe file
.stack 1024 ;this value doesn't matter, I chose this arbitrarily
.data
;not needed in an empty program
.code
mov ax,4C00h
int 21h ;exit this program and return to MS-DOS |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #AArch64_Assembly | AArch64 Assembly | .text
.global _start
_start:
mov x0, #0
mov x8, #93
svc #0 |
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.
| #Java | Java | final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6; //this is fine
immutableInt = 6; //this is an error |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #JavaScript | JavaScript | const pi = 3.1415;
const msg = "Hello World"; |
http://rosettacode.org/wiki/Enforced_immutability | Enforced immutability | Task
Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
| #jq | jq |
["a", "b"] as $a | $a[0] = 1 as $b | $a |
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.
| #Julia | Julia | const x = 1
x = π # ERROR: invalid ridefinition of constant x |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #BQN | BQN | H ← -∘(+´⊢×2⋆⁼⊢)∘((+˝⊢=⌜⍷)÷≠)
H "1223334444" |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #Burlesque | Burlesque | blsq ) "1223334444"F:u[vv^^{1\/?/2\/LG}m[?*++
1.8464393446710157 |
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
| #BQN | BQN | Double ← 2⊸×
Halve ← ⌊÷⟜2
Odd ← 2⊸|
EMul ← {
times ← ↕⌈2⋆⁼𝕨
+´(Odd Halve⍟times 𝕨)/Double⍟times 𝕩
}
17 EMul 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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub equilibriumIndices (a() As Integer, b() As Integer)
If UBound(a) = -1 Then Return '' empty array
Dim sum As Integer = 0
Dim count As Integer = 0
For i As Integer = LBound(a) To UBound(a) : sum += a(i) : Next
Dim sumLeft As Integer = 0, sumRight As Integer = 0
For i As Integer = LBound(a) To UBound(a)
sumRight = sum - sumLeft - a(i)
If sumLeft = sumRight Then
Redim Preserve b(0 To Count)
b(count) = i
count += 1
End If
sumLeft += a(i)
Next
End Sub
Dim a(0 To 6) As Integer = { -7, 1, 5, 2, -4, 3, 0 }
Dim b() As Integer
equilibriumIndices a(), b()
If UBound(b) = -1 Then
Print "There are no equilibrium indices"
ElseIf UBound(b) = LBound(b) Then
Print "The only equilibrium index is : "; b(LBound(b))
Else
Print "The equilibrium indices are : "
For i As Integer = LBound(b) To UBound(b) : Print b(i); " "; : Next
End If
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #jq | jq | env.HOME |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #jsish | jsish | /* Environment variables, in Jsi */
puts(Util.getenv("HOME"));
var environment = Util.getenv();
puts(environment.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
| #Julia | Julia | @show ENV["PATH"]
@show ENV["HOME"]
@show ENV["USER"] |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #K | K | _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
| #REXX | REXX | /*REXX pgm lists a bunch of esthetic numbers in bases 2 ──► 16, & base 10 in two ranges.*/
parse arg baseL baseH range /*obtain optional arguments from the CL*/
if baseL=='' | baseL=="," then baseL= 2 /*Not specified? Then use the default.*/
if baseH=='' | baseH=="," then baseH=16 /* " " " " " " */
if range=='' | range=="," then range=1000..9999 /* " " " " " " */
do radix=baseL to baseH; #= 0; if radix<2 then iterate /*process the bases. */
start= radix * 4; stop = radix * 6
$=; do i=1 until #==stop; y= base(i, radix) /*convert I to base Y*/
if \esthetic(y, radix) then iterate /*not esthetic? Skip*/
#= # + 1; if #<start then iterate /*is # below range?*/
$= $ y /*append # to $ list.*/
end /*i*/
say
say center(' base ' radix", the" th(start) '──►' th(stop) ,
"esthetic numbers ", max(80, length($) - 1), '─')
say strip($)
end /*radix*/
say; g= 25
parse var range start '..' stop
say center(' base 10 esthetic numbers between' start "and" stop '(inclusive) ', g*5-1,"─")
#= 0; $=
do k=start to stop; if \esthetic(k, 10) then iterate; #= # + 1; $= $ k
if #//g==0 then do; say strip($); $=; end
end /*k*/
say strip($); say; say # ' esthetic numbers listed.'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
PorA: _= pos(z, @u); p= substr(@u, _-1, 1); a= substr(@u, _+1, 1); return
th: parse arg th; return th || word('th st nd rd', 1+(th//10)*(th//100%10\==1)*(th//10<4))
vv: parse arg v,_; vr= x2d(v) + _; if vr==-1 then vr= r; return d2x(vr)
/*──────────────────────────────────────────────────────────────────────────────────────*/
base: procedure expose @u; arg x 1 #,toB,inB,,y /*Y is assigned a "null" value. */
if tob=='' then tob= 10 /*maybe assign a default for TObase. */
if inb=='' then inb= 10 /* " " " " " INbase. */
@l= '0123456789abcdef'; @u= @l; upper @u /*two versions of hexadecimal digits. */
if inB\==10 then do; #= 0 /*only convert if not base 10. */
do j=1 for length(x) /*convert X: base inB ──► base 10. */
#= # * inB + pos(substr(x, j, 1), @u) -1 /*build new number.*/
end /*j*/ /* [↑] this also verifies digits. */
end
if toB==10 then return # /*if TOB is ten, then simply return #.*/
do while # >= toB /*convert #: base 10 ──► base toB.*/
y= substr(@l, (# // toB) + 1, 1)y /*construct the output number. */
#= # % toB /* ··· and whittle # down also. */
end /*while*/ /* [↑] algorithm may leave a residual.*/
return substr(@l, # + 1, 1)y /*prepend the residual, if any. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
esthetic: procedure expose @u; arg x,r; L= length(x); if L==1 then return 1
if x<2 then return 0
do d=0 to r-1; _= d2x(d); if pos(_ || _, x)\==0 then return 0
end /*d*/ /* [↑] check for a duplicated digits. */
do j=1 for L; @.j= substr(x, j, 1) /*assign (base) digits to stemmed array*/
end /*j*/
if L==2 then do; z= @.1; call PorA; if @.2==p | @.2==a then nop
else return 0
end
do e=2 to L-1; z= @.e; pe= e - 1; ae= e + 1
if (z==vv(@.pe,-1)|z==vv(@.pe,1))&(z==vv(@.ae,-1)|z==vv(@.ae,1)) then iterate
return 0
end /*e*/; return 1 |
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.
| #F.23 | F# |
//Find 4 integers whose 5th powers sum to the fifth power of an integer (Quickly!) - Nigel Galloway: April 23rd., 2015
let G =
let GN = Array.init<float> 250 (fun n -> (float n)**5.0)
let rec gng (n, i, g, e) =
match (n, i, g, e) with
| (250,_,_,_) -> "No Solution Found"
| (_,250,_,_) -> gng (n+1, n+1, n+1, n+1)
| (_,_,250,_) -> gng (n, i+1, i+1, i+1)
| (_,_,_,250) -> gng (n, i, g+1, g+1)
| _ -> let l = GN.[n] + GN.[i] + GN.[g] + GN.[e]
match l with
| _ when l > GN.[249] -> gng(n,i,g+1,g+1)
| _ when l = round(l**0.2)**5.0 -> sprintf "%d**5 + %d**5 + %d**5 + %d**5 = %d**5" n i g e (int (l**0.2))
| _ -> gng(n,i,g,e+1)
gng (1, 1, 1, 1)
|
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
numeric digits 64 -- switch to exponential format when numbers become larger than 64 digits
say 'Input a number: \-'
say
do
n_ = long ask -- Gets the number, must be an integer
say n_'! =' factorial(n_) '(using iteration)'
say n_'! =' factorial(n_, 'r') '(using recursion)'
catch ex = Exception
ex.printStackTrace
end
return
method factorial(n_ = long, fmethod = 'I') public static returns Rexx signals IllegalArgumentException
if n_ < 0 then -
signal IllegalArgumentException('Sorry, but' n_ 'is not a positive integer')
select
when fmethod.upper = 'R' then -
fact = factorialRecursive(n_)
otherwise -
fact = factorialIterative(n_)
end
return fact
method factorialIterative(n_ = long) private static returns Rexx
fact = 1
loop i_ = 1 to n_
fact = fact * i_
end i_
return fact
method factorialRecursive(n_ = long) private static returns Rexx
if n_ > 1 then -
fact = n_ * factorialRecursive(n_ - 1)
else -
fact = 1
return fact |
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.
| #Burlesque | Burlesque | 2.% |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f
(
t
,
y
(
t
)
)
{\displaystyle {\frac {dy(t)}{dt}}=f(t,y(t))}
with an initial value
y
(
t
0
)
=
y
0
{\displaystyle y(t_{0})=y_{0}}
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
d
y
(
t
)
d
t
≈
y
(
t
+
h
)
−
y
(
t
)
h
{\displaystyle {\frac {dy(t)}{dt}}\approx {\frac {y(t+h)-y(t)}{h}}}
then solve for
y
(
t
+
h
)
{\displaystyle y(t+h)}
:
y
(
t
+
h
)
≈
y
(
t
)
+
h
d
y
(
t
)
d
t
{\displaystyle y(t+h)\approx y(t)+h\,{\frac {dy(t)}{dt}}}
which is the same as
y
(
t
+
h
)
≈
y
(
t
)
+
h
f
(
t
,
y
(
t
)
)
{\displaystyle y(t+h)\approx y(t)+h\,f(t,y(t))}
The iterative solution rule is then:
y
n
+
1
=
y
n
+
h
f
(
t
n
,
y
n
)
{\displaystyle y_{n+1}=y_{n}+h\,f(t_{n},y_{n})}
where
h
{\displaystyle h}
is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
Example: Newton's Cooling Law
Newton's cooling law describes how an object of initial temperature
T
(
t
0
)
=
T
0
{\displaystyle T(t_{0})=T_{0}}
cools down in an environment of temperature
T
R
{\displaystyle T_{R}}
:
d
T
(
t
)
d
t
=
−
k
Δ
T
{\displaystyle {\frac {dT(t)}{dt}}=-k\,\Delta T}
or
d
T
(
t
)
d
t
=
−
k
(
T
(
t
)
−
T
R
)
{\displaystyle {\frac {dT(t)}{dt}}=-k\,(T(t)-T_{R})}
It says that the cooling rate
d
T
(
t
)
d
t
{\displaystyle {\frac {dT(t)}{dt}}}
of the object is proportional to the current temperature difference
Δ
T
=
(
T
(
t
)
−
T
R
)
{\displaystyle \Delta T=(T(t)-T_{R})}
to the surrounding environment.
The analytical solution, which we will compare to the numerical approximation, is
T
(
t
)
=
T
R
+
(
T
0
−
T
R
)
e
−
k
t
{\displaystyle T(t)=T_{R}+(T_{0}-T_{R})\;e^{-kt}}
Task
Implement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:
2 s
5 s and
10 s
and to compare with the analytical solution.
Initial values
initial temperature
T
0
{\displaystyle T_{0}}
shall be 100 °C
room temperature
T
R
{\displaystyle T_{R}}
shall be 20 °C
cooling constant
k
{\displaystyle k}
shall be 0.07
time interval to calculate shall be from 0 s ──► 100 s
A reference solution (Common Lisp) can be seen below. We see that bigger step sizes lead to reduced approximation accuracy.
| #PureBasic | PureBasic | Define.d
Prototype.d Func(Time, t)
Procedure.d Euler(*F.Func, y0, a, b, h)
Protected y=y0, t=a
While t<=b
PrintN(RSet(StrF(t,3),7)+" "+RSet(StrF(y,3),7))
y + h * *F(t,y)
t + h
Wend
EndProcedure
Procedure.d newtonCoolingLaw(Time, t)
ProcedureReturn -0.07*(t-20)
EndProcedure
If OpenConsole()
Euler(@newtonCoolingLaw(), 100, 0, 100, 2)
Euler(@newtonCoolingLaw(), 100, 0, 100, 5)
Euler(@newtonCoolingLaw(), 100, 0, 100,10)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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
| #Haskell | Haskell |
choose :: (Integral a) => a -> a -> a
choose n k = product [k+1..n] `div` product [1..n-k]
|
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
| #HicEst | HicEst | WRITE(Messagebox) BinomCoeff( 5, 3) ! displays 10
FUNCTION factorial( n )
factorial = 1
DO i = 1, n
factorial = factorial * i
ENDDO
END
FUNCTION BinomCoeff( n, k )
BinomCoeff = factorial(n)/factorial(n-k)/factorial(k)
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
| #XQuery | XQuery | declare function local:fib($n as xs:integer) as xs:integer {
if($n < 2)
then $n
else local:fib($n - 1) + local:fib($n - 2)
}; |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbers should be in order.
Invoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.
The specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.
See also
Wikipedia, Emirp.
The Prime Pages, emirp.
Wolfram MathWorld™, Emirp.
The On‑Line Encyclopedia of Integer Sequences, emirps (A6567).
| #Ada | Ada | with Ada.Text_IO, Miller_Rabin;
procedure Emirp_Gen is
type Num is range 0 .. 2**63-1; -- maximum for the gnat Ada compiler
MR_Iterations: constant Positive := 25;
-- the probability Pr[Is_Prime(N, MR_Iterations) = Probably_Prime]
-- is 1 for prime N and < 4**(-MR_Iterations) for composed N
function Is_Emirp(E: Num) return Boolean is
package MR is new Miller_Rabin(Num); use MR;
function Rev(E: Num) return Num is
N: Num := E;
R: Num := 0;
begin
while N > 0 loop
R := 10*R + N mod 10; -- N mod 10 is least significant digit of N
N := N / 10; -- delete least significant digit of N
end loop;
return R;
end Rev;
R: Num := Rev(E);
begin
return E /= R and then
(Is_Prime(E, MR_Iterations) = Probably_Prime) and then
(Is_Prime(R, MR_Iterations) = Probably_Prime);
end Is_Emirp;
function Next(P: Num) return Num is
N: Num := P+1;
begin
while not (Is_Emirp(N)) Loop
N := N + 1;
end loop;
return N;
end Next;
Current: Num;
Count: Num := 0;
begin
-- show the first twenty emirps
Ada.Text_IO.Put("First 20 emirps:");
Current := 1;
for I in 1 .. 20 loop
Current := Next(Current);
Ada.Text_IO.Put(Num'Image(Current));
end loop;
Ada.Text_IO.New_Line;
-- show the emirps between 7700 and 8000
Ada.Text_IO.Put("Emirps between 7700 and 8000:");
Current := 7699;
loop
Current := Next(Current);
exit when Current > 8000;
Ada.Text_IO.Put(Num'Image(Current));
end loop;
-- the 10_000th emirp
Ada.Text_IO.Put("The 10_000'th emirp:");
for I in 1 .. 10_000 loop
Current := Next(Current);
end loop;
Ada.Text_IO.Put_Line(Num'Image(Current));
end Emirp_Gen; |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the x and y coordinates of any point on the curve:
y
2
=
x
3
+
a
x
+
b
{\displaystyle y^{2}=x^{3}+ax+b}
a and b are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation +, such that for any three distinct points P, Q and R on the curve, whenever these points are aligned, we have:
P + Q + R = 0
Here 0 (zero) is the infinity point, for which the x and y values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points P, Q and R, we define the sum S = P + Q as the point (possibly the infinity point) such that S, R and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points S and R can be aligned with the infinity point if and only if S and R are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
S is thus defined as the symmetric of R towards the x axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the a and b parameters of secp256k1, i.e. respectively zero and seven.
Hint: You might need to define a "doubling" function, that returns P+P for any given point P.
Extra credit: define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point P and integer n, the point P + P + ... + P (n times).
| #D | D | import std.stdio, std.math, std.string;
enum bCoeff = 7;
struct Pt {
double x, y;
@property static Pt zero() pure nothrow @nogc @safe {
return Pt(double.infinity, double.infinity);
}
@property bool isZero() const pure nothrow @nogc @safe {
return x > 1e20 || x < -1e20;
}
@property static Pt fromY(in double y) nothrow /*pure*/ @nogc @safe {
return Pt(cbrt(y ^^ 2 - bCoeff), y);
}
@property Pt dbl() const pure nothrow @nogc @safe {
if (this.isZero)
return this;
immutable L = (3 * x * x) / (2 * y);
immutable x2 = L ^^ 2 - 2 * x;
return Pt(x2, L * (x - x2) - y);
}
string toString() const pure /*nothrow*/ @safe {
if (this.isZero)
return "Zero";
else
return format("(%.3f, %.3f)", this.tupleof);
}
Pt opUnary(string op)() const pure nothrow @nogc @safe
if (op == "-") {
return Pt(this.x, -this.y);
}
Pt opBinary(string op)(in Pt q) const pure nothrow @nogc @safe
if (op == "+") {
if (this.x == q.x && this.y == q.y)
return this.dbl;
if (this.isZero)
return q;
if (q.isZero)
return this;
immutable L = (q.y - this.y) / (q.x - this.x);
immutable x = L ^^ 2 - this.x - q.x;
return Pt(x, L * (this.x - x) - this.y);
}
Pt opBinary(string op)(in uint n) const pure nothrow @nogc @safe
if (op == "*") {
auto r = Pt.zero;
Pt p = this;
for (uint i = 1; i <= n; i <<= 1) {
if ((i & n) != 0)
r = r + p;
p = p.dbl;
}
return r;
}
}
void main() @safe {
immutable a = Pt.fromY(1);
immutable b = Pt.fromY(2);
writeln("a = ", a);
writeln("b = ", b);
immutable c = a + b;
writeln("c = a + b = ", c);
immutable d = -c;
writeln("d = -c = ", d);
writeln("c + d = ", c + d);
writeln("a + b + d = ", a + b + d);
writeln("a * 12345 = ", a * 12345);
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #FutureBasic | FutureBasic | window 1, @"Enumerations", (0,0,480,270)
begin enum 1
_apple
_banana
_cherry
end enum
begin enum
_appleExplicit = 10
_bananaExplicit = 15
_cherryExplicit = 30
end enum
print "_apple = "; _apple
print "_banana = "; _banana
print "_cherry = "; _cherry
print
print "_appleExplicit = "; _appleExplicit
print "_bananaExplicit = "; _bananaExplicit
print "_cherryExplicit = "; _cherryExplicit
HandleEvents |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Go | Go | const (
apple = iota
banana
cherry
) |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Groovy | Groovy | enum Fruit { apple, banana, cherry }
enum ValuedFruit {
apple(1), banana(2), cherry(3);
def value
ValuedFruit(val) {value = val}
String toString() { super.toString() + "(${value})" }
}
println Fruit.values()
println ValuedFruit.values() |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.
The purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant.
You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.
For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.
Reference
Cellular automata: Is Rule 30 random? (PDF).
| #D | D | import std.stdio, std.range, std.typecons;
struct CellularRNG {
private uint current;
private immutable uint rule;
private ulong state;
this(in ulong state_, in uint rule_) pure nothrow @safe @nogc {
this.state = state_;
this.rule = rule_;
popFront;
}
public enum bool empty = false;
@property uint front() pure nothrow @safe @nogc { return current; }
void popFront() pure nothrow @safe @nogc {
enum uint nBit = 8;
enum uint NU = ulong.sizeof * nBit;
current = 0;
foreach_reverse (immutable i; 0 .. nBit) {
immutable state2 = state;
current |= (state2 & 1) << i;
state = 0;
/*static*/ foreach (immutable j; staticIota!(0, NU)) {
// To avoid undefined behavior with out-of-range shifts.
static if (j > 0)
immutable aux1 = state2 >> (j - 1);
else
immutable aux1 = state2 >> 63;
static if (j == 0)
immutable aux2 = state2 << 1;
else static if (j == 1)
immutable aux2 = state2 << 63;
else
immutable aux2 = state2 << (NU + 1 - j);
immutable aux = 7 & (aux1 | aux2);
if (rule & (1UL << aux))
state |= 1UL << j;
}
}
}
}
void main() {
CellularRNG(1, 30).take(10).writeln;
CellularRNG(1, 30).drop(2_000_000).front.writeln;
} |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | procedure Empty_String is
function Is_Empty(S: String) return Boolean is
begin
return S = ""; -- test that S is empty
end Is_Empty;
Empty: String := ""; -- Assign empty string
XXXXX: String := "Not Empty";
begin
if (not Is_Empty(Empty)) or Is_Empty(XXXXX) then
raise Program_Error with "something went wrong very very badly!!!";
end if;
end Empty_String; |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Aime | Aime | text s;
s = "";
if (length(s) == 0) {
...
}
if (length(s) != 0) {
....
} |
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining equation, together with 𝒪.
There is a rule for adding two points on an elliptic curve to give a third point.
This addition operation and the set of points E(ℤp) form a group with identity 𝒪.
It is this group that is used in the construction of elliptic curve cryptosystems.
The addition rule — which can be explained geometrically — is summarized as follows:
1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp).
2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪.
3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q.
Then R = P + Q = (xR, yR), where
xR = λ^2 - xP - xQ
yR = λ·(xP - xR) - yP,
with
λ = (yP - yQ) / (xP - xQ) if P ≠ Q,
(3·xP·xP + a) / 2·yP if P = Q (point doubling).
Remark: there already is a task page requesting “a simplified (without modular arithmetic)
version of the elliptic curve arithmetic”.
Here we do add modulo operations. If also the domain is changed from reals to rationals,
the elliptic curves are no longer continuous but break up into a finite number of distinct points.
In that form we use them to implement ECDSA:
Elliptic curve digital signature algorithm.
A digital signature is the electronic analogue of a hand-written signature
that convinces the recipient that a message has been sent intact by the presumed sender.
Anyone with access to the public key of the signer may verify this signature.
Changing even a single bit of a signed message will cause the verification procedure to fail.
ECDSA key generation. Party A does the following:
1. Select an elliptic curve E defined over ℤp.
The number of points in E(ℤp) should be divisible by a large prime r.
2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪).
3. Select a random integer s in the interval [1, r - 1].
4. Compute W = sG.
The public key is (E, G, r, W), the private key is s.
ECDSA signature computation. To sign a message m, A does the following:
1. Compute message representative f = H(m), using a
cryptographic hash function.
Note that f can be greater than r but not longer (measuring bits).
2. Select a random integer u in the interval [1, r - 1].
3. Compute V = uG = (xV, yV) and c ≡ xV mod r (goto (2) if c = 0).
4. Compute d ≡ u^-1·(f + s·c) mod r (goto (2) if d = 0).
The signature for the message m is the pair of integers (c, d).
ECDSA signature verification. To verify A's signature, B should do the following:
1. Obtain an authentic copy of A's public key (E, G, r, W).
Verify that c and d are integers in the interval [1, r - 1].
2. Compute f = H(m) and h ≡ d^-1 mod r.
3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r.
4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r.
Accept the signature if and only if c1 = c.
To be cryptographically useful, the parameter r should have at least 250 bits.
The basis for the security of elliptic curve cryptosystems
is the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size:
given two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G,
determine an integer k such that W = kG and 0 ≤ k < r.
Task.
The task is to write a toy version of the ECDSA, quasi the equal of a real-world
implementation, but utilizing parameters that fit into standard arithmetic types.
To keep things simple there's no need for key export or a hash function (just a sample
hash value and a way to tamper with it). The program should be lenient where possible
(for example: if it accepts a composite modulus N it will either function as expected,
or demonstrate the principle of elliptic curve factorization)
— but strict where required (a point G that is not on E will always cause failure).
Toy ECDSA is of course completely useless for its cryptographic purpose.
If this bothers you, please add a multiple-precision version.
Reference.
Elliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see:
7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.)
7.1 The EC setting
7.1.2 EC domain parameters
7.1.3 EC key pairs
7.2 Primitives
7.2.7 ECSP-DSA (p. 35)
7.2.8 ECVP-DSA (p. 36)
Annex A. Number-theoretic background
A.9 Elliptic curves: overview (p. 115)
A.10 Elliptic curves: algorithms (p. 121)
| #Perl | Perl | # 20200828 added Perl programming solution
use strict;
use warnings;
use Crypt::EC_DSA;
my $ecdsa = new Crypt::EC_DSA;
my ($pubkey, $prikey) = $ecdsa->keygen;
print "Message: ", my $msg = 'Rosetta Code', "\n";
print "Private Key :\n$prikey \n";
print "Public key :\n", $pubkey->x, "\n", $pubkey->y, "\n";
my $signature = $ecdsa->sign( Message => $msg, Key => $prikey );
print "Signature :\n";
for (sort keys %$signature) { print "$_ => $signature->{$_}\n"; }
$ecdsa->verify( Message => $msg, Key => $pubkey, Signature => $signature ) and
print "Signature verified.\n" |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #BBC_BASIC | BBC BASIC | IF FNisdirectoryempty("C:\") PRINT "C:\ is empty" ELSE PRINT "C:\ is not empty"
IF FNisdirectoryempty("C:\temp") PRINT "C:\temp is empty" ELSE PRINT "C:\temp is not empty"
END
DEF FNisdirectoryempty(dir$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
IF RIGHT$(dir$)<>"\" dir$ += "\"
SYS "FindFirstFile", dir$+"*", dir% TO sh%
IF sh% = -1 ERROR 100, "Directory doesn't exist"
res% = 1
REPEAT
IF $$(dir%+44)<>"." IF $$(dir%+44)<>".." EXIT REPEAT
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% == 0
SYS "FindClose", sh%
= (res% == 0) |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries.
| #C | C | #include <stdio.h>
#include <dirent.h>
#include <string.h>
int dir_empty(const char *path)
{
struct dirent *ent;
int ret = 1;
DIR *d = opendir(path);
if (!d) {
fprintf(stderr, "%s: ", path);
perror("");
return -1;
}
while ((ent = readdir(d))) {
if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, "..")))
continue;
ret = 0;
break;
}
closedir(d);
return ret;
}
int main(int c, char **v)
{
int ret = 0, i;
if (c < 2) return -1;
for (i = 1; i < c; i++) {
ret = dir_empty(v[i]);
if (ret >= 0)
printf("%s: %sempty\n", v[i], ret ? "" : "not ");
}
return 0;
} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #ABAP | ABAP |
report z_empty_program.
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Action.21 | Action! | |
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.
| #Kotlin | Kotlin | // version 1.1.0
// constant top level property
const val N = 5
// read-only top level property
val letters = listOf('A', 'B', 'C', 'D', 'E') // 'listOf' creates here a List<Char) which is immutable
class MyClass { // MyClass is effectively immutable because it's only property is read-only
// and it is not 'open' so cannot be sub-classed
// read-only class property
val myInt = 3
fun myFunc(p: Int) { // parameter 'p' is read-only
var pp = p // local variable 'pp' is mutable
while (pp < N) { // compiler will change 'N' to 5
print(letters[pp++])
}
println()
}
}
fun main(args: Array<String>) {
val mc = MyClass() // 'mc' cannot be re-assigned a different object
println(mc.myInt)
mc.myFunc(0)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.