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/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 ...
#VBScript
VBScript
class generator dim t1 dim t2 dim tn dim cur_overflow   Private Sub Class_Initialize cur_overflow = false t1 = ccur(0) t2 = ccur(1) tn = ccur(t1 + t2) end sub   public default property get generated on error resume next   generated = ccur(tn) if err.number <> 0 then generated = cdbl(tn) cur_...
http://rosettacode.org/wiki/Equal_prime_and_composite_sums
Equal prime and composite sums
Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes. P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ... P = 2, 5, 10, 17, 28, etc. Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites. C = (4...
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N is prime int N, I; [if N <= 2 then return N = 2; if (N&1) = 0 then \even >2\ return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   int Cnt, N, M, SumP, SumC, NumP, NumC; [Cnt:= 0; N:= 1; M:= 1; NumP:= 2; NumC:= ...
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
#Ada
Ada
with Ada.Text_Io; with Ada.Command_Line; with Ada.Numerics.Elementary_Functions;   procedure Entropy is use Ada.Text_Io;   type Hist_Type is array (Character) of Natural;   function Log_2 (V : Float) return Float is use Ada.Numerics.Elementary_Functions; begin return Log (V) / Log (2.0); end ...
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 ...
#ActionScript
ActionScript
function Divide(a:Number):Number { return ((a-(a%2))/2); } function Multiply(a:Number):Number { return (a *= 2); } function isEven(a:Number):Boolean { if (a%2 == 0) { return (true); } else { return (false); } } function Ethiopian(left:Number, right:Number) { var r:Number = 0; trace(left+" "+right); whil...
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} ...
#ABAP
ABAP
REPORT equilibrium_index.   TYPES: y_i TYPE STANDARD TABLE OF i WITH EMPTY KEY.   cl_demo_output=>display( REDUCE y_i( LET sequences = VALUE y_i( ( -7 ) ( 1 ) ( 5 ) ( 2 ) ( -4 ) ( 3 ) ( 0 ) ) total_sum = REDUCE #( INIT sum = 0 ...
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Ada
Ada
with Ada.Environment_Variables; use Ada.Environment_Variables; with Ada.Text_Io; use Ada.Text_Io;   procedure Print_Path is begin Put_Line("Path : " & Value("PATH")); end Print_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
#ALGOL_68
ALGOL 68
print((getenv("HOME"), new line))
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
#APL
APL
  ⎕ENV 'HOME' HOME /home/russtopia  
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...
#J
J
isesthetic=: 10&$: :(1 */ .=2 |@-/\ #.inv)"0   gen=: {{r=.$k=.1 while.y>#r do. r=.r,k#~u k k=.1+({:k)+i.2*#k end.y{.r}}
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...
#AWK
AWK
  # syntax: GAWK -f EULERS_SUM_OF_POWERS_CONJECTURE.AWK BEGIN { start_int = systime() main() printf("%d seconds\n",systime()-start_int) exit(0) } function main( sum,s1,x0,x1,x2,x3) { for (x0=1; x0<=250; x0++) { for (x1=1; x1<=x0; x1++) { for (x2=1; x2<=x1; x2++) { for (x3=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...
#Microsoft_Small_Basic
Microsoft Small Basic
'Factorial - smallbasic - 05/01/2019 For n = 1 To 25 f = 1 For i = 1 To n f = f * i EndFor TextWindow.WriteLine("Factorial(" + n + ")=" + f) EndFor
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...
#ALGOL-M
ALGOL-M
  BEGIN   % RETURN 1 IF EVEN, OTHERWISE 0 % INTEGER FUNCTION EVEN(I); INTEGER I; BEGIN EVEN := 1 - (I - 2 * (I / 2)); END;   % TEST THE ROUTINE % INTEGER K; FOR K := 1 STEP 3 UNTIL 10 DO WRITE(K," IS ", IF EVEN(K) = 1 THEN "EVEN" ELSE "ODD");   END
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#ALGOL_W
ALGOL W
begin  % the Algol W standard procedure odd returns true if its integer  %  % parameter is odd, false if it is even  % for i := 1, 1702, 23, -26 do begin write( i, " is ", if odd( i ) then "odd" else "even" ) end for_i end.
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...
#J
J
NB.*euler a Approximates Y(t) in Y'(t)=f(t,Y) with Y(a)=Y0 and t=a..b and step size h. euler=: adverb define 'Y0 a b h'=. 4{. y t=. i.@>:&.(%&h) b - a Y=. (+ h * u)^:(<#t) Y0 t,.Y )   ncl=: _0.07 * -&20 NB. Newton's Cooling Law  
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...
#Java
Java
  public class Euler { private static void euler (Callable f, double y0, int a, int b, int h) { int t = a; double y = y0; while (t < b) { System.out.println ("" + t + " " + y); t += h; y += h * f.compute (t, y); } System.out.println ("DONE"); }   public static void main (Stri...
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...
#C.23
C#
using System;   namespace BinomialCoefficients { class Program { static void Main(string[] args) { ulong n = 1000000, k = 3; ulong result = biCoefficient(n, k); Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result); ...
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 ...
#Vedit_macro_language
Vedit macro language
:FIBONACCI: #11 = 0 #12 = 1 Repeat(#1) { #10 = #11 + #12 #11 = #12 #12 = #10 } Return(#11)
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
#ALGOL_68
ALGOL 68
BEGIN # calculate the shannon entropy of a string # PROC shannon entropy = ( STRING s )REAL: BEGIN INT string length = ( UPB s - LWB s ) + 1; # count the occurances of each character # [ 0 : max abs char ]INT char count; FOR char pos FROM LWB ch...
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 ...
#Ada
Ada
  with ada.text_io;use ada.text_io;   procedure ethiopian is function double (n : Natural) return Natural is (2*n); function halve (n : Natural) return Natural is (n/2); function is_even (n : Natural) return Boolean is (n mod 2 = 0);   function mul (l, r : Natural) return Natural is (if l = 0 then 0 elsif...
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} ...
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   INT FUNC SumRange(INT ARRAY a INT first,last) INT sum INT i   sum=0 FOR i=first TO last DO sum==+a(i) OD RETURN(sum)   PROC EquilibriumIndices(INT...
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} ...
#Ada
Ada
with Ada.Containers.Vectors;   generic type Index_Type is range <>; type Element_Type is private; Zero : Element_Type; with function "+" (Left, Right : Element_Type) return Element_Type is <>; with function "-" (Left, Right : Element_Type) return Element_Type is <>; with function "=" (Left, Right : El...
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
#AppleScript
AppleScript
  tell application "Finder" to get name of 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
#Arturo
Arturo
print ["path:" env\PATH] print ["user:" env\USER] print ["home:" 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
#AutoHotkey
AutoHotkey
EnvGet, OutputVar, Path MsgBox, %OutputVar%
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...
#Java
Java
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream;   public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); }   private static boolean isEsthetic(long n, long b) { if (n == 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...
#BCPL
BCPL
  GET "libhdr"   LET solve() BE { LET pow5 = VEC 249 LET sum = ?   FOR i = 1 TO 249 pow5!i := i * i * i * i * i   FOR w = 4 TO 249 FOR x = 3 TO w - 1 FOR y = 2 TO x - 1 FOR z = 1 TO y - 1 { sum := pow5!w + pow5!x + pow5!y + pow5!z ...
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...
#min
min
((dup 0 ==) 'succ (dup pred) '* linrec) :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...
#AntLang
AntLang
odd: {x mod 2} even: {1 - x mod 2}
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...
#APL
APL
2|28 0 2|37 1
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...
#JavaScript
JavaScript
  // Function that takes differential-equation, initial condition, // ending x, and step size as parameters function eulersMethod(f, x1, y1, x2, h) { // Header console.log("\tX\t|\tY\t"); console.log("------------------------------------");   // Initial Variables var x=x1, y=y1;   // While we're not done yet // ...
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...
#C.2B.2B
C++
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; }   double binomial...
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 ...
#Visual_Basic
Visual Basic
Sub fibonacci() Const n = 139 Dim i As Integer Dim f1 As Variant, f2 As Variant, f3 As Variant 'for Decimal f1 = CDec(0): f2 = CDec(1) 'for Decimal setting Debug.Print "fibo("; 0; ")="; f1 Debug.Print "fibo("; 1; ")="; f2 For i = 2 To n f3 = f1 + f2 Debug.Print "fibo("; i; "...
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
#AutoHotkey
AutoHotkey
FileRead, var, *C %A_ScriptFullPath% MsgBox, % Entropy(var)   Entropy(n) { a := [], len := StrLen(n), m := n while StrLen(m) { s := SubStr(m, 1, 1) m := RegExReplace(m, s, "", c) a[s] := c } for key, val in a { m := Log(p := val / len) e -= p * m / Log(2) } ...
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#AWK
AWK
  BEGIN{FS="" RS="\x04"#EOF getline<"entropy.awk" for(i=1;i<=NF;i++)H[$i]++ for(i in H)E-=(h=H[i]/NF)*log(h) print "bytes ",NF," entropy ",E/log(2) exit}
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#11l
11l
T.enum TokenCategory NAME KEYWORD CONSTANT TEST_CATEGORY = 10
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 ...
#Aime
Aime
void halve(integer &x) { x >>= 1; }   void double(integer &x) { x <<= 1; }   integer iseven(integer x) { return (x & 1) == 0; }   integer ethiopian(integer plier, integer plicand, integer tutor) { integer result;   result = 0;   if (tutor) { o_form("ethiopian multiplication of ~ by ~\n",...
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} ...
#Aime
Aime
list eqindex(list l) { integer e, i, s, sum; list x;   s = sum = 0; l.ucall(add_i, 1, sum); for (i, e in l) { if (s * 2 + e == sum) { x.append(i); } s += e; }   x; }   integer main(void) { list(-7, 1, 5, 2, -4, 3, 0).eqindex.ucall(o_, 0, "\n");   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} ...
#ALGOL_68
ALGOL 68
MODE YIELDINT = PROC(INT)VOID;   PROC gen equilibrium index = ([]INT arr, YIELDINT yield)VOID: ( INT sum := 0; FOR i FROM LWB arr TO UPB arr DO sum +:= arr[i] OD;   INT left:=0, right:=sum; FOR i FROM LWB arr TO UPB arr DO right -:= arr[i]; IF left = right THEN yield(i) FI; ...
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
#AutoIt
AutoIt
ConsoleWrite("# Environment:" & @CRLF)   Local $sEnvVar = EnvGet("LANG") ConsoleWrite("LANG : " & $sEnvVar & @CRLF)   ShowEnv("SystemDrive") ShowEnv("USERNAME")   Func ShowEnv($N) ConsoleWrite( StringFormat("%-12s : %s\n", $N, EnvGet($N)) ) EndFunc ;==>ShowEnv
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
#AWK
AWK
$ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["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
#BASIC
BASIC
x$ = ENVIRON$("path") PRINT x$
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...
#JavaScript
JavaScript
function isEsthetic(inp, base = 10) { let arr = inp.toString(base).split(''); if (arr.length == 1) return false; for (let i = 0; i < arr.length; i++) arr[i] = parseInt(arr[i], base); for (i = 0; i < arr.length-1; i++) if (Math.abs(arr[i]-arr[i+1]) !== 1) return false; return true; }   function collect...
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...
#Bracmat
Bracmat
0:?x0 & whl ' ( 1+!x0:<250:?x0 & out$(x0 !x0) & 0:?x1 & whl ' ( 1+!x1:~>!x0:?x1 & out$(x0 !x0 x1 !x1) & 0:?x2 & whl ' ( 1+!x2:~>!x1:?x2 & 0:?x3 & whl ' ( 1+!x3:~>!x2:?x3 & (!x0^5+!x1^5+!x2^5+!x3^5)^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...
#MiniScript
MiniScript
factorial = function(n) result = 1 for i in range(2,n) result = result * i end for return result end function   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...
#AppleScript
AppleScript
set L to {3, 2, 1, 0, -1, -2, -3}   set evens to {} set odds to {}   repeat with x in L if (x mod 2 = 0) then set the end of evens to x's contents else set the end of odds to x's contents end if end repeat   return {even:evens, odd:odds}
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...
#jq
jq
# euler_method takes a filter (df), initial condition # (x1,y1), ending x (x2), and step size as parameters; # it emits the y values at each iteration. # df must take [x,y] as its input. def euler_method(df; x1; y1; x2; h): h as $h | [x1, y1] | recurse( if ((.[0] < x2 and x1 < x2) or (.[0] > x2...
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...
#Julia
Julia
euler(f::Function, T::Number, t0::Int, t1::Int, h::Int) = collect(begin T += h * f(T); T end for t in t0:h:t1)   # Prints a series of arbitrary values in a tabular form, left aligned in cells with a given width tabular(width, cells...) = println(join(map(s -> rpad(s, width), cells)))   # prints the table according to t...
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Clojure
Clojure
(defn binomial-coefficient [n k] (let [rprod (fn [a b] (reduce * (range a (inc b))))] (/ (rprod (- n k -1) n) (rprod 1 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...
#CoffeeScript
CoffeeScript
  binomial_coefficient = (n, k) -> result = 1 for i in [0...k] result *= (n - i) / (i + 1) result   n = 5 for k in [0..n] console.log "binomial_coefficient(#{n}, #{k}) = #{binomial_coefficient(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 ...
#Visual_Basic_.NET
Visual Basic .NET
Function Fib(ByVal n As Integer) As Decimal Dim fib0, fib1, sum As Decimal Dim i As Integer fib0 = 0 fib1 = 1 For i = 1 To n sum = fib0 + fib1 fib0 = fib1 fib1 = sum Next Fib = fib0 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
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h>   #define MAXLEN 961 //maximum string length   int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#6502_Assembly
6502 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.
#68000_Assembly
68000 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.
#8086_Assembly
8086 Assembly
Sunday equ 0 Monday equ 1 Tuesday equ 2 Wednesday equ 3 Thursday equ 4 Friday equ 5 Saturday equ 6 Sunday equ 7
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#ALGOL_68
ALGOL 68
PROC halve = (REF INT x)VOID: x := ABS(BIN x SHR 1); PROC doublit = (REF INT x)VOID: x := ABS(BIN x SHL 1); PROC iseven = (#CONST# INT x)BOOL: NOT ODD x;   PROC ethiopian = (INT in plier, INT in plicand, #CONST# BOOL tutor)INT: ( INT plier := in plier, plicand := in plicand; INT result:=0;   IF tuto...
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} ...
#AppleScript
AppleScript
-- equilibriumIndices :: [Int] -> [Int] on equilibriumIndices(xs)   script balancedPair on |λ|(a, pair, i) set {x, y} to pair if x = y then {i - 1} & a else a end if end |λ| end script   script plus on |λ...
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
#Batch_File
Batch File
echo %Foo%
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
#BBC_BASIC
BBC BASIC
PRINT FNenvironment("PATH") PRINT FNenvironment("USERNAME") END   DEF FNenvironment(envar$) LOCAL buffer%, size% SYS "GetEnvironmentVariable", envar$, 0, 0 TO size% DIM buffer% LOCAL size% SYS "GetEnvironmentVariable", envar$, buffer%, size%+1 = $$buffer%
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
#C
C
#include <stdlib.h> #include <stdio.h>   int main() { puts(getenv("HOME")); puts(getenv("PATH")); puts(getenv("USER")); return 0; }  
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#Julia
Julia
using Formatting import Base.iterate, Base.IteratorSize, Base.IteratorEltype   """ struct Esthetic   Used for iteration of esthetic numbers """ struct Esthetic{T} lowerlimit::T where T <: Integer base::T upperlimit::T Esthetic{T}(n, bas, m=typemax(T)) where T = new{T}(nextesthetic(n, bas), bas, m) e...
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...
#C
C
// Alexander Maximov, July 2nd, 2015 #include <stdio.h> #include <time.h> typedef long long mylong;   void compute(int N, char find_only_one_solution) { const int M = 30; /* x^5 == x modulo M=2*3*5 */ int a, b, c, d, e; mylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M));   for(s=0; s < N; ++s) p5[s] =...
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...
#MiniZinc
MiniZinc
var int: factorial(int: n) = let { array[0..n] of var int: factorial; constraint forall(a in 0..n)( factorial[a] == if (a == 0) then 1 else a*factorial[a-1] endif )} in factorial[n];   var int: fac = factorial(6); solve satisfy; output [show(fac),"\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...
#Arendelle
Arendelle
( input , "Please enter a number: " ) { @input % 2 = 0 , "| @input | is even!" , "| @input | is odd!" }
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI or android 32 bits */ /* program oddEven.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see t...
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...
#Kotlin
Kotlin
// version 1.1.2   typealias Deriv = (Double) -> Double // only one parameter needed here   const val FMT = " %7.3f"   fun euler(f: Deriv, y: Double, step: Int, end: Int) { var yy = y print(" Step %2d: ".format(step)) for (t in 0..end step step) { if (t % 10 == 0) print(FMT.format(yy)) yy +...
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...
#Commodore_BASIC
Commodore BASIC
  10 REM BINOMIAL COEFFICIENTS 20 REM COMMODORE BASIC 2.0 30 REM 2021-08-24 40 REM BY ALVALONGO 100 Z=0:U=1 110 FOR N=U TO 10 120 PRINT N; 130 FOR K=Z TO N 140 GOSUB 900 150 PRINT C; 160 NEXT K 170 PRINT 180 NEXT N 190 END 900 REM BINOMIAL COEFFICIENT 910 IF K<Z OR K>N THEN C=Z:RETURN 920 IF K=Z OR K=N THEN C=U: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 ...
#Vlang
Vlang
fn fib_iter(n int) int { if n < 2 { return n }   mut prev, mut fib := 0, 1 for _ in 0..(n - 1){ prev, fib = fib, prev + fib } return fib }   fn main() { for val in 0..11 { println('fibonacci(${val:2d}) = ${fib_iter(val):3d}') } }
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
#C.2B.2B
C++
#include <iostream> #include <fstream> #include <cmath>   using namespace std;   string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return conten...
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
#Crystal
Crystal
def entropy(s) counts = s.chars.each_with_object(Hash(Char, Float64).new(0.0)) { |c, h| h[c] += 1 } counts.values.sum do |count| freq = count / s.size -freq * Math.log2(freq) end end   puts entropy File.read(__FILE__)
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#ACL2
ACL2
(defun symbol-to-constant (sym) (intern (concatenate 'string "*" (symbol-name sym) "*") "ACL2"))   (defmacro enum-with-vals (symbol value &rest args) (if (endp args) `(defconst ,(symbol-to-constant symbol) ,value) `(progn (defconst ,(symbol-to-constant symbol) ,value) (enum...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Ada
Ada
type Fruit is (apple, banana, cherry); -- No specification of the representation value; for Fruit use (apple => 1, banana => 2, cherry => 4); -- specification of the representation values
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 ...
#ALGOL-M
ALGOL-M
  BEGIN   INTEGER FUNCTION HALF(I); INTEGER I; BEGIN HALF := I / 2; END;   INTEGER FUNCTION DOUBLE(I); INTEGER I; BEGIN DOUBLE := I + I; END;   % RETURN 1 IF EVEN, OTHERWISE 0 % INTEGER FUNCTION EVEN(I); INTEGER I; BEGIN EVEN := 1 - (I - 2 * (I / 2)); END;   % RETURN I * J AND OPTIONALLY SHOW COMPUTATIONAL STEPS ...
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} ...
#Arturo
Arturo
eqIndex: function [row][ suml: 0 delayed: 0 sumr: sum row result: new [] loop.with:'i row 'r [ suml: suml + delayed sumr: sumr - r delayed: r if suml = sumr -> 'result ++ i ] return result ]   data: @[ @[neg 7, 1, 5, 2, neg 4, 3, 0] @[2 4 6] @[2 9 ...
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
#C.23
C#
using System;   namespace RosettaCode { class Program { static void Main() { string temp = Environment.GetEnvironmentVariable("TEMP"); Console.WriteLine("TEMP is " + temp); } } }
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
#C.2B.2B
C++
#include <cstdlib> #include <cstdio>   int main() { puts(getenv("HOME")); return 0; }
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Clojure
Clojure
(System/getenv "HOME")
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#Kotlin
Kotlin
import kotlin.math.abs   fun isEsthetic(n: Long, b: Long): Boolean { if (n == 0L) { return false } var i = n % b var n2 = n / b while (n2 > 0) { val j = n2 % b if (abs(i - j) != 1L) { return false } n2 /= b i = j } return true }   f...
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...
#C.23
C#
using System;   namespace EulerSumOfPowers { class Program { const int MAX_NUMBER = 250;   static void Main(string[] args) { bool found = false; long[] fifth = new long[MAX_NUMBER];   for (int i = 1; i <= MAX_NUMBER; i++) { long i2 = 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...
#MIPS_Assembly
MIPS Assembly
  ################################## # Factorial; iterative # # By Keith Stellyes :) # # Targets Mars implementation # # August 24, 2016 # ##################################   # This example reads an integer from user, stores in register a1 # Then, it uses a0 as a multiplier and ta...
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...
#ArnoldC
ArnoldC
LISTEN TO ME VERY CAREFULLY isOdd I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE result YOU SET US UP @I LIED GET TO THE CHOPPER result HERE IS MY INVITATION n I LET HIM GO 2 ENOUGH TALK I'LL BE BACK result HASTA LA VISTA, BABY   LISTEN TO ME VERY CAREFULLY showParity I NE...
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...
#Lambdatalk
Lambdatalk
  {def eulersMethod {def eulersMethod.r {lambda {:f :b :h :t :y} {if {<= :t :b} then {tr {td :t} {td {/ {round {* :y 1000}} 1000}}} {eulersMethod.r :f :b :h {+ :t :h} {+ :y {* :h {:f :t :y}}}} else}}} {lambda {:f :y0 :a :b :h} {table {eulersMethod.r :f :b :h :a :y0}}}}   {def cooling {lambda ...
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...
#Common_Lisp
Common Lisp
  (defun choose (n k) (labels ((prod-enum (s e) (do ((i s (1+ i)) (r 1 (* i r))) ((> i e) r))) (fact (n) (prod-enum 1 n))) (/ (prod-enum (- (1+ n) k) n) (fact 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...
#D
D
T binomial(T)(in T n, T k) pure nothrow { if (k > (n / 2)) k = n - k; T bc = 1; foreach (T i; T(2) .. k + 1) bc = (bc * (n - k + i)) / i; return bc; }   void main() { import std.stdio, std.bigint;   foreach (const d; [[5, 3], [100, 2], [100, 98]]) writefln("(%3d %3d) = %s...
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 ...
#Wart
Wart
def (fib n) if (n < 2) n (+ (fib n-1) (fib n-2))
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#D
D
void main(in string[] args) { import std.stdio, std.algorithm, std.math, std.file;   auto data = sort(cast(ubyte[])args[0].read); return data .group .map!(g => g[1] / double(data.length)) .map!(p => -p * p.log2) .sum .writeln; }
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
#Elixir
Elixir
File.open(__ENV__.file, [:read], fn(file) -> text = IO.read(file, :all) leng = String.length(text) String.codepoints(text) |> Enum.group_by(&(&1)) |> Enum.map(fn{_,value} -> length(value) end) |> Enum.reduce(0, fn count, entropy -> freq = count / leng entropy - freq * :math.log2(freq) end...
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Emacs_Lisp
Emacs Lisp
(defun shannon-entropy (input) (let ((freq-table (make-hash-table)) (entropy 0) (length (+ (length input) 0.0))) (mapcar (lambda (x) (puthash x (+ 1 (gethash x freq-table 0)) freq-table)) input) (maphash (lambda (k v) (set 'entropy (+ entropy (* (/ v length) ...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#ALGOL_68
ALGOL 68
BEGIN # example 1 # MODE FRUIT = INT; FRUIT apple = 1, banana = 2, cherry = 4; FRUIT x := cherry; CASE x IN print(("It is an apple #",x, new line)), print(("It is a banana #",x, new line)), SKIP, # 3 not defined # print(("It is a cherry #",x, new line)) OUT SKIP # other values # ESAC END...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#AmigaE
AmigaE
ENUM APPLE, BANANA, CHERRY   PROC main() DEF x ForAll({x}, [APPLE, BANANA, CHERRY], `WriteF('\d\n', x)) ENDPROC
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.
#11l
11l
-V min_size = 10
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 ...
#ALGOL_W
ALGOL W
begin  % returns half of a % integer procedure halve ( integer value a ) ; a div 2;  % returns a doubled % integer procedure double ( integer value a ) ; a * 2;  % returns true if a is even, false otherwise % logical procedure even ( integer value a ) ; not odd( a );  % returns the product of...
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} ...
#AutoHotkey
AutoHotkey
Equilibrium_index(list, BaseIndex=0){ StringSplit, A, list, `, Loop % A0 { i := A_Index , Pre := Post := 0 loop, % A0 if (A_Index < i) Pre += A%A_Index% else if (A_Index > i) Post += A%A_Index% if (Pre = Post) Res .= (Res?", ":"") i - (BaseIndex?0:1) } return Res }
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} ...
#AWK
AWK
  # syntax: GAWK -f EQUILIBRIUM_INDEX.AWK BEGIN { main("-7 1 5 2 -4 3 0") main("2 4 6") main("2 9 2") main("1 -1 1 -1 1 -1 1") exit(0) } function main(numbers, x) { x = equilibrium(numbers) printf("numbers: %s\n",numbers) printf("indices: %s\n\n",length(x)==0?"none":x) } function equili...
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
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Environment-Vars.   DATA DIVISION. WORKING-STORAGE SECTION. 01 home PIC X(75).   PROCEDURE DIVISION. * *> Method 1. ACCEPT home FROM ENVIRONMENT "HOME" DISPLAY home   * *> Method 2. D...
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
#CoffeeScript
CoffeeScript
for var_name in ['PATH', 'HOME', 'LANG', 'USER'] console.log var_name, process.env[var_name]
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
#Common_Lisp
Common Lisp
(lispworks:environment-variable "USER")
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...
#Lua
Lua
function to(n, b) local BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"   if n == 0 then return "0" end   local ss = "" while n > 0 do local idx = (n % b) + 1 n = math.floor(n / b) ss = ss .. BASE:sub(idx, idx) end return string.reverse(ss) end   function isEsth...
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...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <cmath> #include <set> #include <vector>   using namespace std;   bool find() { const auto MAX = 250; vector<double> pow5(MAX); for (auto i = 1; i < MAX; i++) pow5[i] = (double)i * i * i * i * i; for (auto x0 = 1; x0 < MAX; x0++) { for (a...
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...
#Mirah
Mirah
def factorial_iterative(n:int) 2.upto(n-1) do |i| n *= i end n end   puts factorial_iterative 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...
#Arturo
Arturo
loop (neg 5)..5 [x][ if? even? x -> print [pad to :string x 4 ": even"] else -> print [pad to :string x 4 ": odd"] ]