task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Inform_7 | Inform 7 | X is a room |
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
| #PureBasic | PureBasic | #TESTSTR="1223334444"
NewMap uchar.i() : Define.d e
Procedure.d nlog2(x.d) : ProcedureReturn Log(x)/Log(2) : EndProcedure
Procedure countchar(s$, Map uchar())
If Len(s$)
uchar(Left(s$,1))=CountString(s$,Left(s$,1))
s$=RemoveString(s$,Left(s$,1))
ProcedureReturn countchar(s$, uchar())
EndIf
EndProcedure
countchar(#TESTSTR,uchar())
ForEach uchar()
e-uchar()/Len(#TESTSTR)*nlog2(uchar()/Len(#TESTSTR))
Next
OpenConsole()
Print("Entropy of ["+#TESTSTR+"] = "+StrD(e,15))
Input() |
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
| #Limbo | Limbo | implement Ethiopian;
include "sys.m";
sys: Sys;
print: import sys;
include "draw.m";
draw: Draw;
Ethiopian : module
{
init : fn(ctxt : ref Draw->Context, args : list of string);
};
init (ctxt: ref Draw->Context, args: list of string)
{
sys = load Sys Sys->PATH;
print("\n%d\n", ethiopian(17, 34, 0));
print("\n%d\n", ethiopian(99, 99, 1));
}
halve(n: int): int
{
return (n /2);
}
double(n: int): int
{
return (n * 2);
}
iseven(n: int): int
{
return ((n%2) == 0);
}
ethiopian(a: int, b: int, tutor: int): int
{
product := 0;
if (tutor)
print("\nmultiplying %d x %d", a, b);
while (a >= 1) {
if (!(iseven(a))) {
if (tutor)
print("\n%3d %d", a, b);
product += b;
} else
if (tutor)
print("\n%3d ----", a);
a = halve(a);
b = double(b);
}
return product;
}
|
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.
| #SenseTalk | SenseTalk | findEulerSumOfPowers
to findEulerSumOfPowers
set MAX_NUMBER to 250
set possibleValues to 1..MAX_NUMBER
set possible5thPowers to each item of possibleValues to the power of 5
repeat for x0 in 1..250
repeat for x1 in 1..x0
repeat for x2 in 1..x1
repeat for x3 in 1..x2
set possibleSum to item x0 of possible5thPowers \
plus item x1 of possible5thPowers \
plus item x2 of possible5thPowers \
plus item x3 of possible5thPowers
if possibleSum is in possible5thPowers
put x0 & "^5 + " & x1 & "^5 + " & x2 & "^5 + " & x3 & "^5 = " & the item number of possibleSum within possible5thPowers & "^5"
return
end if
end repeat
end repeat
end repeat
end repeat
end findEulerSumOfPowers |
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
| #Racket | Racket | (define (factorial n)
(if (= 0 n)
1
(* n (factorial (- n 1))))) |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Maple | Maple | EvenOrOdd := proc( x::integer )
if x mod 2 = 0 then
print("Even"):
else
print("Odd"):
end if:
end proc:
EvenOrOdd(9); |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | EvenQ[8] |
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).
| #Scheme | Scheme | ; Primality test by simple trial division.
(define prime?
(lambda (num)
(if (< num 2)
#f
(let loop ((div 2))
(cond ((> (* div div) num) #t)
((zero? (modulo num div)) #f)
(else (loop (1+ div))))))))
; Check if number is an emirp prime.
(define emirp?
(lambda (num)
(and (prime? num)
(let ((rev (string->number (list->string (reverse (string->list (number->string num)))))))
(and (not (= num rev)) (prime? rev))))))
(printf "The first 20 emirps:")
(do ((num 1 (1+ num)) (cnt 0))
((>= cnt 20))
(when (emirp? num)
(set! cnt (1+ cnt))
(printf " ~d" num)))
(newline)
(printf "All emirps between 7700 and 8000:")
(do ((num 7700 (1+ num)))
((>= num 8000))
(when (emirp? num)
(printf " ~d" num)))
(newline)
(printf "The 10000th emirp: ~d~%"
(do ((num 1 (1+ num)) (cnt 0))
((>= cnt 10000) (1- num))
(when (emirp? num) (set! cnt (1+ cnt))))) |
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
| #Lua | Lua |
-- create an empty string 3 different ways
str = ""
str = ''
str = [[]]
-- test for empty string
if str == "" then
print "The string is empty"
end
-- test for nonempty string
if str ~= "" then
print "The string is not empty"
end
-- several different ways to check the string's length
if string.len(str) == 0 then
print "The library function says the string is empty."
end
if str:len() == 0 then
print "The method call says the string is empty."
end
if #str == 0 then
print "The unary operator says the string is empty."
end
|
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #M2000_Interpreter | M2000 Interpreter |
A$=""
Print A$<>"", A$="", Len(A$)=0
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Intercal | Intercal | PLEASE GIVE UP |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Io | Io | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #J | J | '' |
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
| #Python | Python | from __future__ import division
import math
def hist(source):
hist = {}; l = 0;
for e in source:
l += 1
if e not in hist:
hist[e] = 0
hist[e] += 1
return (l,hist)
def entropy(hist,l):
elist = []
for v in hist.values():
c = v / l
elist.append(-c * math.log(c ,2))
return sum(elist)
def printHist(h):
flip = lambda (k,v) : (v,k)
h = sorted(h.iteritems(), key = flip)
print 'Sym\thi\tfi\tInf'
for (k,v) in h:
print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2))
source = "1223334444"
(l,h) = hist(source);
print '.[Results].'
print 'Length',l
print 'Entropy:', entropy(h, l)
printHist(h) |
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
| #Locomotive_Basic | Locomotive Basic | 10 DEF FNiseven(a)=(a+1) MOD 2
20 DEF FNhalf(a)=INT(a/2)
30 DEF FNdouble(a)=2*a
40 x=17:y=34:tot=0
50 WHILE x>=1
60 PRINT x,
70 IF FNiseven(x)=0 THEN tot=tot+y:PRINT y ELSE PRINT
80 x=FNhalf(x):y=FNdouble(y)
90 WEND
100 PRINT "=", tot |
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.
| #Sidef | Sidef | define range = (1 ..^ 250)
var p5 = Hash()
var sum2 = Hash()
for i in (range) {
p5{i**5} = i
for j in (range) {
sum2{i**5 + j**5} = [i, j]
}
}
var sk = sum2.keys.map{ Num(_) }.sort
for p in (p5.keys.map{ Num(_) }.sort) {
var s = sk.first {|s|
p > s && sum2.exists(p-s)
} \\ next
var t = (sum2{s} + sum2{p-s} -> map{|n| "#{n}⁵" }.join(' + '))
say "#{t} = #{p5{p}}⁵"
break
} |
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
| #Raku | Raku | sub postfix:<!> (Int $n) { [*] 2..$n }
say 5!; |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | isOdd = logical(bitand(N,1));
isEven = ~logical(bitand(N,1)); |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Maxima | Maxima | evenp(n);
oddp(n); |
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).
| #Sidef | Sidef | func forprimes(a, b, callback) {
for (var p = a.dec.next_prime; p <= b; p.next_prime!) {
callback(p)
}
}
func is_emirp(p) {
var str = Str(p)
var rev = str.reverse
(str != rev) && is_prime(Num(rev))
}
func emirp_list(count) {
var i = 13
var inc = (100 + 10*count)
var n = []
while (n.len < count) {
forprimes(i, i+inc - 1, {|p|
is_emirp(p) && (n << p)
})
(i, inc) = (i+inc, int(inc * 1.03) + 1000)
}
n.splice(count)
return n
}
say ("First 20: ", emirp_list(20).join(' '))
say ("Between 7700 and 8000: ", gather {
forprimes(7700, 8000, {|p| is_emirp(p) && take(p) })
}.join(' '))
say ("The 10,000'th emirp: ", emirp_list(10000)[-1]) |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Maple | Maple |
s := ""; # Create an empty string
evalb(s = ""); # test if the string is empty
evalb(s <> ""); # test if the string is not empty
|
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
str=""; (*Create*)
str==="" (*test empty*)
str=!="" (*test not empty*)
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Java | Java | public class EmptyApplet extends java.applet.Applet {
@Override public void init() {
}
} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #JavaScript | JavaScript | |
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
| #R | R | entropy = function(s)
{freq = prop.table(table(strsplit(s, '')[1]))
-sum(freq * log(freq, base = 2))}
print(entropy("1223334444")) # 1.846439 |
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
| #Racket | Racket | #lang racket
(require math)
(provide entropy hash-entropy list-entropy digital-entropy)
(define (hash-entropy h)
(define (log2 x) (/ (log x) (log 2)))
(define n (for/sum [(c (in-hash-values h))] c))
(- (for/sum ([c (in-hash-values h)] #:unless (zero? c))
(* (/ c n) (log2 (/ c n))))))
(define (list-entropy x) (hash-entropy (samples->hash x)))
(define entropy (compose list-entropy string->list))
(define digital-entropy (compose entropy number->string))
(module+ test
(require rackunit)
(check-= (entropy "1223334444") 1.8464393446710154 1E-8)
(check-= (digital-entropy 1223334444) (entropy "1223334444") 1E-8)
(check-= (digital-entropy 1223334444) 1.8464393446710154 1E-8)
(check-= (entropy "xggooopppp") 1.8464393446710154 1E-8))
(module+ main (entropy "1223334444")) |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #Logo | Logo | to double :x
output ashift :x 1
end
to halve :x
output ashift :x -1
end
to even? :x
output equal? 0 bitand 1 :x
end
to eproduct :x :y
if :x = 0 [output 0]
ifelse even? :x ~
[output eproduct halve :x double :y] ~
[output :y + eproduct halve :x double :y]
end |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #Swift | Swift | extension BinaryInteger {
@inlinable
public func power(_ n: Self) -> Self {
return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *)
}
}
func sumOfPowers(maxN: Int = 250) -> (Int, Int, Int, Int, Int) {
let pow5 = (0..<maxN).map({ $0.power(5) })
let pow5ToN = {n in pow5.firstIndex(of: n)}
for x0 in 1..<maxN {
for x1 in 1..<x0 {
for x2 in 1..<x1 {
for x3 in 1..<x2 {
let powSum = pow5[x0] + pow5[x1] + pow5[x2] + pow5[x3]
if let idx = pow5ToN(powSum) {
return (x0, x1, x2, x3, idx)
}
}
}
}
}
fatalError("Did not find solution")
}
let (x0, x1, x2, x3, y) = sumOfPowers()
print("\(x0)^5 + \(x1)^5 + \(x2)^5 \(x3)^5 = \(y)^5") |
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
| #Rapira | Rapira | Фун Факт(n)
f := 1
для i от 1 до n
f := f * i
кц
Возврат f
Кон Фун |
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.
| #MAXScript | MAXScript | -- MAXScript : Even or Odd : N.H. 2019
-- Open the MAXScript Listener for input and output
userInt = getKBValue prompt:"Enter an integer and i will tell you if its Even or Odd : "
if classOf userInt != Integer then print "The value you enter must be an integer"
else if (Mod userInt 2) == 0 Then Print "Your number is even"
else Print "Your number is odd"
|
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.
| #Mercury | Mercury | even(N) % in a body, suceeeds iff N is even.
odd(N). % in a body, succeeds iff N is odd.
% rolling our own:
:- pred even(int::in) is semidet.
% It's an error to have all three in one module, mind; even/1 would fail to check as semidet.
even(N) :- N mod 2 = 0. % using division that truncates towards -infinity
even(N) :- N rem 2 = 0. % using division that truncates towards zero
even(N) :- N /\ 1 = 0. % using bit-wise and. |
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).
| #Smalltalk | Smalltalk | isEmirp :=
[:p | |e|
(e := p asString reversed asNumber) isPrime
and:[ e ~= p ]
]. |
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).
| #Stata | Stata | emirp 1000
list in 1/20, noobs noh
+-----+
| 13 |
| 17 |
| 31 |
| 37 |
| 71 |
|-----|
| 73 |
| 79 |
| 97 |
| 107 |
| 113 |
|-----|
| 149 |
| 157 |
| 167 |
| 179 |
| 199 |
|-----|
| 311 |
| 337 |
| 347 |
| 359 |
| 389 |
+-----+
emirp 10000
list if 7700<p & p<8000, noobs noh
+------+
| 7717 |
| 7757 |
| 7817 |
| 7841 |
| 7867 |
|------|
| 7879 |
| 7901 |
| 7927 |
| 7949 |
| 7951 |
|------|
| 7963 |
+------+
emirp 1000000
list if _n==10000, noobs noh
+--------+
| 948349 |
+--------+ |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | % Demonstrate how to assign an empty string to a variable.
str = '';
% Demonstrate how to check that a string is empty.
isempty(str)
(length(str)==0)
% Demonstrate how to check that a string is not empty.
~isempty(str)
(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
| #Maxima | Maxima | s: ""$
/* check using string contents */
sequal(s, "");
not sequal(s, "");
/* check using string length */
slength(s) = "";
slength(s) # ""; |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Joy | Joy | . |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Jq | Jq | empty |
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
| #Raku | Raku | sub entropy(@a) {
[+] map -> \p { p * -log p }, bag(@a).values »/» +@a;
}
say log(2) R/ entropy '1223334444'.comb; |
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
| #LOLCODE | LOLCODE | HAI 1.3
HOW IZ I Halve YR Integer
FOUND YR QUOSHUNT OF Integer AN 2
IF U SAY SO
HOW IZ I Dubble YR Integer
FOUND YR PRODUKT OF Integer AN 2
IF U SAY SO
HOW IZ I IzEven YR Integer
FOUND YR BOTH SAEM 0 AN MOD OF Integer AN 2
IF U SAY SO
HOW IZ I EthiopianProdukt YR a AN YR b
I HAS A Result ITZ 0
IM IN YR LOOP UPPIN YR x WILE DIFFRINT a AN 0
NOT I IZ IzEven YR a MKAY
O RLY?
YA RLY
Result R SUM OF Result AN b
OIC
a R I IZ Halve YR a MKAY
b R I IZ Dubble YR b MKAY
IM OUTTA YR LOOP
FOUND YR Result
IF U SAY SO
VISIBLE I IZ EthiopianProdukt YR 17 AN YR 34 MKAY
KTHXBYE |
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.
| #Tcl | Tcl | proc doit {{badx 250} {complete 0}} {
## NB: $badx is exclusive upper limit, and also limits y!
for {set y 1} {$y < $badx} {incr y} {
set s [expr {$y ** 5}]
set r5($s) $y ;# fifth roots of valid sums
}
for {set a 1} {$a < $badx} {incr a} {
set suma [expr {$a ** 5}]
for {set b 1} {$b <= $a} {incr b} {
set sumb [expr {$suma + ($b ** 5)}]
for {set c 1} {$c <= $b} {incr c} {
set sumc [expr {$sumb + ($c ** 5)}]
for {set d 1} {$d <= $c} {incr d} {
set sumd [expr {$sumc + ($d ** 5)}]
if {[info exists r5($sumd)]} {
set e $r5($sumd)
puts "$e^5 = $a^5 + $b^5 + $c^5 + $d^5"
if {!$complete} {
return
}
}
}
}
}
}
puts "search complete (x < $badx)"
}
doit |
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
| #Rascal | Rascal | public int factorial_iter(int n){
result = 1;
for(i <- [1..n])
result *= i;
return result;
} |
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.
| #min | min | 3 even?
4 even?
5 odd?
get-stack print |
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.
| #MiniScript | MiniScript | for i in range(-4, 4)
if i % 2 == 0 then print i + " is even" else print i + " is odd"
end for |
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).
| #Swift | Swift | import Foundation
extension BinaryInteger {
var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) where self % i == 0 {
return false
}
return true
}
}
func isEmirp<T: BinaryInteger>(n: T) -> Bool {
guard n.isPrime else {
return false
}
var aux = n
var revPrime = T(0)
while aux > 0 {
revPrime = revPrime * 10 + aux % 10
aux /= 10
}
guard n != revPrime else {
return false
}
return revPrime.isPrime
}
let lots = (2...).lazy.filter(isEmirp).prefix(10000)
let rang = (7700...8000).filter(isEmirp)
print("First 20 emirps: \(Array(lots.prefix(20)))")
print("Emirps between 7700 and 8000: \(rang)")
print("10,000th emirp: \(Array(lots).last!)") |
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).
| #Tcl | Tcl | package require math::numtheory
# Import only to keep line lengths down
namespace import math::numtheory::isprime
proc emirp? {n} {
set r [string reverse $n]
expr {$n != $r && [isprime $n] && [isprime $r]}
}
# Generate the various emirps
for {set n 2;set emirps {}} {[llength $emirps] < 20} {incr n} {
if {[emirp? $n]} {lappend emirps $n}
}
puts "first20: $emirps"
for {set n 7700;set emirps {}} {$n <= 8000} {incr n} {
if {[emirp? $n]} {lappend emirps $n}
}
puts "7700-8000: $emirps"
for {set n 2;set ne 0} true {incr n} {
if {[emirp? $n] && [incr ne] == 10000} break
}
puts "10,000: $n" |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mercury | Mercury | S = "", % assignment
( if S = "" then ... else ... ), % checking if a string is empty
( if not S = "" then ... else ... ), % checking if a string is not empty |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #min | min | (bool not) :empty?
"" empty? puts!
"Rosetta Code" empty? puts! |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Julia | Julia | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #K | K | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #KonsolScript | KonsolScript | function main() {
} |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #REXX | REXX | /* REXX ***************************************************************
* 28.02.2013 Walter Pachl
* 12.03.2013 Walter Pachl typo in log corrected. thanx for testing
* 22.05.2013 -"- extended the logic to accept other strings
* 25.05.2013 -"- 'my' log routine is apparently incorrect
* 25.05.2013 -"- problem identified & corrected
**********************************************************************/
Numeric Digits 30
Parse Arg s
If s='' Then
s="1223334444"
occ.=0
chars=''
n=0
cn=0
Do i=1 To length(s)
c=substr(s,i,1)
If pos(c,chars)=0 Then Do
cn=cn+1
chars=chars||c
End
occ.c=occ.c+1
n=n+1
End
do ci=1 To cn
c=substr(chars,ci,1)
p.c=occ.c/n
/* say c p.c */
End
e=0
Do ci=1 To cn
c=substr(chars,ci,1)
e=e+p.c*log(p.c,30,2)
End
Say 'Version 1:' s 'Entropy' format(-e,,12)
Exit
log: Procedure
/***********************************************************************
* Return log(x) -- with specified precision and a specified base
* Three different series are used for the ranges 0 to 0.5
* 0.5 to 1.5
* 1.5 to infinity
* 03.09.1992 Walter Pachl
* 25.05.2013 -"- 'my' log routine is apparently incorrect
* 25.05.2013 -"- problem identified & corrected
***********************************************************************/
Parse Arg x,prec,b
If prec='' Then prec=9
Numeric Digits (2*prec)
Numeric Fuzz 3
Select
When x<=0 Then r='*** invalid argument ***'
When x<0.5 Then Do
z=(x-1)/(x+1)
o=z
r=z
k=1
Do i=3 By 2
ra=r
k=k+1
o=o*z*z
r=r+o/i
If r=ra Then Leave
End
r=2*r
End
When x<1.5 Then Do
z=(x-1)
o=z
r=z
k=1
Do i=2 By 1
ra=r
k=k+1
o=-o*z
r=r+o/i
If r=ra Then Leave
End
End
Otherwise /* 1.5<=x */ Do
z=(x+1)/(x-1)
o=1/z
r=o
k=1
Do i=3 By 2
ra=r
k=k+1
o=o/(z*z)
r=r+o/i
If r=ra Then Leave
End
r=2*r
End
End
If b<>'' Then
r=r/log(b,prec)
Numeric Digits (prec)
r=r+0
Return r |
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
| #Lua | Lua | function halve(a)
return a/2
end
function double(a)
return a*2
end
function isEven(a)
return a%2 == 0
end
function ethiopian(x, y)
local result = 0
while (x >= 1) do
if not isEven(x) then
result = result + y
end
x = math.floor(halve(x))
y = double(y)
end
return result;
end
print(ethiopian(17, 34)) |
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.
| #UNIX_Shell | UNIX Shell | MAX=250
pow5=()
for (( i=1; i<MAX; ++i )); do
pow5[i]=$(( i*i*i*i*i ))
done
for (( a=1; a<MAX; ++a )); do
for (( b=a+1; b<MAX; ++b )); do
for (( c=b+1; c<MAX; ++c )); do
for (( d=c+1; d<MAX; ++d )); do
(( sum=pow5[a]+pow5[b]+pow5[c]+pow5[d] ))
(( low=d+3 ))
(( high=MAX ))
while (( low <= high )); do
(( guess=(low+high)/2 ))
if (( pow5[guess] == sum )); then
printf 'Found example: %d⁵+%d⁵+%d⁵+%d⁵=%d⁵\n' "$a" "$b" "$c" "$d" "$guess"
exit 0
elif (( pow5[guess] < sum )); then
(( low=guess+1 ))
else
(( high=guess-1 ))
fi
done
done
done
done
done
printf 'No examples found.\n'
exit 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
| #RASEL | RASEL | 1&$:?v:1-3\$/1\
>$11\/.@ |
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.
| #MIPS_Assembly | MIPS Assembly |
.data
even_str: .asciiz "Even"
odd_str: .asciiz "Odd"
.text
#set syscall to get integer from user
li $v0,5
syscall
#perform bitwise AND and store in $a0
and $a0,$v0,1
#set syscall to print dytomh
li $v0,4
#jump to odd if the result of the AND operation
beq $a0,1,odd
even:
#load even_str message, and print
la $a0,even_str
syscall
#exit program
li $v0,10
syscall
odd:
#load odd_str message, and print
la $a0,odd_str
syscall
#exit program
li $v0,10
syscall
|
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.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | / 2 {x} ЗН |
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).
| #VBA | VBA | Option Explicit
Private Const MAX As Long = 5000000
Private Emirps As New Collection
Private CollTemp As New Collection
Sub Main()
Dim t
t = Timer
FillCollectionOfEmirps
Debug.Print "At this point : Execution time = " & Timer - t & " seconds."
Debug.Print "We have a Collection of the " & Emirps.Count & " first Emirps."
Debug.Print "---------------------------"
'show the first twenty emirps
Debug.Print "the first 20 emirps: "; ExtractEmirps(1, 20)
'show all emirps between 7,700 and 8,000
Debug.Print "all emirps between 7,700 and 8,000: "; ExtractEmirps(7700, 8000, True)
'show the 10,000th emirp
Debug.Print "the 10,000th emirp: "; ExtractEmirps(10000, 10000)
End Sub
Private Function ExtractEmirps(First As Long, Last As Long, Optional Value = False) As String
Dim temp$, i As Long, e
If First = Last Then
ExtractEmirps = Emirps(First)
Else
If Not Value Then
For i = First To Last
temp = temp & ", " & Emirps(i)
Next
Else
For Each e In Emirps
If e > First And e < Last Then
temp = temp & ", " & e
End If
If e = Last Then Exit For
Next e
End If
ExtractEmirps = Mid(temp, 3)
End If
End Function
Private Sub FillCollectionOfEmirps()
Dim Primes() As Long, e, i As Long
Primes = Atkin
For i = LBound(Primes) To UBound(Primes)
CollTemp.Add Primes(i), CStr(Primes(i))
Next i
For Each e In CollTemp
If IsEmirp(e) Then Emirps.Add e
Next
End Sub
Private Function Atkin() As Long()
Dim MyBool() As Boolean
Dim SQRT_MAX As Long, i&, j&, N&, cpt&, MAX_TEMP As Long, temp() As Long
ReDim MyBool(MAX)
SQRT_MAX = Sqr(MAX) + 1
MAX_TEMP = Sqr(MAX / 4) + 1
For i = 1 To MAX_TEMP
For j = 1 To SQRT_MAX
N = 4 * i * i + j * j
If N <= MAX And (N Mod 12 = 1 Or N Mod 12 = 5) Then
MyBool(N) = True
End If
Next j
Next i
MAX_TEMP = Sqr(MAX / 3) + 1
For i = 1 To MAX_TEMP
For j = 1 To SQRT_MAX
N = 3 * i * i + j * j
If N <= MAX And N Mod 12 = 7 Then
MyBool(N) = True
End If
Next j
Next i
For i = 1 To SQRT_MAX
For j = 1 To SQRT_MAX
N = 3 * i * i - j * j
If i > j And N <= MAX And N Mod 12 = 11 Then
MyBool(N) = True
End If
Next j
Next i
For i = 5 To SQRT_MAX Step 2
If MyBool(i) Then
For j = i * i To MAX Step i
MyBool(j) = False
Next
End If
Next
ReDim temp(MAX / 2)
temp(0) = 2: temp(1) = 3: cpt = 2
For i = 5 To MAX Step 2
If MyBool(i) Then temp(cpt) = i: cpt = cpt + 1
Next
ReDim Preserve temp(cpt - 1)
Atkin = temp
End Function
Private Function IsEmirp(N) As Boolean
Dim a As String, b As String
a = StrReverse(CStr(N)): b = CStr(N)
If a <> b Then
On Error Resume Next
CollTemp.Add a, a
If Err.Number > 0 Then
IsEmirp = True
Else
CollTemp.Remove a
End If
On Error GoTo 0
End If
End Function |
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
| #Mirah | Mirah | empty_string1 = ""
empty_string2 = String.new
puts "empty string is empty" if empty_string1.isEmpty()
puts "empty string has no length" if empty_string2.length() == 0
puts "empty string is not nil" unless empty_string1 == nil |
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
| #Nanoquery | Nanoquery | s = ""
if len(s)=0
println "s is empty"
else
println "s is not empty"
end |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Kotlin | Kotlin | fun main(a: Array<String>) {} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Lambdatalk | Lambdatalk | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Lang5 | Lang5 | exit |
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
| #Ring | Ring |
decimals(8)
entropy = 0
countOfChar = list(255)
source="1223334444"
charCount =len( source)
usedChar =""
for i =1 to len( source)
ch =substr(source, i, 1)
if not(substr( usedChar, ch)) usedChar =usedChar +ch ok
j =substr( usedChar, ch)
countOfChar[j] =countOfChar[j] +1
next
l =len(usedChar)
for i =1 to l
probability =countOfChar[i] /charCount
entropy =entropy - (probability *logBase(probability, 2))
next
see "Characters used and the number of occurrences of each " + nl
for i =1 to l
see "'" + substr(usedChar, i, 1) + "' " + countOfChar[i] + nl
next
see " Entropy of " + source + " is " + entropy + " bits." + nl
see " The result should be around 1.84644 bits." + nl
func logBase (x, b)
logBase =log( x) /log( 2)
return logBase
|
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
| #Ruby | Ruby | def entropy(s)
counts = Hash.new(0.0)
s.each_char { |c| counts[c] += 1 }
leng = s.length
counts.values.reduce(0) do |entropy, count|
freq = count / leng
entropy - freq * Math.log2(freq)
end
end
p entropy("1223334444") |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.
In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.
Examine the table produced and discard any row where the value in the left column is even.
Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together
For example: 17 × 34
17 34
Halving the first column:
17 34
8
4
2
1
Doubling the second column:
17 34
8 68
4 136
2 272
1 544
Strike-out rows whose first cell is even:
17 34
8 68
4 136
2 272
1 544
Sum the remaining numbers in the right-hand column:
17 34
8 --
4 ---
2 ---
1 544
====
578
So 17 multiplied by 34, by the Ethiopian method is 578.
Task
The task is to define three named functions/methods/procedures/subroutines:
one to halve an integer,
one to double an integer, and
one to state if an integer is even.
Use these functions to create a function that does Ethiopian multiplication.
References
Ethiopian multiplication explained (BBC Video clip)
A Night Of Numbers - Go Forth And Multiply (Video)
Russian Peasant Multiplication
Programming Praxis: Russian Peasant Multiplication
| #M2000_Interpreter | M2000 Interpreter |
Module EthiopianMultiplication{
Form 60, 25
Const Center=2, ColumnWith=12
Report Center,"Ethiopian Method of Multiplication"
// using decimals as unsigned integers
Def Decimal leftval, rightval, sum
(leftval, rightval)=(random(1, 65535), random(1, 65536))
Print $( , ColumnWith), "Target:", leftval*rightval,
Hex leftval*rightval
sum=0
if @IsEven(leftval) Else sum+=rightval
Print leftval, rightval,
Hex leftval, rightval
while leftval>1
leftval=@halveInt(leftval)
rightval=@DoubleInt(rightval)
Print leftval, rightval,
Hex leftval, rightval
if @IsEven(leftval) Else sum+=rightval
End while
Print "", sum
Hex "", sum
Function HalveInt(i)
=Binary.Shift(i,-1)
End Function
Function DoubleInt(i)
=Binary.Shift(i,1)
End Function
Function IsEven(i)
=Binary.And(i, 1)=0
End Function
}
EthiopianMultiplication
|
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.
| #VBA | VBA | Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Public Sub begin()
start_int = GetTickCount()
main
Debug.Print (GetTickCount() - start_int) / 1000 & " seconds"
End Sub
Private Function pow(x, y) As Variant
pow = CDec(Application.WorksheetFunction.Power(x, y))
End Function
Private Sub main()
For x0 = 1 To 250
For x1 = 1 To x0
For x2 = 1 To x1
For x3 = 1 To x2
sum = CDec(pow(x0, 5) + pow(x1, 5) + pow(x2, 5) + pow(x3, 5))
s1 = Int(pow(sum, 0.2))
If sum = pow(s1, 5) Then
Debug.Print x0 & "^5 + " & x1 & "^5 + " & x2 & "^5 + " & x3 & "^5 = " & s1
Exit Sub
End If
Next x3
Next x2
Next x1
Next x0
End Sub |
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
| #REBOL | REBOL | rebol [
Title: "Factorial"
URL: http://rosettacode.org/wiki/Factorial_function
]
; Standard recursive implementation.
factorial: func [n][
either n > 1 [n * factorial n - 1] [1]
]
; Iteration.
ifactorial: func [n][
f: 1
for i 2 n 1 [f: f * i]
f
]
; Automatic memoization.
; I'm just going to say up front that this is a stunt. However, you've
; got to admit it's pretty nifty. Note that the 'memo' function
; works with an unlimited number of arguments (although the expected
; gains decrease as the argument count increases).
memo: func [
"Defines memoizing function -- keeps arguments/results for later use."
args [block!] "Function arguments. Just specify variable names."
body [block!] "The body block of the function."
/local m-args m-r
][
do compose/deep [
func [
(args)
/dump "Dump memory."
][
m-args: []
if dump [return m-args]
if m-r: select/only m-args reduce [(args)] [return m-r]
m-r: do [(body)]
append m-args reduce [reduce [(args)] m-r]
m-r
]
]
]
mfactorial: memo [n][
either n > 1 [n * mfactorial n - 1] [1]
]
; Test them on numbers zero to ten.
for i 0 10 1 [print [i ":" factorial i ifactorial i mfactorial i]] |
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.
| #ML | ML |
fun even( x: int ) = (x mod 2 = 0);
fun odd( x: int ) = (x mod 2 = 1);
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Modula-2 | Modula-2 | MODULE EvenOrOdd;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
VAR
buf : ARRAY[0..63] OF CHAR;
i : INTEGER;
BEGIN
FOR i:=-5 TO 5 DO
FormatString("%i is even: %b\n", buf, i, i MOD 2 = 0);
WriteString(buf)
END;
ReadChar
END EvenOrOdd. |
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).
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Runtime.CompilerServices
Module Module1
<Extension()>
Function ToHashSet(Of T)(source As IEnumerable(Of T)) As HashSet(Of T)
Return New HashSet(Of T)(source)
End Function
<Extension()>
Function Reverse(number As Integer) As Integer
If number < 0 Then
Return -Reverse(-number)
End If
If number < 10 Then
Return number
End If
Dim rev = 0
While number > 0
rev = rev * 10 + number Mod 10
number = number \ 10
End While
Return rev
End Function
<Extension()>
Function Delimit(Of T)(source As IEnumerable(Of T), Optional seperator As String = " ") As String
Return String.Join(If(seperator, " "), source)
End Function
Iterator Function Primes(bound As Integer) As IEnumerable(Of Integer)
If bound < 2 Then
Return
End If
Yield 2
Dim composite As New BitArray((bound - 1) / 2)
Dim limit As Integer = Int((Int(Math.Sqrt(bound)) - 1) / 2)
For i = 0 To limit - 1
If composite(i) Then
Continue For
End If
Dim prime = 2 * i + 3
Yield prime
For j As Integer = Int((prime * prime - 2) / 2) To composite.Count - 1 Step prime
composite(j) = True
Next
Next
For i = limit To composite.Count - 1
If Not composite(i) Then
Yield 2 * i + 3
End If
Next
End Function
Iterator Function FindEmirpPrimes(limit As Integer) As IEnumerable(Of Integer)
Dim ps = Primes(limit).ToHashSet()
For Each p In ps
Dim rev = p.Reverse()
If rev <> p AndAlso ps.Contains(rev) Then
Yield p
End If
Next
End Function
Sub Main()
Dim limit = 1_000_000
Console.WriteLine("First 20:")
Console.WriteLine(FindEmirpPrimes(limit).Take(20).Delimit())
Console.WriteLine()
Console.WriteLine("Between 7700 and 8000:")
Console.WriteLine(FindEmirpPrimes(limit).SkipWhile(Function(p) p < 7700).TakeWhile(Function(p) p < 8000).Delimit())
Console.WriteLine()
Console.WriteLine("10000th:")
Console.WriteLine(FindEmirpPrimes(limit).ElementAt(9999))
End Sub
End Module |
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
| #Nemerle | Nemerle | def empty = "";
mutable fill_later = ""; |
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
| #NESL | NESL | my_empty_string = "";
% To make sure it is empty, we can ask whether its length is equal to zero. %
#my_empty_string == 0; |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Lasso | Lasso | [] |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #LaTeX | LaTeX | \documentclass{minimal}
\begin{document}
\end{document} |
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
| #Run_BASIC | Run BASIC | dim chrCnt( 255) ' possible ASCII chars
source$ = "1223334444"
numChar = len(source$)
for i = 1 to len(source$) ' count which chars are used in source
ch$ = mid$(source$,i,1)
if not( instr(chrUsed$, ch$)) then chrUsed$ = chrUsed$ + ch$
j = instr(chrUsed$, ch$)
chrCnt(j) =chrCnt(j) +1
next i
lc = len(chrUsed$)
for i = 1 to lc
odds = chrCnt(i) /numChar
entropy = entropy - (odds * (log(odds) / log(2)))
next i
print " Characters used and times used of each "
for i = 1 to lc
print " '"; mid$(chrUsed$,i,1); "'";chr$(9);chrCnt(i)
next i
print " Entropy of '"; source$; "' is "; entropy; " bits."
end |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #Rust | Rust | fn entropy(s: &[u8]) -> f32 {
let mut histogram = [0u64; 256];
for &b in s {
histogram[b as usize] += 1;
}
histogram
.iter()
.cloned()
.filter(|&h| h != 0)
.map(|h| h as f32 / s.len() as f32)
.map(|ratio| -ratio * ratio.log2())
.sum()
}
fn main() {
let arg = std::env::args().nth(1).expect("Need a string.");
println!("Entropy of {} is {}.", arg, entropy(arg.as_bytes()));
} |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | IntegerHalving[x_]:=Floor[x/2]
IntegerDoubling[x_]:=x*2;
OddInteger OddQ
Ethiopian[x_, y_] :=
Total[Select[NestWhileList[{IntegerHalving[#[[1]]],IntegerDoubling[#[[2]]]}&, {x,y}, (#[[1]]>1&)], OddQ[#[[1]]]&]][[2]]
Ethiopian[17, 34] |
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.
| #VBScript | VBScript | Max=250
For X0=1 To Max
For X1=1 To X0
For X2=1 To X1
For X3=1 To X2
Sum=fnP5(X0)+fnP5(X1)+fnP5(X2)+fnP5(X3)
S1=Int(Sum^0.2)
If Sum=fnP5(S1) Then
WScript.StdOut.Write X0 & " " & X1 & " " & X2 & " " & X3 & " " & S1
WScript.Quit
End If
Next
Next
Next
Next
Function fnP5(n)
fnP5 = n ^ 5
End Function |
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
| #Red | Red | fac: function [n][r: 1 repeat i n [r: r * i] r]
fac: function [n][repeat i also n n: 1 [n: n * i] n] |
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.
| #Nanoquery | Nanoquery | def isEven(n)
if ((n % 2) = 1)
return false
else
return true
end
end
for i in range(1, 10)
print i
if isEven(i)
println " is even."
else
println " is odd."
end
end |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd.
Use modular congruences:
i ≡ 0 (mod 2) iff i is even.
i ≡ 1 (mod 2) iff i is odd.
| #Neko | Neko | var number = 6;
if(number % 2 == 0) {
$print("Even");
} else {
$print("Odd");
} |
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).
| #Wren | Wren | import "/math" for Int
var isEmirp = Fn.new{ |n|
if (!Int.isPrime(n)) return false
var ns = "%(n)"
var rs = ns[-1..0]
var r = Num.fromString(rs)
if (r == n) return false
if (Int.isPrime(r)) return true
return false
}
System.print("The first 20 emirps are:")
var count = 0
var i = 3
while (count < 20) {
if (isEmirp.call(i)) {
count = count + 1
System.write("%(i) ")
}
i = i + 2
}
System.print("\n\nThe emirps between 7700 and 8000 are:")
i = 7701
while (i < 8000) {
if (isEmirp.call(i)) System.write("%(i) ")
i = i + 2
}
System.write("\n\nThe 10,000th emirp is ")
count = 0
i = 1
while (count < 10000) {
i = i + 2
if (isEmirp.call(i)) {
count = count + 1
}
}
System.print(i) |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
s1 = '' -- assignment
s2 = "" -- equivalent to s1
parse '.' . s3 . -- parsing a token that doesn't exist results in an empty string
strings = [s1, s2, s3, ' ']
loop s_ = 0 to strings.length - 1
say (Rexx s_).right(3)':\-'
select
when strings[s_] == '' then say ' "'strings[s_]'" is really empty'
when strings[s_].length = 0 then say ' "'strings[s_]'" is empty'
when strings[s_] = '' then say ' "'strings[s_]'" looks empty but may not be'
when strings[s_].length > 0 then say ' "'strings[s_]'" is not empty'
otherwise nop
end
end s_
return
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #LC3_Assembly | LC3 Assembly | .END |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Liberty_BASIC | Liberty BASIC | end |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is :
H
2
(
X
)
=
−
∑
i
=
1
n
c
o
u
n
t
i
N
log
2
(
c
o
u
n
t
i
N
)
{\displaystyle H_{2}(X)=-\sum _{i=1}^{n}{\frac {count_{i}}{N}}\log _{2}\left({\frac {count_{i}}{N}}\right)}
where
c
o
u
n
t
i
{\displaystyle count_{i}}
is the count of character
n
i
{\displaystyle n_{i}}
.
For this task, use X="1223334444" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.
This coding problem calculates the "specific" or "intensive" entropy that finds its parallel in physics with "specific entropy" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the "information" content of a file. It comes from Boltzmann's H-theorem where
S
=
k
B
N
H
{\displaystyle S=k_{B}NH}
where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a "per molecule" basis.
The "total", "absolute", or "extensive" information entropy is
S
=
H
2
N
{\displaystyle S=H_{2}N}
bits
This is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of "information". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have
S
=
N
log
2
(
16
)
{\displaystyle S=N\log _{2}(16)}
bits of entropy. The total entropy in bits of the example above is S= 10*18.4644 = 18.4644 bits.
The H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much "order" was in the data.
Two other "entropies" are useful:
Normalized specific entropy:
H
n
=
H
2
∗
log
(
2
)
log
(
n
)
{\displaystyle H_{n}={\frac {H_{2}*\log(2)}{\log(n)}}}
which varies from 0 to 1 and it has units of "entropy/symbol" or just 1/symbol. For this example, Hn<\sub>= 0.923.
Normalized total (extensive) entropy:
S
n
=
H
2
N
∗
log
(
2
)
log
(
n
)
{\displaystyle S_{n}={\frac {H_{2}N*\log(2)}{\log(n)}}}
which varies from 0 to N and does not have units. It is simply the "entropy", but it needs to be called "total normalized extensive entropy" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\sub>= 9.23.
Shannon himself is the reason his "entropy/symbol" H function is very confusingly called "entropy". That's like calling a function that returns a speed a "meter". See section 1.7 of his classic A Mathematical Theory of Communication and search on "per symbol" and "units" to see he always stated his entropy H has units of "bits/symbol" or "entropy/symbol" or "information/symbol". So it is legitimate to say entropy NH is "information".
In keeping with Landauer's limit, the physics entropy generated from erasing N bits is
S
=
H
2
N
k
B
ln
(
2
)
{\displaystyle S=H_{2}Nk_{B}\ln(2)}
if the bit storage device is perfectly efficient. This can be solved for H2*N to (arguably) get the number of bits of information that a physical entropy represents.
Related tasks
Fibonacci_word
Entropy/Narcissist
| #Scala | Scala | import scala.math._
def entropy( v:String ) = { v
.groupBy (a => a)
.values
.map( i => i.length.toDouble / v.length )
.map( p => -p * log10(p) / log10(2))
.sum
}
// Confirm that "1223334444" has an entropy of about 1.84644
assert( math.round( entropy("1223334444") * 100000 ) * 0.00001 == 1.84644 ) |
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
| #scheme | scheme |
(define (entropy input)
(define (close? a b)
(define (norm x y)
(define (infinite_norm m n)
(define (absminus p q)
(cond ((null? p) '())
(else (cons (abs (- (car p) (car q))) (absminus (cdr p) (cdr q))))))
(define (mm l)
(cond ((null? (cdr l)) (car l))
((> (car l) (cadr l)) (mm (cons (car l) (cddr l))))
(else (mm (cdr l)))))
(mm (absminus m n)))
(if (pair? x) (infinite_norm x y) (abs (- x y))))
(let ((epsilon 0.2))
(< (norm a b) epsilon)))
(define (freq-list x)
(define (f x)
(define (count a b)
(cond ((null? b) 1)
(else (+ (if (close? a (car b)) 1 0) (count a (cdr b))))))
(let ((t (car x)) (tt (cdr x)))
(count t tt)))
(define (g x)
(define (filter a b)
(cond ((null? b) '())
((close? a (car b)) (filter a (cdr b)))
(else (cons (car b) (filter a (cdr b))))))
(let ((t (car x)) (tt (cdr x)))
(filter t tt)))
(cond ((null? x) '())
(else (cons (f x) (freq-list (g x))))))
(define (scale x)
(define (sum x)
(if (null? x) 0.0 (+ (car x) (sum (cdr x)))))
(let ((z (sum x)))
(map (lambda(m) (/ m z)) x)))
(define (cal x)
(if (null? x) 0 (+ (* (car x) (/ (log (car x)) (log 2))) (cal (cdr x)))))
(- (cal (scale (freq-list input)))))
(entropy (list 1 2 2 3 3 3 4 4 4 4))
(entropy (list (list 1 1) (list 1.1 1.1) (list 1.2 1.2) (list 1.3 1.3) (list 1.5 1.5) (list 1.6 1.6)))
|
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
| #MATLAB | MATLAB | function result = halveInt(number)
result = idivide(number,2,'floor');
end |
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture | Euler's sum of powers conjecture | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
Euler's (disproved) sum of powers conjecture
At least k positive kth powers are required to sum to a kth power,
except for the trivial case of one kth power: yk = yk
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
Task
Write a program to search for an integer solution for:
x05 + x15 + x25 + x35 == y5
Where all xi's and y are distinct integers between 0 and 250 (exclusive).
Show an answer here.
Related tasks
Pythagorean quadruples.
Pythagorean triples.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Structure Pair
Dim a, b As Integer
Sub New(x as integer, y as integer)
a = x : b = y
End Sub
End Structure
Dim max As Integer = 250
Dim p5() As Long,
sum2 As SortedDictionary(Of Long, Pair) = New SortedDictionary(Of Long, Pair)
Function Fmt(p As Pair) As String
Return String.Format("{0}^5 + {1}^5", p.a, p.b)
End Function
Sub Init()
p5(0) = 0 : p5(1) = 1 : For i As Integer = 1 To max - 1
For j As Integer = i + 1 To max
p5(j) = CLng(j) * j : p5(j) *= p5(j) * j
sum2.Add(p5(i) + p5(j), New Pair(i, j))
Next
Next
End Sub
Sub Calc(Optional findLowest As Boolean = True)
For i As Integer = 1 To max : Dim p As Long = p5(i)
For Each s In sum2.Keys
Dim t As Long = p - s : If t <= 0 Then Exit For
If sum2.Keys.Contains(t) AndAlso sum2.Item(t).a > sum2.Item(s).b Then
Console.WriteLine(" {1} + {2} = {0}^5", i, Fmt(sum2.Item(s)), Fmt(sum2.Item(t)))
If findLowest Then Exit Sub
End If
Next : Next
End Sub
Sub Main(args As String())
If args.Count > 0 Then
Dim t As Integer = 0 : Integer.TryParse(args(0), t)
If t > 0 AndAlso t < 5405 Then max = t
End If
Console.WriteLine("Checking from 1 to {0}...", max)
For i As Integer = 0 To 1
ReDim p5(max) : sum2.Clear()
Dim st As DateTime = DateTime.Now
Init() : Calc(i = 0)
Console.WriteLine("{0} Computation time to {2} was {1} seconds{0}", vbLf,
(DateTime.Now - st).TotalSeconds, If(i = 0, "find lowest one", "check entire space"))
Next
If Diagnostics.Debugger.IsAttached Then Console.ReadKey()
End Sub
End Module |
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
| #Relation | Relation |
function factorial (n)
set result = 1
if n > 1
set k = 2
while k <= n
set result = result * k
set k = k + 1
end while
end if
end function
|
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.
| #NESL | NESL | function even(n) = mod(n, 2) == 0;
% test the function by applying it to the first ten positive integers: %
{even(n) : n in [1:11]}; |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
say 'Val'.right(5)': mod - ver - pos - bits'
say '---'.right(5)': ---- + ---- + ---- + ----'
loop nn = -15 to 15 by 3
say nn.right(5)':' eo(isEven(nn)) '-' eo(isEven(nn, 'v')) '-' eo(isEven(nn, 'p')) '-' eo(isEven(nn, 'b'))
end nn
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Overloaded method. Default is to use the remainder specialization below
method isEven(anInt, meth = 'R') public static returns boolean
select case meth.upper().left(1)
when 'R' then eo = isEvenRemainder(anInt)
when 'V' then eo = isEvenVerify(anInt)
when 'P' then eo = isEvenPos(anInt)
when 'B' then eo = isEvenBits(anInt)
otherwise eo = isEvenRemainder(anInt) -- default
end
return eo
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isEvenRemainder(anInt) public static returns boolean
return anInt // 2 == 0
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isEvenVerify(anInt) public static returns boolean
return anInt.right(1).verify('02468') == 0
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isEvenPos(anInt) public static returns boolean
return '13579'.pos(anInt.right(1)) == 0
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method isEvenBits(anInt) public static returns boolean
return \(anInt.d2x(1).x2b().right(1))
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method eo(state = boolean) public static
if state then sv = 'Even'
else sv = 'Odd'
return sv.left(4)
|
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).
| #zkl | zkl | var PS=Import("Src/ZenKinetic/sieve").postponed_sieve;
var ps=Utils.Generator(PS), plist=ps.walk(10).copy();
fcn isEmirp(p){ rp:=p.toString().reverse().toInt();
if(p==rp) return(False);
if(plist.holds(rp)) return(True);
tp:=p; mp:=p.max(rp); while(tp<mp) { plist.append(tp=ps.next()) }
return(tp==rp);
}
Utils.Generator(PS).filter(20,isEmirp);
Utils.Generator(PS).filter(fcn(p){if(p>8000)return(Void.Stop); p>7700 and isEmirp(p)});
Utils.Generator(PS).reduce(fcn(N,p){N+=isEmirp(p); (N==10000) and T(Void.Stop,p) or N },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
| #Nim | Nim | var x = ""
if x == "":
echo "empty"
if x != "":
echo "not empty"
# Alternatively:
if x.len == 0:
echo "empty"
if x.len > 0:
echo "not empty" |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #NS-HUBASIC | NS-HUBASIC | 10 S$=""
20 IF S$<>"" THEN O$="NOT "
30 PRINT "THE STRING IS "O$"EMPTY." |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Lilypond | Lilypond | \version "2.6.12" |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Lingo | Lingo | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Lisp | Lisp | |
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
| #Scilab | Scilab | function E = entropy(d)
d=strsplit(d);
n=unique(string(d));
N=size(d,'r');
count=zeros(n);
n_size = size(n,'r');
for i = 1:n_size
count(i) = sum ( d == n(i) );
end
E=0;
for i=1:length(count)
E = E - count(i)/N * log(count(i)/N) / log(2);
end
endfunction
word ='1223334444';
E = entropy(word);
disp('The entropy of '+word+' is '+string(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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const func float: entropy (in string: stri) is func
result
var float: entropy is 0.0;
local
var hash [char] integer: count is (hash [char] integer).value;
var char: ch is ' ';
var float: p is 0.0;
begin
for ch range stri do
if ch in count then
incr(count[ch]);
else
count @:= [ch] 1;
end if;
end for;
for key ch range count do
p := flt(count[ch]) / flt(length(stri));
entropy -:= p * log(p) / log(2.0);
end for;
end func ;
const proc: main is func
begin
writeln(entropy("1223334444") digits 5);
end func; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.