task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #SenseTalk | SenseTalk | put the temporary folder & "NewFolder" into newFolderPath
make folder newFolderPath -- create a new empty directory
if the filesAndFolders in newFolderPath is empty then
put "Directory " & newFolderPath & " is empty!"
else
put "Something is present in " & newFolderPath
end if
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #Sidef | Sidef | Dir.new('/my/dir').is_empty; # true, false or nil |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Dart | Dart | main() {} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #dc | dc | {} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #DCL | DCL | {} |
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 bit... | #J | J | entropy=: +/@(-@* 2&^.)@(#/.~ % #) |
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 bit... | #Java | Java | import java.lang.Math;
import java.util.Map;
import java.util.HashMap;
public class REntropy {
@SuppressWarnings("boxing")
public static double getShannonEntropy(String s) {
int n = 0;
Map<Character, Integer> occ = new HashMap<>();
for (int c_ = 0; c_ < s.length(); ++c_) {
char cx = s.charAt... |
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 ... | #Euphoria | Euphoria | function emHalf(integer n)
return floor(n/2)
end function
function emDouble(integer n)
return n*2
end function
function emIsEven(integer n)
return (remainder(n,2) = 0)
end function
function emMultiply(integer a, integer b)
integer sum
sum = 0
while (a) do
if (not emIsEven(a)) then sum += b end if
... |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Racket | Racket |
#lang racket
(define (subsums xs)
(for/fold ([sums '()] [sum 0]) ([x xs])
(values (cons (+ x sum) sums)
(+ x sum))))
(define (equivilibrium xs)
(define-values (sums total) (subsums xs))
(for/list ([sum (reverse sums)]
[x xs]
[i (in-naturals)]
#:when (= (-... |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Raku | Raku | sub equilibrium_index(@list) {
my ($left,$right) = 0, [+] @list;
gather for @list.kv -> $i, $x {
$right -= $x;
take $i if $left == $right;
$left += $x;
}
}
my @list = -7, 1, 5, 2, -4, 3, 0;
.say for equilibrium_index(@list).grep(/\d/); |
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... | #Perl | Perl | use constant MAX => 250;
my @p5 = (0,map { $_**5 } 1 .. MAX-1);
my $s = 0;
my %p5 = map { $_ => $s++ } @p5;
for my $x0 (1..MAX-1) {
for my $x1 (1..$x0-1) {
for my $x2 (1..$x1-1) {
for my $x3 (1..$x2-1) {
my $sum = $p5[$x0] + $p5[$x1] + $p5[$x2] + $p5[$x3];
die "$x3 $x2 $x1 $x0 $p5{$sum}\n" i... |
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 iterat... | #PHP | PHP | <?php
function factorial($n) {
if ($n < 0) {
return 0;
}
$factorial = 1;
for ($i = $n; $i >= 1; $i--) {
$factorial = $factorial * $i;
}
return $factorial;
}
?> |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #Gambas | Gambas | Public Sub Form_Open()
Dim sAnswer, sMessage As String
sAnswer = InputBox("Input an integer", "Odd or even")
If IsInteger(sAnswer) Then
If Odd(Val(sAnswer)) Then sMessage = "' is an odd number"
If Even(Val(sAnswer)) Then sMessage = "' is an even number"
Else
sMessage = "' does not compute!!"
Endif
Print "'"... |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #R | R | choose(5,3) |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Racket | Racket |
#lang racket
(require math)
(binomial 10 5)
|
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 numbe... | #Julia | Julia | using Primes
function collapse(n::Array{<:Integer})
sum = 0
for (p, d) in enumerate(n)
sum += d * 10 ^ (p - 1)
end
return sum
end
Base.reverse(n::Integer) = collapse(reverse(digits(n)))
isemirp(n::Integer) = (if isprime(n) m = reverse(n); return m != n && isprime(m) end; false)
function fi... |
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 numbe... | #Kotlin | Kotlin | // version 1.1.4
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun... |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #XPL0 | XPL0 | def \Fruit\ Apple, Banana, Cherry; \Apple=0, Banana=1, Cherry=2
def Apple=1, Banana=2, Cherry=4;
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Z80_Assembly | Z80 Assembly | Sunday equ 0
Monday equ 1
Tuesday equ 2
Wednesday equ 3
Thursday equ 4
Friday equ 5
Saturday equ 6 |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #zkl | zkl | const RGB_COLOR{ // put color names in a name space
const RED =0xf00;
const BLUE=0x0f0, GREEN = 0x00f;
const CYAN=BLUE + GREEN; // → 0x0ff
}
println(RGB_COLOR.BLUE); |
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 oper... | #Euphoria | Euphoria | sequence s
-- assign an empty string
s = ""
-- another way to assign an empty string
s = {} -- "" and {} are equivalent
if not length(s) then
-- string is empty
end if
if length(s) then
-- string is not empty
end if |
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 oper... | #F.23 | F# | open System
[<EntryPoint>]
let main args =
let emptyString = String.Empty // or any of the literals "" @"" """"""
printfn "Is empty %A: %A" emptyString (emptyString = String.Empty)
printfn "Is not empty %A: %A" emptyString (emptyString <> String.Empty)
0 |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #Standard_ML | Standard ML | fun isDirEmpty(path: string) =
let
val dir = OS.FileSys.openDir path
val dirEntryOpt = OS.FileSys.readDir dir
in
(
OS.FileSys.closeDir(dir);
case dirEntryOpt of
NONE => true
| _ => false
)
end; |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #Tcl | Tcl | proc isEmptyDir {dir} {
# Get list of _all_ files in directory
set filenames [glob -nocomplain -tails -directory $dir * .*]
# Check whether list is empty (after filtering specials)
expr {![llength [lsearch -all -not -regexp $filenames {^\.\.?$}]]}
} |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #UNIX_Shell | UNIX Shell |
#!/bin/sh
DIR=/tmp/foo
[ `ls -a $DIR|wc -l` -gt 2 ] && echo $DIR is NOT empty || echo $DIR is empty
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #VBA | VBA | Sub Main()
Debug.Print IsEmptyDirectory("C:\Temp")
Debug.Print IsEmptyDirectory("C:\Temp\")
End Sub
Private Function IsEmptyDirectory(D As String) As Boolean
Dim Sep As String
Sep = Application.PathSeparator
D = IIf(Right(D, 1) <> Sep, D & Sep, D)
IsEmptyDirectory = (Dir(D & "*.*") = "")
End Funct... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Delphi | Delphi | {} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Dyalect | Dyalect | {} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | |
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 bit... | #JavaScript | JavaScript | // Shannon entropy in bits per symbol.
function entropy(str) {
const len = str.length
// Build a frequency map from the string.
const frequencies = Array.from(str)
.reduce((freq, c) => (freq[c] = (freq[c] || 0) + 1) && freq, {})
// Sum the frequency of each character.
return Object.values(frequencies)... |
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 ... | #F.23 | F# | let ethopian n m =
let halve n = n / 2
let double n = n * 2
let even n = n % 2 = 0
let rec loop n m result =
if n <= 1 then result + m
else if even n then loop (halve n) (double m) result
else loop (halve n) (double m) (result + m)
loop n m 0 |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Red | Red | Red []
eqindex: func [a [block!]] [
collect [
repeat ind length? a [ if (sum skip a ind) = sum copy/part a ind - 1 [ keep ind ] ]
]
]
prin "(1 based) equ indices are: "
probe eqindex [-7 1 5 2 -4 3 0]
|
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #ReScript | ReScript | let arr = [-7, 1, 5, 2, -4, 3, 0]
let sum = Js.Array2.reduce(arr, \"+", 0)
let len = Js.Array.length(arr)
let rec aux = (acc, i, left, right) => {
if (i >= len) { acc } else {
let x = arr[i]
let right = right - x
if (left == right) {
let _ = Js.Array2.push(acc, i)
}
aux(acc, i+1, (left + x... |
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... | #Phix | Phix | with javascript_semantics
constant MAX = 250
constant p5 = new_dict(),
sum2 = new_dict()
atom t0 = time()
for i=1 to MAX do
atom i5 = power(i,5)
setd(i5,i,p5)
for j=1 to i-1 do
atom j5 = power(j,5)
setd(j5+i5,{j,i},sum2)
end for
end for
?time()-t0
function forsum2(object... |
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 iterat... | #Picat | Picat | fact(N) = prod(1..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... | #GAP | GAP | IsEvenInt(n);
IsOddInt(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... | #Genie | Genie | [indent = 4]
/*
Even or odd, in Genie
valac even_or_odd.gs
*/
def parity(n:int):bool
return ((n & 1) == 0)
def show_parity(n:int):void
print "%d is %s", n, parity(n) ? "even" : "odd"
init
show_parity(0)
show_parity(1)
show_parity(2)
show_parity(-2)
show_parity(-1) |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Raku | Raku | say combinations(5, 3).elems; |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #REXX | REXX | /*REXX program calculates binomial coefficients (also known as combinations). */
numeric digits 100000 /*be able to handle gihugeic numbers. */
parse arg n k . /*obtain N and K from the C.L. */
say 'combinations('n","k')=' comb(n,k) ... |
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 numbe... | #Lua | Lua |
function isPrime (n)
if n < 2 then return false end
if n < 4 then return true end
if n % 2 == 0 then return false end
for d = 3, math.sqrt(n), 2 do
if n % d == 0 then return false end
end
return true
end
function isEmirp (n)
if not isPrime(n) then return false end
local rev =... |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #zonnon | zonnon |
module Enumerations;
type
Fruits = (apple,banana,cherry);
var
deserts,i: Fruits;
begin
deserts := Fruits.banana;
writeln("ord(deserts): ",integer(deserts):2);
for i := Fruits.apple to Fruits.cherry do
writeln(integer(i):2)
end
end Enumerations.
|
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 oper... | #Factor | Factor | "" 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 oper... | #Fantom | Fantom |
a := "" // assign an empty string to 'a'
a.isEmpty // method on sys::Str to check if string is empty
a.size == 0 // what isEmpty actually checks
a == "" // alternate check for an empty string
!a.isEmpty // check that a string is not empty
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #VBScript | VBScript |
Function IsDirEmpty(path)
IsDirEmpty = False
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(path)
If objFolder.Files.Count = 0 And objFolder.SubFolders.Count = 0 Then
IsDirEmpty = True
End If
End Function
'Test
WScript.StdOut.WriteLine IsDirEmpty("C:\Temp")
WScript.S... |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #Wren | Wren | import "io" for Directory
var isEmptyDir = Fn.new { |path|
if (!Directory.exists(path)) Fiber.abort("Directory at '%(path)' does not exist.")
return Directory.list(path).count == 0
}
var path = "test"
var empty = isEmptyDir.call(path)
System.print("'%(path)' is %(empty ? "empty" : "not empty")") |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #zkl | zkl | path:="Empty"; File.isDir(path).println();
File.mkdir(path); File.isDir(path).println();
File.glob(path+"/*").println(); // show contents of directory |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #E | E | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #eC | eC | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #EchoLisp | EchoLisp | |
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 bit... | #jq | jq | # Input: an array of strings.
# Output: an object with the strings as keys, the values of which are the corresponding frequencies.
def counter:
reduce .[] as $item ( {}; .[$item] += 1 ) ;
# entropy in bits of the input string
def entropy:
(explode | map( [.] | implode ) | counter
| [ .[] | . * log ] | add) as... |
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 bit... | #Jsish | Jsish | /* Shannon entropy, in Jsish */
function values(obj:object):array {
var vals = [];
for (var key in obj) vals.push(obj[key]);
return vals;
}
function entropy(s) {
var split = s.split('');
var counter = {};
split.forEach(function(ch) {
if (!counter[ch]) counter[ch] = 1;
els... |
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 ... | #Factor | Factor | USING: arrays kernel math multiline sequences ;
IN: ethiopian-multiplication
/*
This function is built-in
: odd? ( n -- ? ) 1 bitand 1 number= ;
*/
: double ( n -- 2*n ) 2 * ;
: halve ( n -- n/2 ) 2 /i ;
: ethiopian-mult ( a b -- a*b )
[ 0 ] 2dip
[ dup 0 > ] [
[ odd? [ + ] [ drop ] if ] 2keep
... |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #REXX | REXX | /*REXX program calculates and displays the equilibrium index for a numeric array (list).*/
parse arg x /*obtain the optional arguments from CL*/
if x='' then x= copies(" 7 -7", 50) 7 /*Not specified? Then use the default.*/
say ' array list: ' space(x) ... |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Ring | Ring |
list = [-7, 1, 5, 2, -4, 3, 0]
see "equilibrium indices are : " + equilibrium(list) + nl
func equilibrium l
r = 0 s = 0 e = ""
for n = 1 to len(l)
s += l[n]
next
for i = 1 to len(l)
if r = s - r - l[i] e += string(i-1) + "," ok
r += l[i]
next
e = left(e,le... |
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... | #PHP | PHP | <?php
function eulers_sum_of_powers () {
$max_n = 250;
$pow_5 = array();
$pow_5_to_n = array();
for ($p = 1; $p <= $max_n; $p ++) {
$pow5 = pow($p, 5);
$pow_5 [$p] = $pow5;
$pow_5_to_n[$pow5] = $p;
}
foreach ($pow_5 as $n_0 => $p_0) {
foreach ($pow_5 as $n_1 => $p_1) {
if ($n_0 < $n_1) continue;
f... |
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 iterat... | #PicoLisp | PicoLisp | (de fact (N)
(if (=0 N)
1
(* N (fact (dec 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... | #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
test(-2)
test(-1)
test(0)
test(1)
test(2)
testBig("-222222222222222222222222222222222222")
testBig("-1")
testBig("0")
testBig("1")
testBig("222222222222222222222222222222222222")
}
func test(n int) {
fmt.Pri... |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Ring | Ring |
numer = 0
binomial(5,3)
see "(5,3) binomial = " + numer + nl
func binomial n, k
if k > n return nil ok
if k > n/2 k = n - k ok
numer = 1
for i = 1 to k
numer = numer * ( n - i + 1 ) / i
next
return numer
|
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Ruby | Ruby | class Integer
# binomial coefficient: n C k
def choose(k)
# n!/(n-k)!
pTop = (self-k+1 .. self).inject(1, &:*)
# k!
pBottom = (2 .. k).inject(1, &:*)
pTop / pBottom
end
end
p 5.choose(3)
p 60.choose(30) |
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 numbe... | #Maple | Maple | EmirpPrime := proc(n)
local eprime;
eprime := parse(StringTools:-Reverse(convert(n,string)));
if n <> eprime and isprime(n) and isprime(eprime) then
return n;
end if;
end proc:
EmirpsList := proc( n )
local i, values;
values := Array([]):
i := 0:
do
i := i + 1;
if... |
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 numbe... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | reverseDigits[n_Integer] := FromDigits@Reverse@IntegerDigits@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 oper... | #Forth | Forth |
\ string words operate on the address and count left on the stack by a string
\ ? means the word returns a true/false flag on the stack
: empty? ( c-addr u -- ? ) nip 0= ;
: filled? ( c-addr u -- ? ) empty? 0= ;
: ="" ( c-addr u -- ) drop 0 ; \ It's OK to copy syntax from other languages
|
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 oper... | #Fortran | Fortran | SUBROUTINE TASTE(T)
CHARACTER*(*) T !This form allows for any size.
IF (LEN(T).LE.0) WRITE(6,*) "Empty!"
IF (LEN(T).GT.0) WRITE(6,*) "Not empty!"
END
CHARACTER*24 TEXT
CALL TASTE("")
CALL TASTE("This")
TEXT = "" !Fills the entire variable wit... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #EDSAC_order_code | EDSAC order code | T64K [ set load point ]
GK [ set base address ]
ZF [ stop ]
EZPF [ begin at load point ] |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Egel | Egel | |
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 bit... | #Julia | Julia | entropy(s) = -sum(x -> x * log(2, x), count(x -> x == c, s) / length(s) for c in unique(s))
@show entropy("1223334444")
@show entropy([1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 3, 4, 5]) |
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 bit... | #Kotlin | Kotlin | // version 1.0.6
fun log2(d: Double) = Math.log(d) / Math.log(2.0)
fun shannon(s: String): Double {
val counters = mutableMapOf<Char, Int>()
for (c in s) {
if (counters.containsKey(c)) counters[c] = counters[c]!! + 1
else counters.put(c, 1)
}
val nn = s.length.toDouble()
var sum... |
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 ... | #FALSE | FALSE | [2/]h:
[2*]d:
[$2/2*-]o:
[0[@$][$o;![@@\$@+@]?h;!@d;!@]#%\%]m:
17 34m;!. {578} |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Ruby | Ruby | def eq_indices(list)
list.each_index.select do |i|
list[0...i].sum == list[i+1..-1].sum
end
end |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Rust | Rust |
extern crate num;
use num::traits::Zero;
fn equilibrium_indices(v: &[i32]) -> Vec<usize> {
let mut right = v.iter().sum();
let mut left = i32::zero();
v.iter().enumerate().fold(vec![], |mut out, (i, &el)| {
right -= el;
if left == right {
out.push(i);
}
le... |
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... | #Picat | Picat |
import sat.
main =>
X = new_list(5), X :: 1..150, decreasing_strict(X),
X[1]**5 #= sum([X[I]**5 : I in 2..5]),
solve(X), printf("%d**5 = %d**5 + %d**5 + %d**5 + %d**5", X[1], X[2], X[3], X[4], X[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 iterat... | #Piet | Piet | push 1
not
in(number)
duplicate
not // label a
pointer // pointer 1
duplicate
push 1
subtract
push 1
pointer
push 1
noop
pointer
duplicate // the next op is back at label a
push 1 // this part continues from pointer 1
noop
push 2 // label b
push 1
rot 1 2
duplicate
not
pointer // pointer 2
mult... |
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... | #Groovy | Groovy | def isOdd = { int i -> (i & 1) as boolean }
def isEven = {int i -> ! isOdd(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... | #Haskell | Haskell | Prelude> even 5
False
Prelude> even 42
True
Prelude> odd 5
True
Prelude> odd 42
False |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Run_BASIC | Run BASIC | print "binomial (5,1) = "; binomial(5, 1)
print "binomial (5,2) = "; binomial(5, 2)
print "binomial (5,3) = "; binomial(5, 3)
print "binomial (5,4) = "; binomial(5,4)
print "binomial (5,5) = "; binomial(5,5)
end
function binomial(n,k)
coeff = 1
for i = n - k + 1 to n
coeff = coeff * i
next i
for i = 1 to k
... |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Rust | Rust | fn fact(n:u32) -> u64 {
let mut f:u64 = n as u64;
for i in 2..n {
f *= i as u64;
}
return f;
}
fn choose(n: u32, k: u32) -> u64 {
let mut num:u64 = n as u64;
for i in 1..k {
num *= (n-i) as u64;
}
return num / fact(k);
}
fn main() {
println!("{}", choose(5,3));
} |
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 numbe... | #MATLAB | MATLAB |
NN=(1:1:1e6); %Natural numbers between 1 and t
pns=NN(isprime(NN)); %prime numbers
p=fliplr(str2num(fliplr(num2str(pns))));
a=pns(isprime(p)); b=p(isprime(p)); c=a-b;
emirps=NN(a(c~=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 oper... | #Free_Pascal | Free Pascal | s := ''; |
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 oper... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub IsEmpty(s As String)
If Len(s) = 0 Then
Print "String is empty"
Else
Print "String is not empty"
End If
End Sub
Dim s As String ' implicitly assigned an empty string
IsEmpty(s)
Dim t As String = "" ' explicitly assigned an empty string
IsEmpty(t)
Dim u As String = "not emp... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #EGL | EGL |
package programs;
program Empty_program type BasicProgram {}
function main()
end
end
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Eiffel | Eiffel | class
ROOT
create
make
feature
make
do
end
end |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Elena | Elena | public program()
{
} |
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 bit... | #Lambdatalk | Lambdatalk |
{def entropy
{def entropy.count
{lambda {:s :c :i}
{let { {:c {/ {A.get :i :c} {A.length :s}}}
} {* :c {log2 :c}}}}}
{def entropy.sum
{lambda {:s :c}
{- {+ {S.map {entropy.count :s :c}
{S.serie 0 {- {A.length :c} 1}}}}}}}
{lambda {:s}
{entropy.sum {A.split :s} {cdr... |
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 ... | #Forth | Forth | : even? ( n -- ? ) 1 and 0= ;
: e* ( x y -- x*y )
dup 0= if nip exit then
over 2* over 2/ recurse
swap even? if nip else + then ; |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Scala | Scala | def getEquilibriumIndex(A: Array[Int]): Int = {
val bigA: Array[BigInt] = A.map(BigInt(_))
val partialSums: Array[BigInt] = bigA.scanLeft(BigInt(0))(_+_).tail
def lSum(i: Int): BigInt = if (i == 0) 0 else partialSums(i - 1)
def rSum(i: Int): BigInt = partialSums.last - partialSums(i)
def ... |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const array integer: numList is [] (-7, 1, 5, 2, -4, 3, 0);
const func array integer: equilibriumIndex (in array integer: elements) is func
result
var array integer: indexList is 0 times 0;
local
var integer: element is 0;
var integer: index is 0;
var integer: sum is 0;... |
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... | #PicoLisp | PicoLisp | (off P)
(off S)
(for I 250
(idx
'P
(list (setq @@ (** I 5)) I)
T )
(for (J I (>= 250 J) (inc J))
(idx
'S
(list (+ @@ (** J 5)) (list I J))
T ) ) )
(println
(catch 'found
(for A (idx 'P)
(for B (idx 'S)
(T (<= (car A) (car B)))
... |
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 iterat... | #Plain_English | Plain English | A factorial is a number.
To run:
Start up.
Demonstrate input.
Write "Bye-bye!" to the console.
Wait for 1 second.
Shut down.
To demonstrate input:
Write "Enter a number: " to the console without advancing.
Read a string from the console.
If the string is empty, exit.
Convert the string to a number... |
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... | #Hoon | Hoon | |= n=@ud
?: =((mod n 2) 0)
"even"
"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... | #Icon_and_Unicon | Icon and Unicon | procedure isEven(n)
return n%2 = 0
end |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Scala | Scala | object Binomial {
def main(args: Array[String]): Unit = {
val n=5
val k=3
val result=binomialCoefficient(n,k)
println("The Binomial Coefficient of %d and %d equals %d.".format(n, k, result))
}
def binomialCoefficient(n:Int, k:Int)=fact(n) / (fact(k) * fact(n-k))
def fact(n:Int):Int... |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #Scheme | Scheme | (define (factorial n)
(define (*factorial n acc)
(if (zero? n)
acc
(*factorial (- n 1) (* acc n))))
(*factorial n 1))
(define (choose n k)
(/ (factorial n) (* (factorial k) (factorial (- n k)))))
(display (choose 5 3))
(newline) |
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 numbe... | #Modula-2 | Modula-2 | MODULE Emirp;
FROM Conversions IMPORT StrToLong;
FROM FormatString IMPORT FormatString;
FROM LongMath IMPORT sqrt;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE IsPrime(x : LONGINT) : BOOLEAN;
VAR
i : LONGINT;
u : LONGREAL;
v : LONGINT;
BEGIN
IF x<2 THEN RETURN FALSE END;
IF x=2 THE... |
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 oper... | #Frink | Frink | a = ""
if a == ""
println["empty"]
if a != ""
println["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 oper... | #FutureBasic | FutureBasic | window 1, @"Empty string", (0,0,480,270)
CFStringRef s
s = @""
if ( fn StringIsEqual( s, @"" ) ) then print @"string is empty"
if ( fn StringLength( s ) == 0 ) then print @"string is empty"
if ( len(s) == 0 ) then print @"string is empty"
print
s = @"Hello"
if ( fn StringIsEqual( s, @"" ) == NO ) then print @"s... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Elixir | Elixir | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Elm | Elm |
--Language prints the text in " "
import Html
main =
Html.text"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 bit... | #Lang5 | Lang5 | : -rot rot rot ; [] '__A set : dip swap __A swap 1 compress append '__A
set execute __A -1 extract nip ; : nip swap drop ; : sum '+ reduce ;
: 2array 2 compress ; : comb "" split ; : lensize length nip ;
: <group> #( a -- 'a )
grade subscript dup 's dress distinct strip
length 1 2array reshape swap
'A set
... |
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 bit... | #Liberty_BASIC | Liberty BASIC |
dim countOfChar( 255) ' all possible one-byte ASCII chars
source$ ="1223334444"
charCount =len( source$)
usedChar$ =""
for i =1 to len( source$) ' count which chars are used in source
ch$ =mid$( source$, i, 1)
if not( instr( usedChar$, ch$)) then usedChar$ =use... |
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 ... | #Fortran | Fortran | program EthiopicMult
implicit none
print *, ethiopic(17, 34, .true.)
contains
subroutine halve(v)
integer, intent(inout) :: v
v = int(v / 2)
end subroutine halve
subroutine doublit(v)
integer, intent(inout) :: v
v = v * 2
end subroutine doublit
function iseven(x)
logical :: i... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.