task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist)   if *envars = 0 then envars := ["HOME", "TRACE", "BLKSIZE","STRSIZE","COEXPSIZE","MSTKSIZE", "IPATH","LPATH","NOERRBUF"]   every v := !sort(envars) do write(v," = ",image(getenv(v))|"* not set *") end
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#J
J
2!:5'HOME'
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#Python
Python
from collections import deque from itertools import dropwhile, islice, takewhile from textwrap import wrap from typing import Iterable, Iterator     Digits = str # Alias for the return type of to_digits()     def esthetic_nums(base: int) -> Iterator[int]: """Generate the esthetic number sequence for a given base  ...
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...
#Elixir
Elixir
defmodule Euler do def sum_of_power(max \\ 250) do {p5, sum2} = setup(max) sk = Enum.sort(Map.keys(sum2)) Enum.reduce(Enum.sort(Map.keys(p5)), Map.new, fn p,map -> sum(sk, p5, sum2, p, map) end) end   defp setup(max) do Enum.reduce(1..max, {%{}, %{}}, fn i,{p5,sum2} -> i5 = i*i*i*i...
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...
#Neko
Neko
var factorial = function(number) { var i = 1; var result = 1;   while(i <= number) { result *= i; i += 1; }   return result; };   $print(factorial(10));
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Befunge
Befunge
&2%52**"E"+,@
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#BQN
BQN
  odd ← 2⊸|   !0 ≡ odd 12 !1 ≡ odd 31
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de euler (F Y A B H) (while (> B A) (prinl (round A) " " (round Y)) (inc 'Y (*/ H (F A Y) 1.0)) (inc 'A H) ) )   (de newtonCoolingLaw (A B) (*/ -0.07 (- B 20.) 1.0) )   (euler newtonCoolingLaw 100.0 0 100.0 2.0) (euler newtonCoolingLaw 100.0 0 100.0 5.0) (euler newtonCool...
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#PL.2FI
PL/I
test: procedure options (main); /* 3 December 2012 */   declare (x, y, z) float; declare (T0 initial (100), Tr initial (20)) float; declare k float initial (0.07); declare t fixed binary; declare h fixed binary;   x, y, z = T0; /* Step size is 2 seconds */ h = 2; put skip data (h); put ski...
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...
#Golfscript
Golfscript
;5 3 # Set up demo input {),(;{*}*}:f; # Define a factorial function .f@.f@/\@-f/
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Groovy
Groovy
def factorial = { x -> assert x > -1 x == 0 ? 1 : (1..x).inject(1G) { BigInteger product, BigInteger factor -> product *= factor } }   def combinations = { n, k -> assert k >= 0 assert n >= k factorial(n).intdiv(factorial(k)*factorial(n-k)) }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Xojo
Xojo
Function fibo(n As Integer) As UInt64   Dim noOne As UInt64 = 1 Dim noTwo As UInt64 = 1 Dim sum As UInt64   For i As Integer = 3 To n sum = noOne + noTwo noTwo = noOne noOne = sum Next   Return noOne End Function
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Ruby
Ruby
def entropy(s) counts = s.each_char.tally size = s.size.to_f counts.values.reduce(0) do |entropy, count| freq = count / size entropy - freq * Math.log2(freq) end end   s = File.read(__FILE__) p entropy(s)  
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Rust
Rust
use std::fs::File; use std::io::{Read, BufReader};   fn entropy<I: IntoIterator<Item = u8>>(iter: I) -> f32 { let mut histogram = [0u64; 256]; let mut len = 0u64;   for b in iter { histogram[b as usize] += 1; len += 1; }   histogram .iter() .cloned() .filter(|...
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Sidef
Sidef
func entropy(s) { [0, s.chars.freq.values.map {|c| var f = c/s.len f * f.log2 }... ]«-» }   say entropy(File(__FILE__).open_r.slurp)
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Tcl
Tcl
proc entropy {str} { set log2 [expr log(2)] foreach char [split $str ""] {dict incr counts $char} set entropy 0.0 foreach count [dict values $counts] { set freq [expr {$count / double([string length $str])}] set entropy [expr {$entropy - $freq * log($freq)/$log2}] } return $entropy }   puts [f...
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#C
C
#include <stdio.h> #include <math.h>   #define C 7 typedef struct { double x, y; } pt;   pt zero(void) { return (pt){ INFINITY, INFINITY }; }   // should be INFINITY, but numeric precision is very much in the way int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; }   pt neg(pt p) { return (pt){ p.x, -p.y }; }   pt d...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Factor
Factor
IN: scratchpad { "sun" "mon" "tue" "wed" "thur" "fri" "sat" } <enum>   --- Data stack: T{ enum f ~array~ } IN: scratchpad [ 1 swap at ] [ keys ] bi   --- Data stack: "mon" { 0 1 2 3 4 5 6 }
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Fantom
Fantom
  // create an enumeration with named constants enum class Fruits { apple, banana, orange }  
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Forth
Forth
0 CONSTANT apple 1 CONSTANT banana 2 CONSTANT cherry ...
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#11l
11l
V n = 64   F pow2(x) R UInt64(1) << x   F evolve(UInt64 =state; rule) L 10 V b = UInt64(0) L(q) (7 .. 0).step(-1) V st = state b [|]= (st [&] 1) << q state = 0 L(i) 0 .< :n V t = ((st >> (i - 1)) [|] (st << (:n + 1 - i))) [&] 7 I (rule [&] po...
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...
#8th
8th
"" var, str
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#AArch64_Assembly
AArch64 Assembly
str: .asciz ""
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
Elliptic Curve Digital Signature Algorithm
Elliptic curves. An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), together with a special point 𝒪 called the point at infinity. The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp, which satisfy the above defining eq...
#Go
Go
package main   import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "encoding/binary" "fmt" "log" )   func check(err error) { if err != nil { log.Fatal(err) } }   func main() { priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) check(err) ...
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...
#AutoHotkey
AutoHotkey
MsgBox % isDir_empty(A_ScriptDir)?"true":"false"   isDir_empty(p) { Loop, %p%\* , 1 return 0 return 1 }
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#AWK
AWK
  # syntax: GAWK -f EMPTY_DIRECTORY.AWK BEGIN { n = split("C:\\TEMP3,C:\\NOTHERE,C:\\AWK\\FILENAME,C:\\WINDOWS",arr,",") for (i=1; i<=n; i++) { printf("'%s' %s\n",arr[i],is_dir(arr[i])) } exit(0) } function is_dir(path, cmd,dots,entries,msg,rec,valid_dir) { cmd = sprintf("DIR %s 2>NUL",path) ...
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#68000_Assembly
68000 Assembly
forever: MOVE.B D0,$300001 JMP forever
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#8051_Assembly
8051 Assembly
ORG RESET jmp $
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Go
Go
package main   func main() { s := "immutable" s[0] = 'a' }
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Haskell
Haskell
pi = 3.14159 msg = "Hello World"
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Icon_and_Unicon
Icon and Unicon
$define "1234"
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#J
J
B=: A=: 'this is a test' A=: '*' 2 3 5 7} A A th** *s*a test B this is a test
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#BASIC
BASIC
10 DEF FN L(X)=LOG(X)/LOG(2) 20 S$="1223334444" 30 U$="" 40 FOR I=1 TO LEN(S$) 50 K=0 60 FOR J=1 TO LEN(U$) 70 IF MID$(U$,J,1)=MID$(S$,I,1) THEN K=1 80 NEXT J 90 IF K=0 THEN U$=U$+MID$(S$,I,1) 100 NEXT I 110 DIM R(LEN(U$)-1) 120 FOR I=1 TO LEN(U$) 130 C=0 140 FOR J=1 TO LEN(S$) 150 IF MID$(U$,I,1)=MID$(S$,J,1) THEN C=C...
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...
#BBC_BASIC
BBC BASIC
REM >entropy PRINT FNentropy("1223334444") END : DEF FNentropy(x$) LOCAL unique$, count%, n%, ratio(), u%, i%, j% unique$ = "" n% = LEN x$ FOR i% = 1 TO n% IF INSTR(unique$, MID$(x$, i%, 1)) = 0 THEN unique$ += MID$(x$, i%, 1) NEXT u% = LEN unique$ DIM ratio(u% - 1) FOR i% = 1 TO u% count% = 0 FOR j% = 1 TO n% ...
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 ...
#Bracmat
Bracmat
( (halve=.div$(!arg.2)) & (double=.2*!arg) & (isEven=.mod$(!arg.2):0) & ( mul = a b as bs newbs result .  !arg:(?as.?bs) & whl ' ( !as:? (%@:~1:?a) & !as halve$!a:?as & !bs:? %@?b & !bs double$!b:?bs ) & :?newbs & whl ' ( !as:%@?a ?a...
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} ...
#Factor
Factor
USE: math.vectors : accum-left ( seq id quot -- seq ) accumulate nip ; inline : accum-right ( seq id quot -- seq ) [ <reversed> ] 2dip accum-left <reversed> ; inline : equilibrium-indices ( seq -- inds ) 0 [ + ] [ accum-left ] [ accum-right ] 3bi [ = ] 2map V{ } swap dup length iota [ [ suffix ] curry [ ] if ] 2eac...
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} ...
#Fortran
Fortran
program Equilibrium implicit none   integer :: array(7) = (/ -7, 1, 5, 2, -4, 3, 0 /)   call equil_index(array)   contains   subroutine equil_index(a) integer, intent(in) :: a(:) integer :: i   do i = 1, size(a) if(sum(a(1:i-1)) == sum(a(i+1:size(a)))) write(*,*) i end do   end subroutine end program
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Java
Java
System.getenv("HOME") // get env var System.getenv() // get the entire environment as a Map of keys to values
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#JavaScript
JavaScript
var shell = new ActiveXObject("WScript.Shell"); var env = shell.Environment("PROCESS"); WScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT'));
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Joy
Joy
"HOME" getenv.
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#Raku
Raku
use Lingua::EN::Numbers;   sub esthetic($base = 10) { my @s = ^$base .map: -> \s { ((s - 1).base($base) if s > 0), ((s + 1).base($base) if s < $base - 1) }   flat [ (1 .. $base - 1)».base($base) ], { [ flat .map: { $_ xx * Z~ flat @s[.comb.tail.parse-base($base)] } ] } … * }   for 2 .. 16 -> $b ...
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...
#ERRE
ERRE
PROGRAM EULERO   CONST MAX=250   !$DOUBLE   FUNCTION POW5(X) POW5=X*X*X*X*X END FUNCTION   !$INCLUDE="PC.LIB"   BEGIN CLS FOR X0=1 TO MAX DO FOR X1=1 TO X0 DO FOR X2=1 TO X1 DO FOR X3=1 TO X2 DO LOCATE(3,1) PRINT(X0;X1;X2;X3) SUM=POW5(X0)+POW5(X1)+POW5(X2)+P...
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...
#Nemerle
Nemerle
using System; using System.Console;   module Program { Main() : void { WriteLine("Factorial of which number?"); def number = long.Parse(ReadLine()); WriteLine("Using Fold : Factorial of {0} is {1}", number, FactorialFold(number)); WriteLine("Using Match: Factorial of {0} is {1}", number, Fac...
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...
#Bracmat
Bracmat
( ( even = . @( !arg  :  ? [-2 ( 0 | 2 | 4 | 6 | 8 ) ) ) & (odd=.~(even$!arg)) & ( eventest = . out $ (!arg is (even$!arg&|not) even) ) & ( oddtest = . out $ (!arg is (odd$!arg&|not) odd) )...
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...
#Brainf.2A.2A.2A
Brainf***
,[>,----------] Read until newline ++< Get a 2 and move into position [->-[>+>>]> Do [+[-<+>]>+>>] divmod <<<<<] magic >[-]<++++++++ Clear and get an 8 [>++++++<-] to get a 48 >[>+<-]>. to get n % 2 to ASCII and print
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#PowerShell
PowerShell
  function euler (${f}, ${y}, $y0, $t0, $tEnd) { function f-euler ($tn, $yn, $h) { $yn + $h*(f $tn $yn) } function time ($t0, $h, $tEnd) { $end = [MATH]::Floor(($tEnd - $t0)/$h) foreach ($_ in 0..$end) { $_*$h + $t0 } } $time = time $t0 10 $tEnd $time5 = time $t0 5 $tE...
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...
#GW-BASIC
GW-BASIC
10 REM BINOMIAL CALCULATOR 20 INPUT "N? ", N 30 INPUT "P? ", P 40 GOSUB 70 50 PRINT C 60 END 70 C = 0 80 IF N < 0 OR P<0 OR P > N THEN RETURN 90 IF P < N\2 THEN P = N - P 100 C = 1 110 FOR I = N TO P+1 STEP -1 120 C=C*I 130 NEXT I 140 FOR I = 1 TO N-P 150 C=C/I 160 NEXT I 170 RETURN
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#XPL0
XPL0
func Fib1(N); \Return Nth Fibonacci number using iteration int N; int Fn, F0, F1; [F0:= 0; F1:= 1; Fn:= N; while N > 1 do [Fn:= F0 + F1; F0:= F1; F1:= Fn; N:= N-1; ]; return Fn; ];   func Fib2(N); \Return Nth Fibonacci number using recursion int N; return if N < 2 then N el...
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Vlang
Vlang
import os import math   fn main() { println("Binary file entropy: ${entropy(os.args[0])?}") }   fn entropy(file string) ?f64 { d := os.read_bytes(file)?   mut f := [256]f64{} for b in d { f[b]++ } mut hm := 0.0 for c in f { if c > 0 { hm += c * math.log2(c) ...
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Wren
Wren
import "os" for Process import "io" for File   var args = Process.allArguments var s = File.read(args[1]).trim() var m = {} for (c in s) { var d = m[c] m[c] = (d) ? d + 1 : 1 } var hm = 0 for (k in m.keys) { var c = m[k] hm = hm + c * c.log2 } var l = s.count System.print(l.log2 - hm/l)
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#zkl
zkl
fcn entropy(text){ text.pump(Void,fcn(c,freq){ c=c.toAsc(); freq[c]=freq[c]+1; freq } .fp1((0).pump(256,List,(0.0).create.fp(0)).copy())) .filter() // remove all zero entries .apply('/(text.len())) // (num of char)/len .apply(fcn(p){-p*p.log()}) // |p*ln(p)| .sum(0.0)/(2.0).log(); /...
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...
#11l
11l
F reversed(Int =n) V result = 0 L result = 10 * result + n % 10 n I/= 10 I n == 0 R result   V limit = 1'000'000 V is_prime = [0B] * 2 [+] [1B] * (limit - 1) L(n) 0 .< Int(limit ^ 0.5 + 1.5) I is_prime[n] L(i) (n * n .< limit + 1).step(n) is_prime[i] = 0B   F is_emirp(...
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#C.2B.2B
C++
#include <cmath> #include <iostream>   using namespace std;   // define a type for the points on the elliptic curve that behaves // like a built in type. class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; // the 'b' in y^2 = x^3 + a * x + b ...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Fortran
Fortran
enum, bind(c) enumerator :: one=1, two, three, four, five enumerator :: six, seven, nine=9 end enum
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Free_Pascal
Free Pascal
' FB 1.05.0 Win64   Enum Animals Cat Dog Zebra End Enum   Enum Dogs Bulldog = 1 Terrier = 2 WolfHound = 4 End Enum   Print Cat, Dog, Zebra Print Bulldog, Terrier, WolfHound Sleep
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Enum Animals Cat Dog Zebra End Enum   Enum Dogs Bulldog = 1 Terrier = 2 WolfHound = 4 End Enum   Print Cat, Dog, Zebra Print Bulldog, Terrier, WolfHound Sleep
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#C
C
#include <stdio.h> #include <limits.h>   typedef unsigned long long ull; #define N (sizeof(ull) * CHAR_BIT) #define B(x) (1ULL << (x))   void evolve(ull state, int rule) { int i, p, q, b;   for (p = 0; p < 10; p++) { for (b = 0, q = 8; q--; ) { ull st = state; b |= (st&1) << q;   for (state = i = 0; i < N;...
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#C.2B.2B
C++
#include <bitset> #include <stdio.h>   #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x)))   void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( ...
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...
#ACL2
ACL2
(= (length str) 0)
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Action.21
Action!
PROC CheckIsEmpty(CHAR ARRAY s) PrintF("'%S' is empty? ",s) IF s(0)=0 THEN PrintE("True") ELSE PrintE("False") FI RETURN   PROC Main() CHAR ARRAY str1,str2   str1="" str2="text"   CheckIsEmpty(str1) CheckIsEmpty(str2) RETURN
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
Elliptic Curve Digital Signature Algorithm
Elliptic curves. An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), together with a special point 𝒪 called the point at infinity. The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp, which satisfy the above defining eq...
#Julia
Julia
module ToyECDSA   using SHA   import Base.in, Base.==, Base.+, Base.*   export ECDSA_Key, ECDSA_Public_Key, genkey, ECDSA_sign, isverifiedECDSA   # T will be BigInt in most applications struct CurveFP{T} p::T a::T b::T CurveFP(p, a::T, b::T) where T <: Number = new{T}(p, a, b) end   struct PointEC{T} ...
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
Elliptic Curve Digital Signature Algorithm
Elliptic curves. An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), together with a special point 𝒪 called the point at infinity. The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp, which satisfy the above defining eq...
#Nim
Nim
import math, random, strformat   const MaxN = 1073741789 # Maximum modulus. MaxR = MaxN + 65536 # Maximum order "g". Infinity = int64.high # Symbolic infinity.   type   Point = tuple[x, y: int64]   Curve = object a, b: int64 n: int64 g: Point r: int64   Pair = tuple[a, b: int64] ...
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...
#BaCon
BaCon
FUNCTION check$(dir$)   IF FILEEXISTS(dir$) THEN RETURN IIF$(LEN(WALK$(dir$, 127, ".+", FALSE)), " is NOT empty.", " is empty." ) ELSE RETURN " doesn't exist." ENDIF   ENDFUNCTION   dir$ = "bla" PRINT "Directory '", dir$, "'", check$(dir$)   dir$ = "/mnt" PRINT "Directory '", dir$, "'", chec...
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...
#Batch_File
Batch File
@echo off if "%~1"=="" exit /b 3 set "samp_path=%~1" set "tst_var="   %== Store the current directory of the CMD ==% for /f %%T in ('cd') do set curr_dir=%%T   %== Go to the samp_path ==% cd %samp_path% 2>nul ||goto :folder_not_found   %== The current directory is now samp_path ==% %== Scan what is inside samp_path...
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#8086_Assembly
8086 Assembly
.model small ;.exe file .stack 1024 ;this value doesn't matter, I chose this arbitrarily .data ;not needed in an empty program .code mov ax,4C00h int 21h ;exit this program and return to MS-DOS
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#AArch64_Assembly
AArch64 Assembly
.text .global _start   _start: mov x0, #0 mov x8, #93 svc #0
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Java
Java
final int immutableInt = 4; int mutableInt = 4; mutableInt = 6; //this is fine immutableInt = 6; //this is an error
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#JavaScript
JavaScript
const pi = 3.1415; const msg = "Hello World";
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#jq
jq
  ["a", "b"] as $a | $a[0] = 1 as $b | $a
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Julia
Julia
const x = 1 x = π # ERROR: invalid ridefinition of constant x
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#BQN
BQN
H ← -∘(+´⊢×2⋆⁼⊢)∘((+˝⊢=⌜⍷)÷≠)   H "1223334444"
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Burlesque
Burlesque
blsq ) "1223334444"F:u[vv^^{1\/?/2\/LG}m[?*++ 1.8464393446710157
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#BQN
BQN
Double ← 2⊸× Halve ← ⌊÷⟜2 Odd ← 2⊸|   EMul ← { times ← ↕⌈2⋆⁼𝕨 +´(Odd Halve⍟times 𝕨)/Double⍟times 𝕩 }   17 EMul 34
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub equilibriumIndices (a() As Integer, b() As Integer) If UBound(a) = -1 Then Return '' empty array   Dim sum As Integer = 0 Dim count As Integer = 0 For i As Integer = LBound(a) To UBound(a) : sum += a(i) : Next Dim sumLeft As Integer = 0, sumRight As Integer = 0   For i As Integer =...
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#jq
jq
env.HOME
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#jsish
jsish
/* Environment variables, in Jsi */ puts(Util.getenv("HOME")); var environment = Util.getenv(); puts(environment.PATH);
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Julia
Julia
@show ENV["PATH"] @show ENV["HOME"] @show ENV["USER"]
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#K
K
_getenv "HOME"
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#REXX
REXX
/*REXX pgm lists a bunch of esthetic numbers in bases 2 ──► 16, & base 10 in two ranges.*/ parse arg baseL baseH range /*obtain optional arguments from the CL*/ if baseL=='' | baseL=="," then baseL= 2 /*Not specified? Then use the default.*/ if baseH=='' | baseH=="," then baseH=16 ...
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...
#F.23
F#
  //Find 4 integers whose 5th powers sum to the fifth power of an integer (Quickly!) - Nigel Galloway: April 23rd., 2015 let G = let GN = Array.init<float> 250 (fun n -> (float n)**5.0) let rec gng (n, i, g, e) = match (n, i, g, e) with | (250,_,_,_) -> "No Solution Found" | (_,250,_,_) -> gng (n+1, n+1...
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...
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols nobinary   numeric digits 64 -- switch to exponential format when numbers become larger than 64 digits   say 'Input a number: \-' say do n_ = long ask -- Gets the number, must be an integer   say n_'! =' factorial(n_) '(using iteration)' ...
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...
#Burlesque
Burlesque
2.%
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#PureBasic
PureBasic
Define.d Prototype.d Func(Time, t)   Procedure.d Euler(*F.Func, y0, a, b, h) Protected y=y0, t=a While t<=b PrintN(RSet(StrF(t,3),7)+" "+RSet(StrF(y,3),7)) y + h * *F(t,y) t + h Wend EndProcedure   Procedure.d newtonCoolingLaw(Time, t) ProcedureReturn -0.07*(t-20) EndProcedure     If OpenConsole() ...
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...
#Haskell
Haskell
  choose :: (Integral a) => a -> a -> a choose n k = product [k+1..n] `div` product [1..n-k]  
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#HicEst
HicEst
WRITE(Messagebox) BinomCoeff( 5, 3) ! displays 10   FUNCTION factorial( n ) factorial = 1 DO i = 1, n factorial = factorial * i ENDDO END   FUNCTION BinomCoeff( n, k ) BinomCoeff = factorial(n)/factorial(n-k)/factorial(k) END
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#XQuery
XQuery
declare function local:fib($n as xs:integer) as xs:integer { if($n < 2) then $n else local:fib($n - 1) + local:fib($n - 2) };
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Ada
Ada
with Ada.Text_IO, Miller_Rabin;   procedure Emirp_Gen is   type Num is range 0 .. 2**63-1; -- maximum for the gnat Ada compiler   MR_Iterations: constant Positive := 25; -- the probability Pr[Is_Prime(N, MR_Iterations) = Probably_Prime] -- is 1 for prime N and < 4**(-MR_Iterations) for composed N   ...
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#D
D
import std.stdio, std.math, std.string;   enum bCoeff = 7;   struct Pt { double x, y;   @property static Pt zero() pure nothrow @nogc @safe { return Pt(double.infinity, double.infinity); }   @property bool isZero() const pure nothrow @nogc @safe { return x > 1e20 || x < -1e20; }   ...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#FutureBasic
FutureBasic
window 1, @"Enumerations", (0,0,480,270)   begin enum 1 _apple _banana _cherry end enum   begin enum _appleExplicit = 10 _bananaExplicit = 15 _cherryExplicit = 30 end enum   print "_apple = "; _apple print "_banana = "; _banana print "_cherry = "; _cherry print print "_appleExplicit = "; _appleExplicit print "_banan...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Go
Go
const ( apple = iota banana cherry )
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Groovy
Groovy
enum Fruit { apple, banana, cherry }   enum ValuedFruit { apple(1), banana(2), cherry(3); def value ValuedFruit(val) {value = val} String toString() { super.toString() + "(${value})" } }   println Fruit.values() println ValuedFruit.values()
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#D
D
import std.stdio, std.range, std.typecons;   struct CellularRNG { private uint current; private immutable uint rule; private ulong state;   this(in ulong state_, in uint rule_) pure nothrow @safe @nogc { this.state = state_; this.rule = rule_; popFront; }   public enum bo...
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...
#Ada
Ada
procedure Empty_String is   function Is_Empty(S: String) return Boolean is begin return S = ""; -- test that S is empty end Is_Empty;   Empty: String := ""; -- Assign empty string XXXXX: String := "Not Empty";   begin if (not Is_Empty(Empty)) or Is_Empty(XXXXX) then raise Program_Error wit...
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...
#Aime
Aime
text s; s = ""; if (length(s) == 0) { ... } if (length(s) != 0) { .... }
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
Elliptic Curve Digital Signature Algorithm
Elliptic curves. An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), together with a special point 𝒪 called the point at infinity. The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp, which satisfy the above defining eq...
#Perl
Perl
# 20200828 added Perl programming solution   use strict; use warnings;   use Crypt::EC_DSA;   my $ecdsa = new Crypt::EC_DSA;   my ($pubkey, $prikey) = $ecdsa->keygen;   print "Message: ", my $msg = 'Rosetta Code', "\n";   print "Private Key :\n$prikey \n"; print "Public key  :\n", $pubkey->x, "\n", $pubkey->y, "\n";   ...
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...
#BBC_BASIC
BBC BASIC
IF FNisdirectoryempty("C:\") PRINT "C:\ is empty" ELSE PRINT "C:\ is not empty" IF FNisdirectoryempty("C:\temp") PRINT "C:\temp is empty" ELSE PRINT "C:\temp is not empty" END   DEF FNisdirectoryempty(dir$) LOCAL dir%, sh%, res% DIM dir% LOCAL 317 IF RIGHT$(dir$)<>"\" dir$ += "...
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...
#C
C
#include <stdio.h> #include <dirent.h> #include <string.h>   int dir_empty(const char *path) { struct dirent *ent; int ret = 1;   DIR *d = opendir(path); if (!d) { fprintf(stderr, "%s: ", path); perror(""); return -1; }   while ((ent = readdir(d))) { if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, ...
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#ABAP
ABAP
  report z_empty_program.  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Action.21
Action!
 
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Kotlin
Kotlin
// version 1.1.0   // constant top level property const val N = 5   // read-only top level property val letters = listOf('A', 'B', 'C', 'D', 'E') // 'listOf' creates here a List<Char) which is immutable   class MyClass { // MyClass is effectively immutable because it's only property is read-only /...