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/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...
#Lua
Lua
T0 = 100 TR = 20 k = 0.07 delta_t = { 2, 5, 10 } n = 100   NewtonCooling = function( t ) return -k * ( t - TR ) end     function Euler( f, y0, n, h ) local y = y0 for x = 0, n, h do print( "", x, y ) y = y + h * f( y ) end end     for i = 1, #delta_t do print( "delta_t = ", delta_t[i] ) Euler( Ne...
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...
#dc
dc
[sx1q]sz[d0=zd1-lfx*]sf[skdlfxrlk-lfxlklfx*/]sb
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...
#Delphi
Delphi
program Binomial;   {$APPTYPE CONSOLE}   function BinomialCoff(N, K: Cardinal): Cardinal; var L: Cardinal;   begin if N < K then Result:= 0 // Error else begin if K > N - K then K:= N - K; // Optimization Result:= 1; L:= 0; while L < K do begin Result:= Result * (N - L); ...
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 ...
#WDTE
WDTE
let memo fib n => n { > 1 => + (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
#Erlang
Erlang
#! /usr/bin/escript   -define(LOG2E, 1.44269504088896340735992).   main(_) -> Self = escript:script_name(), {ok, Contents} = file:read_file(Self), io:format("My entropy is ~p~n", [entropy(Contents)]).   entropy(Data) -> Frq = count(Data), maps:fold(fun(_, C, E) -> P = C / byte_size...
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
#Factor
Factor
USING: assocs io io.encodings.utf8 io.files kernel math math.functions math.statistics prettyprint sequences ; IN: rosetta-code.entropy-narcissist   : entropy ( seq -- entropy ) [ length ] [ histogram >alist [ second ] map ] bi [ swap / ] with map [ dup log 2 log / * ] map-sum neg ;   "entropy-narcissist.fa...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Arturo
Arturo
enum: [apple banana cherry] print "as a block of words:" inspect.muted enum   enum: ['apple 'banana 'cherry] print "\nas a block of literals:" print enum   enum: #[ apple: 1 banana: 2 cherry: 3 ] print "\nas a dictionary:" print enum
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#ATS
ATS
datatype my_enum = | value_a | value_b | value_c
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#AutoHotkey
AutoHotkey
fruit_%apple% = 0 fruit_%banana% = 1 fruit_%cherry% = 2
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.
#6502_Assembly
6502 Assembly
List: byte $01,$02,$03,$04,$05
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.
#68000_Assembly
68000 Assembly
bit7 equ %10000000 bit6 equ %01000000   MOVE.B (A0),D0 AND.B #bit7,D0 ;D0.B contains either $00 or $80
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.
#8th
8th
  123 const var, one-two-three  
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.
#ACL2
ACL2
(defconst *pi-approx* 22/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 ...
#AppleScript
AppleScript
on run {ethMult(17, 34), ethMult("Rhind", 9)}   --> {578, "RhindRhindRhindRhindRhindRhindRhindRhind"} end run     -- Int -> Int -> Int -- or -- Int -> String -> String on ethMult(m, n) script fns property identity : missing value property plus : missing value   on half(n) -- 1. half ...
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} ...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   call :equilibrium-index "-7 1 5 2 -4 3 0" call :equilibrium-index "2 4 6" call :equilibrium-index "2 9 2" call :equilibrium-index "1 -1 1 -1 1 -1 1" pause>nul exit /b   %== The Function ==% :equilibrium-index <sequence with quotes> ::Set the pseudo-array sequence... set "se...
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
#D
D
import std.stdio, std.process;   void main() { auto home = getenv("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
#Delphi.2FPascal
Delphi/Pascal
program EnvironmentVariable;   {$APPTYPE CONSOLE}   uses SysUtils;   begin WriteLn('Temp = ' + GetEnvironmentVariable('TEMP')); 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
#E
E
<unsafe:java.lang.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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[EstheticNumbersRangeHelper, EstheticNumbersRange] EstheticNumbersRangeHelper[power_, mima : {mi_, max_}, b_ : 10] := Module[{steps, cands}, steps = Tuples[{-1, 1}, power - 1]; steps = Accumulate[Prepend[#, 0]] & /@ steps; cands = Table[Select[# + ConstantArray[s, power] & /@ steps, AllTrue[Between[{0, 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...
#Clojure
Clojure
  (ns test-p.core (:require [clojure.math.numeric-tower :as math]) (:require [clojure.data.int-map :as i]))   (defn solve-power-sum [max-value max-sols] " Finds solutions by using method approach of EchoLisp Large difference is we store a dictionary of all combinations of y^5 - x^5 with the x, y value so...
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...
#.D0.9C.D0.9A-61.2F52
МК-61/52
ВП П0 1 ИП0 * L0 03 С/П
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...
#Asymptote
Asymptote
for (int i = 1; i <= 10; ++i) { if (i % 2 == 0) { write(string(i), " is even"); } else { write(string(i), " is odd"); } }
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...
#Maple
Maple
with(Student[NumericalAnalysis]); k := 0.07: TR := 20: Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 50); # step size = 2 Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 20); # step size = 5 Euler(diff(T(t), t) = -k*(T(t) - TR), T(0) = 100, t = 100, numsteps = 10); # step s...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  euler[step_, val_] := NDSolve[ {T'[t] == -0.07 (T[t] - 20), T[0] == 100}, T, {t, 0, 100}, Method -> "ExplicitEuler", StartingStepSize -> step ][[1, 1, 2]][val]  
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...
#Elixir
Elixir
defmodule RC do def choose(n,k) when is_integer(n) and is_integer(k) and n>=0 and k>=0 and n>=k do if k==0, do: 1, else: choose(n,k,1,1) end   def choose(n,k,k,acc), do: div(acc * (n-k+1), k) def choose(n,k,i,acc), do: choose(n, k, i+1, div(acc * (n-i+1), i)) end   IO.inspect RC.choose(5,3) IO.inspect RC.ch...
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...
#Erlang
Erlang
  choose(N, 0) -> 1; choose(N, K) when is_integer(N), is_integer(K), (N >= 0), (K >= 0), (N >= K) -> choose(N, K, 1, 1).   choose(N, K, K, Acc) -> (Acc * (N-K+1)) div K; choose(N, K, I, Acc) -> choose(N, K, I+1, (Acc * (N-I+1)) div I).  
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 ...
#WebAssembly
WebAssembly
(func $fibonacci_nth (param $n i32) (result i32)  ;;Declare some local registers (local $i i32) (local $a i32) (local $b i32)  ;;Handle first 2 numbers as special cases (if (i32.eq (get_local $n) (i32.const 0)) (return (i32.const 0)) ) (if (i32.eq...
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
#FreeBASIC
FreeBASIC
' version 01-06-2016 ' compile with: fbc -s console ' modified code from ENTROPY entry   Dim As Integer i, count, totalchar(255) Dim As UByte buffer Dim As Double prop, entropy ' command (0) returns the name of this program (including the path) Dim As String slash, filename = Command(0) Dim As Integer ff = FreeFile '...
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
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" "math" "os" "runtime" )   func main() { _, src, _, _ := runtime.Caller(0) fmt.Println("Source file entropy:", entropy(src)) fmt.Println("Binary file entropy:", entropy(os.Args[0])) }   func entropy(file string) float64 { d, err := i...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#AWK
AWK
fruit["apple"]=1; fruit["banana"]=2; fruit["cherry"]=3 fruit[1]="apple"; fruit[2]="banana"; fruit[3]="cherry" i=0; apple=++i; banana=++i; cherry=++i;
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#BASIC
BASIC
REM Impossible. Can only be faked with arrays of strings. OPTION BASE 1 DIM SHARED fruitsName$(1 TO 3) DIM SHARED fruitsVal%( 1 TO 3) fruitsName$[1] = "apple" fruitsName$[2] = "banana" fruitsName$[3] = "cherry" fruitsVal%[1] = 1 fruitsVal%[2] = 2 fruitsVal%[3] = 3   REM OR GLOBAL CONSTANTS DIM SHARED apple%, banana%, c...
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.
#Ada
Ada
Foo : constant := 42; Foo : constant Blahtype := Blahvalue;
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.
#ALGOL_68
ALGOL 68
INT max allowed = 20; REAL pi = 3.1415 9265; # pi is constant that the compiler will enforce # REF REAL var = LOC REAL; # var is a constant pointer to a local REAL address # var := pi # constant pointer var has the REAL value referenced assigned pi #
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.
#AutoHotkey
AutoHotkey
MyData := new FinalBox("Immutable data") MsgBox % "MyData.Data = " MyData.Data MyData.Data := "This will fail to set" MsgBox % "MyData.Data = " MyData.Data   Class FinalBox { __New(FinalValue) { ObjInsert(this, "proxy",{Data:FinalValue}) } ; override the built-in methods: __Get(k) { return, this["p...
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 ...
#Arturo
Arturo
halve: function [x]-> shr x 1 double: function [x]-> shl x 1   ; even? already exists   ethiopian: function [x y][ prod: 0 while [x > 0][ unless even? x [prod: prod + y] x: halve x y: double y ] return prod ]   print ethiopian 17 34 print ethiopian 2 3
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} ...
#BBC_BASIC
BBC BASIC
DIM list(6) list() = -7, 1, 5, 2, -4, 3, 0 PRINT "Equilibrium indices are " FNequilibrium(list()) END   DEF FNequilibrium(l()) LOCAL i%, r, s, e$ s = SUM(l()) FOR i% = 0 TO DIM(l(),1) IF r = s - r - l(i%) THEN e$ += STR$(i%) + "," r += l(i%) NEXT ...
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} ...
#C
C
#include <stdio.h> #include <stdlib.h>   int list[] = {-7, 1, 5, 2, -4, 3, 0};   int eq_idx(int *a, int len, int **ret) { int i, sum, s, cnt; /* alloc long enough: if we can afford the original list, * we should be able to afford to this. Beats a potential * million realloc() calls. Even if memory is a r...
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
#Eiffel
Eiffel
class APPLICATION inherit EXECUTION_ENVIRONMENT create make feature {NONE} -- Initialization make -- Retrieve and print value for environment variable `USERNAME'. do print (get ("USERNAME")) end 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
#Elixir
Elixir
System.get_env("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
#Emacs_Lisp
Emacs Lisp
(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...
#Nim
Nim
import strformat   func isEsthetic(n, b: int64): bool = if n == 0: return false var i = n mod b var n = n div b while n > 0: let j = n mod b if abs(i - j) != 1: return false n = n div b i = j result = true     proc listEsths(n1, n2, m1, m2: int64; perLine: int; all: bool) = var esths: ...
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...
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. EULER. DATA DIVISION. FILE SECTION. WORKING-STORAGE SECTION. 1 TABLE-LENGTH CONSTANT 250. 1 SEARCHING-FLAG PIC 9. 88 FINISHED-SEARCHING VALUE IS 1 WHEN SET TO FALSE IS 0. 1 CAL...
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...
#ML.2FI
ML/I
MCSKIP "WITH" NL "" Factorial - iterative MCSKIP MT,<> MCINS %. MCDEF FACTORIAL WITHS () AS <MCSET T1=%A1. MCSET T2=1 MCSET T3=1 %L1.MCGO L2 IF T3 GR T1 MCSET T2=T2*T3 MCSET T3=T3+1 MCGO L1 %L2.%T2.> fact(1) is FACTORIAL(1) fact(2) is FACTORIAL(2) fact(3) is FACTORIAL(3) fact(4) is FACTORIAL(4)
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...
#AutoHotkey
AutoHotkey
if ( int & 1 ){ ; do odd stuff }else{ ; do even stuff }
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...
#Maxima
Maxima
euler_method(f, y0, a, b, h):= block( [t: a, y: y0, tg: [a], yg: [y0]], unless t>=b do ( t: t + h, y: y + f(t, y)*h, tg: endcons(t, tg), yg: endcons(y, yg) ), [tg, yg] );   /* initial temperature */ T0: 100;   /* environment of temperature */ Tr: 20;   /* the cooling constant */ k: 0.07;   /...
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...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П2 С/П П3 С/П П4 ПП 19 ИП3 * ИП4 + П4 С/П ИП2 ИП3 + П2 БП 05 ... ... ... ... ... ... ... ... ... ... В/О
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...
#ERRE
ERRE
PROGRAM BINOMIAL   !$DOUBLE   PROCEDURE BINOMIAL(N,K->BIN) LOCAL R,D R=1 D=N-K IF D>K THEN K=D D=N-K END IF WHILE N>K DO R*=N N-=1 WHILE D>1 AND (R-D*INT(R/D))=0 DO R/=D D-=1 END WHILE END WHILE BIN=R END PROCEDURE   BEGIN BINOM...
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...
#F.23
F#
  let choose n k = List.fold (fun s i -> s * (n-i+1)/i ) 1 [1..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 ...
#Whitespace
Whitespace
 
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
#Haskell
Haskell
import qualified Data.ByteString as BS import Data.List import System.Environment   (>>>) = flip (.)   main = getArgs >>= head >>> BS.readFile >>= BS.unpack >>> entropy >>> print   entropy = sort >>> group >>> map genericLength >>> normalize >>> map lg >>> sum where lg c = -c * logBase 2 c normalize c = let 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
#J
J
entropy=: +/@:-@(* 2&^.)@(#/.~ % #) 1!:2&2 entropy 1!:1 (4!:4 <'entropy') { 4!:3''
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
#Java
Java
  import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map;   public class EntropyNarcissist {   private static final String FILE_NAME = "src/EntropyNarcissist.java";   public static void main(String[] args) { ...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Bracmat
Bracmat
fruits=apple+banana+cherry;
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#C
C
enum fruits { apple, banana, cherry };   enum fruits { apple = 0, banana = 1, cherry = 2 };
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#C.23
C#
enum fruits { apple, banana, cherry }   enum fruits { apple = 0, banana = 1, cherry = 2 }   enum fruits : int { apple = 0, banana = 1, cherry = 2 }   [FlagsAttribute] enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }
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.
#BASIC
BASIC
CONST x = 1
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.
#BBC_BASIC
BBC BASIC
DEF FNconst = 2.71828182845905 PRINT FNconst FNconst = 1.234 : REM Reports 'Syntax 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.
#Bracmat
Bracmat
myVar=immutable (m=mutable) immutable; changed:?(myVar.m); lst$myVar  
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.
#C
C
#define PI 3.14159265358979323 #define MINSIZE 10 #define MAXSIZE 100
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...
#11l
11l
F entropy(source) DefaultDict[Char, Int] hist L(c) source hist[c]++ V r = 0.0 L(v) hist.values() V c = Float(v) / source.len r -= c * log2(c) R r   print(entropy(‘1223334444’))
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#AutoHotkey
AutoHotkey
MsgBox % Ethiopian(17, 34) "`n" Ethiopian2(17, 34)   ; func definitions: half( x ) { return x >> 1 }   double( x ) { return x << 1 }   isEven( x ) { return x & 1 == 0 }   Ethiopian( a, b ) { r := 0 While (a >= 1) { if !isEven(a) r += b a := half(a) b := double(b) } return r }   ; or a recursive function...
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} ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program { static IEnumerable<int> EquilibriumIndices(IEnumerable<int> sequence) { var left = 0; var right = sequence.Sum(); var index = 0; foreach (var element in sequence) { right -= e...
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
#Erlang
Erlang
  os:getenv( "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
#Euphoria
Euphoria
puts(1,getenv("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
#F.23
F#
open System   [<EntryPoint>] let main args = printfn "%A" (Environment.GetEnvironmentVariable("PATH")) 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...
#Pascal
Pascal
program Esthetic; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$codealign proc=16} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils,//IntToStr strutils;//Numb2USA aka commatize const ConvBase :array[0..15] of char= '0123456789ABCDEF'; maxBase = 16; type tErg = string[63]; tCnt = array[0..maxBas...
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...
#Common_Lisp
Common Lisp
  (ql:quickload :alexandria) (let ((fifth-powers (mapcar #'(lambda (x) (expt x 5)) (alexandria:iota 250)))) (loop named outer for x0 from 1 to (length fifth-powers) do (loop for x1 from 1 below x0 do (loop for x2 from 1 below x1 do (loop for x3 from 1 below x2 do ...
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...
#Modula-2
Modula-2
MODULE Factorial; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   PROCEDURE Factorial(n : CARDINAL) : CARDINAL; VAR result : CARDINAL; BEGIN result := 1; WHILE n#0 DO result := result * n; DEC(n) END; RETURN result END Factorial;   VAR buf : ARRAY[...
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...
#AWK
AWK
function isodd(x) { return (x%2)!=0; }   function iseven(x) { return (x%2)==0; }
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#Nim
Nim
import strutils   proc euler(f: proc (x,y: float): float; y0, a, b, h: float) = var (t,y) = (a,y0) while t < b: echo formatFloat(t, ffDecimal, 3), " ", formatFloat(y, ffDecimal, 3) t += h y += h * f(t,y)   proc newtoncooling(time, temp: float): float = -0.07 * (temp - 20)   euler(newtoncooling, 100.0,...
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#Objeck
Objeck
  class EulerMethod { T0 : static : Float; TR : static : Float; k : static : Float; delta_t : static : Float[]; n : static : Float;   function : Main(args : String[]) ~ Nil { T0 := 100; TR := 20; k := 0.07; delta_t := [2.0, 5.0, 10.0]; n := 100;   f := NewtonCooling(Float) ~ Float; ...
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...
#Factor
Factor
  : fact ( n -- n-factorial ) dup 0 = [ drop 1 ] [ dup 1 - fact * ] if ;   : choose ( n k -- n-choose-k ) 2dup - [ fact ] tri@ * / ;   ! outputs 10 5 3 choose .   ! alternative using folds USE: math.ranges   ! (product [n..k+1] / product [n-k..1]) : choose-fold ( n k -- n-choose-k ) 2dup 1 + [a,b] product -...
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...
#Fermat
Fermat
Bin(5,3)
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 ...
#Wrapl
Wrapl
DEF fib() ( VAR seq <- [0, 1]; EVERY SUSP seq:values; REP SUSP seq:put(seq:pop + seq[1])[-1]; );
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
#Julia
Julia
using DataStructures   entropy(s) = -sum(x -> x / length(s) * log2(x / length(s)), values(counter(s))) println("self-entropy: ", entropy(read(Base.source_path(), String)))
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
#Kotlin
Kotlin
// version 1.1.0 (entropy_narc.kt)   fun log2(d: Double) = Math.log(d) / Math.log(2.0)   fun shannon(s: String): Double { val counters = mutableMapOf<Char, Int>() for (c in s) { if (counters.containsKey(c)) counters[c] = counters[c]!! + 1 else counters.put(c, 1) } val nn = s.length.toDo...
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
#Lua
Lua
function getFile (filename) local inFile = io.open(filename, "r") local fileContent = inFile:read("*all") inFile:close() return fileContent end   function log2 (x) return math.log(x) / math.log(2) end   function entropy (X) local N, count, sum, i = X:len(), {}, 0 for char = 1, N do i = X...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#C.2B.2B
C++
enum fruits { apple, banana, cherry };   enum fruits { apple = 0, banana = 1, cherry = 2 };
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Clojure
Clojure
; a set of keywords (def fruits #{:apple :banana :cherry})   ; a predicate to test "fruit" membership (defn fruit? [x] (contains? fruits x))   ; if you need a value associated with each fruit (def fruit-value (zipmap fruits (iterate inc 1)))   (println (fruit? :apple)) (println (fruit-value :banana))
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.
#C.23
C#
readonly DateTime now = DateTime.Now;
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.
#C.2B.2B
C++
#include <iostream>   class MyOtherClass { public: const int m_x; MyOtherClass(const int initX = 0) : m_x(initX) { }   };   int main() { MyOtherClass mocA, mocB(7);   std::cout << mocA.m_x << std::endl; // displays 0, the default value given for MyOtherClass's constructor. std::cout << mocB.m_x << std::endl; ...
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...
#Ada
Ada
with Ada.Text_IO, Ada.Float_Text_IO, Ada.Numerics.Elementary_Functions;   procedure Count_Entropy is   package TIO renames Ada.Text_IO;   Count: array(Character) of Natural := (others => 0); Sum: Natural := 0; Line: String := "1223334444";   begin for I in Line'Range loop -- count the characters ...
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 ...
#AutoIt
AutoIt
  Func Halve($x) Return Int($x/2) EndFunc   Func Double($x) Return ($x*2) EndFunc   Func IsEven($x) Return (Mod($x,2) == 0) EndFunc   ; this version also supports negative parameters Func Ethiopian($nPlier, $nPlicand, $bTutor = True) Local $nResult = 0 If ($nPlier < 0) Then $nPlier =- $nPlier $nPlicand =- $nPl...
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} ...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <numeric> #include <vector>   template <typename T> std::vector<size_t> equilibrium(T first, T last) { typedef typename std::iterator_traits<T>::value_type value_t;   value_t left = 0; value_t right = std::accumulate(first, last, value_t(0)); std::vecto...
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
#Factor
Factor
"HOME" os-env print
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
#Forth
Forth
s" HOME" getenv type
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
#Fortran
Fortran
program show_home implicit none character(len=32) :: home_val  ! The string value of the variable HOME integer :: home_len ! The actual length of the value integer :: stat ! The status of the value: ! 0 = ok ! 1 = variable does no...
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...
#Perl
Perl
use 5.020; use warnings; use experimental qw(signatures);   use ntheory qw(fromdigits todigitstring);   sub generate_esthetic ($root, $upto, $callback, $base = 10) {   my $v = fromdigits($root, $base);   return if ($v > $upto); $callback->($v);   my $t = $root->[-1];   __SUB__->([@$root, $t + 1], $u...
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...
#D
D
import std.stdio, std.range, std.algorithm, std.typecons;   auto eulersSumOfPowers() { enum maxN = 250; auto pow5 = iota(size_t(maxN)).map!(i => ulong(i) ^^ 5).array.assumeSorted;   foreach (immutable x0; 1 .. maxN) foreach (immutable x1; 1 .. x0) foreach (immutable x2; 1 .. x1) ...
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...
#Modula-3
Modula-3
PROCEDURE FactIter(n: CARDINAL): CARDINAL = VAR result := n; counter := n - 1;   BEGIN FOR i := counter TO 1 BY -1 DO result := result * i; END; RETURN result; END FactIter;
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...
#BaCon
BaCon
' Even or odd OPTION MEMTYPE int SPLIT ARGUMENT$ BY " " TO arg$ SIZE dim n = IIF$(dim < 2, 0, VAL(arg$[1])) PRINT n, " is ", IIF$(EVEN(n), "even", "odd")
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...
#OCaml
OCaml
(* Euler integration by recurrence relation. * Given a function, and stepsize, provides a function of (t,y) which * returns the next step: (t',y'). *) let euler f ~step (t,y) = ( t+.step, y +. step *. f t y )   (* newton_cooling doesn't use time parameter, so _ is a placeholder *) let newton_cooling ~k ~tr _ y = -.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...
#Forth
Forth
: choose ( n k -- nCk ) 1 swap 0 ?do over i - i 1+ */ loop nip ;   5 3 choose . \ 10 33 17 choose . \ 1166803110
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...
#Fortran
Fortran
program test_choose   implicit none   write (*, '(i0)') choose (5, 3)   contains   function factorial (n) result (res)   implicit none integer, intent (in) :: n integer :: res integer :: i   res = product ((/(i, i = 1, n)/))   end function factorial   function choose (n, k) result (res)   ...
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 ...
#Wren
Wren
// iterative (quick) var fibItr = Fn.new { |n| if (n < 2) return n var a = 0 var b = 1 for (i in 2..n) { var c = a + b a = b b = c } return b }   // recursive (slow) var fibRec fibRec = Fn.new { |n| if (n < 2) return n return fibRec.call(n-1) + fibRec.call(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
#Nim
Nim
import os, math, strutils, tables   let execName = getAppFilename().splitPath().tail let srcName = execName & ".nim"   func entropy(str: string): float = var counts: CountTable[char] for ch in str: counts.inc(ch) for count in counts.values: result -= count / str.len * log2(count / str.len)   echo "Source ...
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
#PARI.2FGP
PARI/GP
entropy(s)=s=Vec(s);my(v=vecsort(s,,8));-sum(i=1,#v,(x->x*log(x))(sum(j=1,#s,v[i]==s[j])/#s))/log(2); entropy(Str(entropy))
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
#Perl
Perl
#!/usr/bin/perl use strict ; use warnings ; use feature 'say' ;   sub log2 { my $number = shift ; return log( $number ) / log( 2 ) ; }   open my $fh , "<" , $ARGV[ 0 ] or die "Can't open $ARGV[ 0 ]$!\n" ; my %frequencies ; my $totallength = 0 ; while ( my $line = <$fh> ) { chomp $line ; next if $line =~ /^$...
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Common_Lisp
Common Lisp
;; symbol to number (defconstant +apple+ 0) (defconstant +banana+ 1) (defconstant +cherry+ 2)   ;; number to symbol (defun index-fruit (i) (aref #(+apple+ +banana+ +cherry+) i))
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Computer.2Fzero_Assembly
Computer/zero Assembly
LDA 4 ;load from memory address 4 STP NOP NOP byte 1