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/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.
| #Logtalk | Logtalk |
:- object(immutable).
% forbid using (complementing) categories for adding to or
% modifying (aka hot patching) the object
:- set_logtalk_flag(complements, deny).
% forbid dynamically adding new predicates at runtime
:- set_logtalk_flag(dynamic_declarations, deny).
:- public(foo/1).
fo... |
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.
| #Lua | Lua | local pi <const> = 3.14159265359 |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#define MAXLEN 100 //maximum string length
int makehist(unsigned 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... |
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 ... | #C | C | #include <stdio.h>
#include <stdbool.h>
void halve(int *x) { *x >>= 1; }
void doublit(int *x) { *x <<= 1; }
bool iseven(const int x) { return (x & 1) == 0; }
int ethiopian(int plier,
int plicand, const bool tutor)
{
int result=0;
if (tutor)
printf("ethiopian multiplication of %d by %d\n", plier, ... |
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}
... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println(ex([]int32{-7, 1, 5, 2, -4, 3, 0}))
// sequence of 1,000,000 random numbers, with values
// chosen so that it will be likely to have a couple
// of equalibrium indexes.
rand.Seed(time.Now().UnixNano())
v... |
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
| #Kotlin | Kotlin | // version 1.0.6
// tested on Windows 10
fun main(args: Array<String>) {
println(System.getenv("SystemRoot"))
} |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #langur | langur | writeln "HOME: ", _env["HOME"]
writeln "PATH: ", _env["PATH"]
writeln "USER: ", _env["USER"] |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #Lasso | Lasso | #!/usr/bin/lasso9
define getenv(sysvar::string) => {
local(regexp = regexp(
-find = `(?m)^` + #sysvar + `=(.*?)$`,
-input = sys_environ -> join('\n'),
-ignorecase
))
return #regexp ->find ? #regexp -> matchString(1)
}
stdoutnl(getenv('HOME'))
stdoutnl(getenv('PATH'))
stdoutnl(getenv('USER'))
stdoutnl(geten... |
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
| #Liberty_BASIC | Liberty BASIC | print StartupDir$
print DefaultDir$ |
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... | #Ring | Ring |
basePlus = []
decList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
for base = 2 to 16
see "Base " + base + ": " + (base*4) + "th to " + (base*6) + "th esthetic numbers:" + nl
res = 0
binList = []
for n = 1 to 10000
str = decim... |
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... | #Factor | Factor | USING: arrays backtrack kernel literals math.functions
math.ranges prettyprint sequences ;
CONSTANT: pow5 $[ 0 250 [a,b) [ 5 ^ ] map ]
: xn ( n1 -- n2 n2 ) [1,b) amb-lazy dup ;
250 xn xn xn xn drop 4array dup pow5 nths sum dup pow5
member? [ pow5 index suffix . ] [ 2drop fail ] if |
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... | #newLISP | newLISP | > (define (factorial n) (exp (gammaln (+ n 1))))
(lambda (n) (exp (gammaln (+ n 1))))
> (factorial 4)
24 |
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... | #C | C | if (x & 1) {
/* x is odd */
} else {
/* or not */
} |
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... | #Python | Python | def euler(f,y0,a,b,h):
t,y = a,y0
while t <= b:
print "%6.3f %6.3f" % (t,y)
t += h
y += h * f(t,y)
def newtoncooling(time, temp):
return -0.07 * (temp - 20)
euler(newtoncooling,100,0,100,10)
|
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... | #R | R | euler <- function(f, y0, a, b, h)
{
t <- a
y <- y0
while (t < b)
{
cat(sprintf("%6.3f %6.3f\n", t, y))
t <- t + h
y <- y + h*f(t, y)
}
}
newtoncooling <- function(time, temp){
return(-0.07*(temp-20))
}
euler(newtoncooling, 100, 0, 100, 10) |
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... | #Icon_and_Unicon | Icon and Unicon | link math, factors
procedure main()
write("choose(5,3)=",binocoef(5,3))
end |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Binomial.bas"
110 PRINT "Binomial (5,3) =";BINOMIAL(5,3)
120 DEF BINOMIAL(N,K)
130 LET R=1:LET D=N-K
140 IF D>K THEN LET K=D:LET D=N-K
150 DO WHILE N>K
160 LET R=R*N:LET N=N-1
170 DO WHILE D>1 AND MOD(R,D)=0
180 LET R=R/D:LET D=D-1
190 LOOP
200 LOOP
210 LET BINOMIAL=R
220 END DE... |
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 ... | #Yabasic | Yabasic | sub fibonacci (n)
n1 = 0
n2 = 1
for k = 1 to abs(n)
sum = n1 + n2
n1 = n2
n2 = sum
next k
if n < 0 then
return n1 * ((-1) ^ ((-n) + 1))
else
return n1
end if
end sub |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbe... | #ALGOL_68 | ALGOL 68 | # parse the command line - ignore errors #
INT emirp from := 1; # lowest emirp required #
INT emirp to := 10; # highest emirp required #
BOOL value range := FALSE; # TRUE if the range is the value of the emirps #
... |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a... | #EchoLisp | EchoLisp |
(require 'struct)
(decimals 4)
(string-delimiter "")
(struct pt (x y))
(define-syntax-id _.x (struct-get _ #:pt.x))
(define-syntax-id _.y (struct-get _ #:pt.y))
(define (E-zero) (pt Infinity Infinity))
(define (E-zero? p) (= (abs p.x) Infinity))
(define (E-neg p) (pt p.x (- p.y)))
;; magic formulae from "C"
... |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Haskell | Haskell | data Fruit = Apple | Banana | Cherry deriving Enum |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Huginn | Huginn | enum FRUIT {
APPLE,
BANANA,
CHERRY
} |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Icon_and_Unicon | Icon and Unicon | fruits := [ "apple", "banana", "cherry", "apple" ] # a list keeps ordered data
fruits := set("apple", "banana", "cherry") # a set keeps unique data
fruits := table() # table keeps an unique data with values
fruits["apple"] := 1
fruits["banana"] := 2
fruits["cher... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #F.23 | F# |
// Generate random numbers using Rule 30. Nigel Galloway: August 1st., 2019
eca 30 [|yield 1; yield! Array.zeroCreate 99|]|>Seq.chunkBySize 8|>Seq.map(fun n->n|>Array.mapi(fun n g->g.[0]<<<(7-n))|>Array.sum)|>Seq.take 10|>Seq.iter(printf "%d "); printfn ""
|
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #Go | Go | package main
import "fmt"
const n = 64
func pow2(x uint) uint64 {
return uint64(1) << x
}
func evolve(state uint64, rule int) {
for p := 0; p < 10; p++ {
b := uint64(0)
for q := 7; q >= 0; q-- {
st := state
b |= (st & 1) << uint(q)
state = 0
... |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #ALGOL_68 | ALGOL 68 | # declare a string variable and assign an empty string to it #
STRING s := "";
# test the string is empty #
IF s = "" THEN write( ( "s is empty", newline ) ) FI;
# test the string is not empty #
IF s /... |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Apex | Apex |
String.isBlank(record.txt_Field__c);
--Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.
|
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining eq... | #Phix | Phix | requires(64)
enum X, Y -- rational ec point
enum A, B, N, G, R -- elliptic curve parameters
-- also signature pair(A,B)
constant mxN = 1073741789 -- maximum modulus
constant mxr = 1073807325 -- max order G = mxN + 65536
constant inf = -2147483647 -- symbolic infinity
sequence e ... |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #C.23 | C# | using System;
using System.IO;
class Program
{
static void Main( string[] args )
{
foreach ( string dir in args )
{
Console.WriteLine( "'{0}' {1} empty", dir, IsDirectoryEmpty( dir ) ? "is" : "is not" );
}
}
private static bool IsDirectoryEmpty( string dir )
{... |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #C.2B.2B | C++ |
#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i) {
path p(argv[i]);
if (exists(p) && is_directory(p))
std::cout << "'" << argv[i] << "' is" << (!is_empty(p) ? " not" : "") << "... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Ada | Ada | procedure Empty is
begin
null;
end; |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Agena | Agena | |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Tau = 2*Pi;Protect[Tau]
{"Tau"}
Tau = 2
->Set::wrsym: Symbol Tau is Protected. |
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.
| #MBS | MBS | CONSTANT INT foo=640; |
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.
| #Nemerle | Nemerle | def foo = 42; // immutable by default
mutable bar = "O'Malleys"; // mutable because you asked it to be |
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.
| #Nim | Nim | var x = "mutablefoo" # Mutable variable
let y = "immutablefoo" # Immutable variable, at runtime
const z = "constantfoo" # Immutable constant, at compile time
x[0] = 'M'
y[0] = 'I' # Compile error: 'y[0]' cannot be assigned to
z[0] = 'C' # Compile error: 'z[0]' cannot be assigned to |
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... | #C.23 | C# |
using System;
using System.Collections.Generic;
namespace Entropy
{
class Program
{
public static double logtwo(double num)
{
return Math.Log(num)/Math.Log(2);
}
public static void Main(string[] args)
{
label1:
string input = Console.ReadLine();
double infoC=0;
Dictionary<char,double> table ... |
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 ... | #C.23 | C# |
using System;
using System.Linq;
namespace RosettaCode.Tasks
{
public static class EthiopianMultiplication_Task
{
public static void Test ( )
{
Console.WriteLine ( "Ethiopian Multiplication" );
int A = 17, B = 34;
Console.WriteLine ( "Recursion: {0}*{1}={2}", A, B, EM_Recursion ( A, B ) );
Console... |
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}
... | #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println(ex([]int32{-7, 1, 5, 2, -4, 3, 0}))
// sequence of 1,000,000 random numbers, with values
// chosen so that it will be likely to have a couple
// of equalibrium indexes.
rand.Seed(time.Now().UnixNano())
v... |
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
| #LIL | LIL |
static LILCALLBACK lil_value_t fnc_env(lil_t lil, size_t argc, lil_value_t* argv)
{
if (!argc) return NULL;
return lil_alloc_string(getenv(lil_to_string(argv[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
| #Lingo | Lingo | sx = xtra("Shell").new()
if the platform contains "win" then
path = sx.shell_cmd("echo %PATH%").line[1]
else
path = sx.shell_cmd("echo $PATH").line[1]
end if |
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
| #Logtalk | Logtalk | os::environment_variable('PATH', Path). |
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... | #Ruby | Ruby | def isEsthetic(n, b)
if n == 0 then
return false
end
i = n % b
n2 = (n / b).floor
while n2 > 0
j = n2 % b
if (i - j).abs != 1 then
return false
end
n2 = n2 / b
i = j
end
return true
end
def listEsths(n, n2, m, m2, perLine, all)
... |
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... | #Forth | Forth |
: sq dup * ;
: 5^ dup sq sq * ;
create pow5 250 cells allot
:noname
250 0 DO i 5^ pow5 i cells + ! LOOP ; execute
: @5^ cells pow5 + @ ;
: solution? ( n -- n )
pow5 250 cells bounds DO
dup i @ = IF drop i pow5 - cell / unloop EXIT THEN
cell +LOOP drop 0 ;
\ GFORTH only provides 2 index ... |
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... | #Nial | Nial | fact is recur [ 0 =, 1 first, pass, product, -1 +] |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #C.23 | C# | namespace RosettaCode
{
using System;
public static class EvenOrOdd
{
public static bool IsEvenBitwise(this int number)
{
return (number & 1) == 0;
}
public static bool IsOddBitwise(this int number)
{
return (number & 1) != 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... | #Racket | Racket |
(define (ODE-solve f init
#:x-max x-max
#:step h
#:method (method euler))
(reverse
(iterate-while (λ (x . y) (<= x x-max)) (method f h) init)))
|
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... | #Raku | Raku | sub euler ( &f, $y0, $a, $b, $h ) {
my $y = $y0;
my @t_y;
for $a, * + $h ... * > $b -> $t {
@t_y[$t] = $y;
$y += $h * f( $t, $y );
}
return @t_y;
}
constant COOLING_RATE = 0.07;
constant AMBIENT_TEMP = 20;
constant INITIAL_TEMP = 100;
constant INITIAL_TIME = 0;
constant FINAL... |
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... | #J | J | 3 ! 5
10 |
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... | #Java | Java | public class Binomial {
// precise, but may overflow and then produce completely incorrect results
private static long binomialInt(int n, int k) {
if (k > n - k)
k = n - k;
long binom = 1;
for (int i = 1; i <= k; i++)
binom = binom * (n + 1 - i) / i;
r... |
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 ... | #zkl | zkl | var fibShift=fcn(ab){ab.append(ab.sum()).pop(0)}.fp(L(0,1)); |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbe... | #Arturo | Arturo | emirps: function [upto][
result: new []
loop range .step: 2 11 upto 'x [
if prime? x [
reversed: to :integer reverse to :string x
if x <> reversed [
if prime? reversed ->
'result ++ x
]
]
]
return result
]
lst: emi... |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a... | #Go | Go | package main
import (
"fmt"
"math"
)
const bCoeff = 7
type pt struct{ x, y float64 }
func zero() pt {
return pt{math.Inf(1), math.Inf(1)}
}
func is_zero(p pt) bool {
return p.x > 1e20 || p.x < -1e20
}
func neg(p pt) pt {
return pt{p.x, -p.y}
}
func dbl(p pt) pt {
if is_zero(p) {
... |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Inform_7 | Inform 7 | Fruit is a kind of value. The fruits are apple, banana, and cherry. |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #J | J | enum =: cocreate''
( (;:'apple banana cherry') ,L:0 '__enum' ) =: i. 3
cherry__enum
2 |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #Java | Java | enum Fruits{
APPLE, BANANA, CHERRY
} |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #Haskell | Haskell | import CellularAutomata (fromList, rule, runCA)
import Control.Comonad
import Data.List (unfoldr)
rnd = fromBits <$> unfoldr (pure . splitAt 8) bits
where
size = 80
bits =
extract
<$> runCA
(rule 30)
(fromList (1 : replicate size 0))
fromBits = foldl ((+) . (2 *)) 0 |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #J | J |
coclass'ca'
DOC =: 'locale creation: (RULE ; INITIAL_STATE) conew ''ca'''
create =: 3 :'''RULE STATE'' =: y'
next =: 3 :'STATE =: RULE (((8$2) #: [) {~ [: #. [: -. [: |: |.~"1 0&_1 0 1@]) STATE'
coclass'base'
coclass'rng'
coinsert'ca'
bit =: 3 :'([ next) ({. STATE)'
byte =: [: #. [: , [: bit"0 (i.8)"_
coclass'base'... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #Julia | Julia | function evolve(state, rule, N=64)
B(x) = UInt64(1) << x
for p in 0:9
b = UInt64(0)
for q in 7:-1:0
st = UInt64(state)
b |= (st & 1) << q
state = UInt64(0)
for i in 0:N-1
t1 = (i > 0) ? st >> (i - 1) : st >> (N - 1)
... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #Kotlin | Kotlin | // version 1.1.51
const val N = 64
fun pow2(x: Int) = 1L shl x
fun evolve(state: Long, rule: Int) {
var state2 = state
for (p in 0..9) {
var b = 0
for (q in 7 downTo 0) {
val st = state2
b = (b.toLong() or ((st and 1L) shl q)).toInt()
state2 = 0L
... |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #APL | APL |
⍝⍝ Assign empty string to A
A ← ''
0 = ⍴∊ A
1
~0 = ⍴∊ A
0
|
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #AppleScript | AppleScript |
-- assign empty string to str
set str to ""
-- check if string is empty
if str is "" then
-- str is empty
end if
-- or
if id of str is {} then
-- str is empty
end if
-- or
if (count of str) is 0 then
-- str is empty
end if
-- check if string is not empty
if str is not "" then
-- string is not empty
end if... |
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining eq... | #Python | Python |
from collections import namedtuple
from hashlib import sha256
from math import ceil, log
from random import randint
from typing import NamedTuple
# Bitcoin ECDSA curve
secp256k1_data = dict(
p=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F, # Field characteristic
a=0x0, # Curve param a... |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #Clojure | Clojure | (require '[clojure.java.io :as io])
(defn empty-dir? [path]
(let [file (io/file path)]
(assert (.exists file))
(assert (.isDirectory file))
(-> file .list empty?))) ; .list ignores "." and ".." |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #CoffeeScript | CoffeeScript |
fs = require 'fs'
is_empty_dir = (dir) ->
throw Error "#{dir} is not a dir" unless fs.statSync(dir).isDirectory()
# readdirSync does not return . or ..
fns = fs.readdirSync dir
fns.length == 0
|
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #Common_Lisp | Common Lisp |
(defun empty-directory-p (path)
(and (null (directory (concatenate 'string path "/*")))
(null (directory (concatenate 'string path "/*/")))))
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Aime | Aime | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #ALGOL_60 | ALGOL 60 | 'BEGIN' 'END' |
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.
| #OCaml | OCaml | type im_string
val create : int -> im_string
val make : int -> char -> im_string
val of_string : string -> im_string
val to_string : im_string -> string
val copy : im_string -> im_string
val sub : im_string -> int -> int -> im_string
val length : im_string -> int
val get : im_string -> int -> char
val iter : (char ->... |
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.
| #Oforth | Oforth | Object Class new: MyClass(a, b)
MyClass method: setA(value) value := a ;
MyClass method: setB(value) value := b ;
MyClass method: initialize(v, w) self setA(v) self setB(w) ;
MyClass new(1, 2) // OK : An immutable object
MyClass new(1, 2) setA(4) // KO : An immutable object can't be updat... |
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.
| #PARI.2FGP | PARI/GP | use constant PI => 3.14159;
use constant MSG => "Hello World"; |
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... | #C.2B.2B | C++ | #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
double log2( double number ) {
return log( number ) / log( 2 ) ;
}
int main( int argc , char *argv[ ] ) {
std::string teststring( argv[ 1 ] ) ;
std::map<char , int> frequencies ;
for ( char c : teststring )
f... |
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 ... | #C.2B.2B | C++ | template<int N>
struct Half
{
enum { Result = N >> 1 };
};
template<int N>
struct Double
{
enum { Result = N << 1 };
};
template<int N>
struct IsEven
{
static const bool Result = (... |
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}
... | #Haskell | Haskell | import System.Random (randomRIO)
import Data.List (findIndices, takeWhile)
import Control.Monad (replicateM)
import Control.Arrow ((&&&))
equilibr xs =
findIndices (\(a, b) -> sum a == sum b) . takeWhile (not . null . snd) $
flip ((&&&) <$> take <*> (drop . pred)) xs <$> [1 ..]
langeSliert = replicateM 2000 (ra... |
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
| #LSL | LSL | default {
state_entry() {
llOwnerSay("llGetTimestamp()="+(string)llGetTimestamp());
llOwnerSay("llGetEnergy()="+(string)llGetEnergy());
llOwnerSay("llGetFreeMemory()="+(string)llGetFreeMemory());
llOwnerSay("llGetMemoryLimit()="+(string)llGetMemoryLimit());
}
} |
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
| #Lua | Lua | print( os.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
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
\\ using read only variablles
Print "Platform: ";Platform$
Print "Computer Os: "; Os$
Print "Type of OS: ";OsBit;" bit"
Print "Computer Name:"; Computer$
Print "User Name: "; User.Name$
\\ using WScript.Shell
Declare objShell "WScript.Shell"
With... |
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
| #Make | Make | TARGET = $(HOME)/some/thing.txt
foo:
echo $(TARGET) |
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... | #Rust | Rust | // [dependencies]
// radix_fmt = "1.0"
// Returns the next esthetic number in the given base after n, where n is an
// esthetic number in that base or one less than a power of base.
fn next_esthetic_number(base: u64, n: u64) -> u64 {
if n + 1 < base {
return n + 1;
}
let mut a = n / base;
let ... |
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... | #Fortran | Fortran | C EULER SUM OF POWERS CONJECTURE - FORTRAN IV
C FIND I1,I2,I3,I4,I5 : I1**5+I2**5+I3**5+I4**5=I5**5
INTEGER I,P5(250),SUMX
MAXN=250
DO 1 I=1,MAXN
1 P5(I)=I**5
DO 6 I1=1,MAXN
DO 6 I2=1,MAXN
DO 6 I3=1,MAXN
DO 6 I4=1,MAXN
SUMX=P5(I1)+P5(I2)+P5(I3)+P5(I4)
I5=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... | #Nickle | Nickle | int fact(int n) { return 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... | #C.2B.2B | C++ | bool isOdd(int x)
{
return x % 2;
}
bool isEven(int x)
{
return !(x % 2);
} |
http://rosettacode.org/wiki/Euler_method | Euler method | Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.
The ODE has to be provided in the following form:
d
y
(
t
)
d
t
=
f... | #REXX | REXX | /* REXX ***************************************************************
* 24.05.2013 Walter Pachl translated from PL/I
**********************************************************************/
Numeric Digits 100
T0=100
Tr=20
k=0.07
h=2
x=t0
Call head
do t=0 to 100 by 2
Select
When t<=4 | t>=9... |
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... | #JavaScript | JavaScript | function binom(n, k) {
var coeff = 1;
var i;
if (k < 0 || k > n) return 0;
for (i = 0; i < k; i++) {
coeff = coeff * (n - i) / (i + 1);
}
return coeff;
}
console.log(binom(5, 3)); |
http://rosettacode.org/wiki/Evaluate_binomial_coefficients | Evaluate binomial coefficients | This programming task, is to calculate ANY binomial coefficient.
However, it has to be able to output
(
5
3
)
{\displaystyle {\binom {5}{3}}}
, which is 10.
This formula is recommended:
(
n
k
)
=
n
!
(
n
−
k
)
!
k
!
=
n
(
n
−
1
)
(
n
−
2
)
…
(
n
−
k
+
1
)
k
(
k
−
1... | #jq | jq | # nCk assuming n >= k
def binomial(n; k):
if k > n / 2 then binomial(n; n-k)
else reduce range(1; k+1) as $i (1; . * (n - $i + 1) / $i)
end;
def task:
.[0] as $n | .[1] as $k
| "\($n) C \($k) = \(binomial( $n; $k) )";
;
([5,3], [100,2], [ 33,17]) | task
|
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 ... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM Only positive numbers
20 LET n=10
30 LET n1=0: LET n2=1
40 FOR k=1 TO n
50 LET sum=n1+n2
60 LET n1=n2
70 LET n2=sum
80 NEXT k
90 PRINT n1 |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbe... | #AutoHotkey | AutoHotkey | SetBatchLines, -1
p := 1
Loop, 20 {
p := NextEmirp(p)
a .= p " "
}
p := 7700
Loop {
p := NextEmirp(p)
if (p > 8000)
break
b .= p " "
}
p :=1
Loop, 10000
p := NextEmirp(p)
MsgBox, % "First twenty emirps: " a
. "`nEmirps between 7,700 and 8,000: " b
. "`n10,000th emirp: " p
IsPrime(n) {
if (n < 2)
return, ... |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a... | #Haskell | Haskell | import Data.Monoid
import Control.Monad (guard)
import Test.QuickCheck (quickCheck) |
http://rosettacode.org/wiki/Elliptic_curve_arithmetic | Elliptic curve arithmetic | Elliptic curves are sometimes used in cryptography as a way to perform digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a... | #J | J | zero=: _j_
isZero=: 1e20 < |@{.@+.
neg=: +
dbl=: monad define
'p_x p_y'=. +. p=. y
if. isZero p do. p return. end.
L=. 1.5 * p_x*p_x % p_y
r=. (L*L) - 2*p_x
r j. (L * p_x-r) - p_y
)
add=: dyad define
'p_x p_y'=. +. p=. x
'q_x q_y'=. +. q=. y
if. x=y do. dbl x return. end.
if. isZero x do. y re... |
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #JavaScript | JavaScript |
// enum fruits { apple, banana, cherry }
var f = "apple";
if(f == "apple"){
f = "banana";
}
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #jq | jq | 1 | while(true; .+1)
|
http://rosettacode.org/wiki/Enumerations | Enumerations | Task
Create an enumeration of constants with and without explicit values.
| #JScript.NET | JScript.NET | enum fruits { apple, banana, cherry }
enum fruits { apple = 0, banana = 1, cherry = 2 } |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | FromDigits[#, 2] & /@ Partition[Flatten[CellularAutomaton[30, {{1}, 0}, {200, 0}]], 8] |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #Nim | Nim | const N = 64
template pow2(x: uint): uint = 1u shl x
proc evolve(state: uint; rule: Positive) =
var state = state
for _ in 1..10:
var b = 0u
for q in countdown(7, 0):
let st = state
b = b or (st and 1) shl q
state = 0
for i in 0u..<N:
let t = (st shr (i - 1) or st shl (N ... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator | Elementary cellular automaton/Random Number Generator | Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi... | #Pascal | Pascal | Program Rule30;
//http://en.wikipedia.org/wiki/Next_State_Rule_30;
//http://mathworld.wolfram.com/Rule30.html
{$IFDEF FPC}
{$Mode Delphi}{$ASMMODE INTEL}
{$OPTIMIZATION ON,ALL}
// {$CODEALIGN proc=1}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
SysUtils;
const
maxRounds = 2*1000*1000;
rounds = 10;
var
R... |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program strEmpty.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szNotEmptyString: .asciz "String is not empty. \n"
szEmptyString: .asciz "String is e... |
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm | Elliptic Curve Digital Signature Algorithm | Elliptic curves.
An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form
y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),
together with a special point 𝒪 called the point at infinity.
The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp,
which satisfy the above defining eq... | #Raku | Raku | use Digest::SHA256::Native;
# Following data taken from the C entry
our (\A,\B,\P,\O,\Gx,\Gy) = (355, 671, 1073741789, 1073807281, 13693, 10088);
#`{ Following data taken from the Julia entry; 256-bit; tested
our (\A,\B,\P,\O,\Gx,\Gy) = (0, 7, # https://en.bitcoin.it/wiki/Secp256k1
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF... |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #D | D | import std.stdio, std.file;
void main() {
auto dir = "somedir";
writeln(dir ~ " is empty: ", dirEmpty(dir));
}
bool dirEmpty(string dirname) {
if (!exists(dirname) || !isDir(dirname))
throw new Exception("dir not found: " ~ dirname);
return dirEntries(dirname, SpanMode.shallow).empty;
} |
http://rosettacode.org/wiki/Empty_directory | Empty directory | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other... | #Delphi | Delphi |
program Empty_directory;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IOUtils;
function IsDirectoryEmpty(dir: string): Boolean;
var
count: Integer;
begin
count := Length(TDirectory.GetFiles(dir)) + Length(TDirectory.GetDirectories(dir));
Result := count = 0;
end;
var
i: Integer;
const
CHECK... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #ALGOL_68 | ALGOL 68 | ~ |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.