task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Simula | Simula | BEGIN
END |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Slate | Slate | |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | primes = Prime[Range[10^7]];
gaps = {Differences[primes], Most[primes]} // Transpose;
tmp = GatherBy[gaps, First][[All, 1]];
tmp = SortBy[tmp, First];
starts = Association[Rule @@@ tmp];
set = {Most[tmp[[All, 1]]], Abs@Differences[tmp[[All, 2]]]} // Transpose;
data = Table[{n, k} = SelectFirst[set, Last/*GreaterThan[10... |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Pascal | Pascal | program primesieve;
// sieving small ranges of 65536
//{$O+,R+}
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=32}
uses
sysutils;
{$ENDIF}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
const
smlPrimes :array [0..10] of Byte = (2,3,5,7,11,13,17,19,23,29,31);
maxPreSievePrime = 17;
sie... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public static class ElementWiseOperations
{
private static readonly Dictionary<string, Func<double, double, double>> operations =
new Dictionary<string, Func<double, double, double>> {
{ "add", (a, b) => a + b },
{ ... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #AutoHotkey | AutoHotkey | divident := 580
divisor := 34
answer := accumulator := 0
obj := [] , div := divisor
while (div < divident)
{
obj[2**(A_Index-1)] := div ; obj[powers_of_2] := doublings
div *= 2 ; double up
}
while obj.MaxIndex() ; iterate rows "in the reverse order"
{
if (accumulator + obj[obj.MaxIndex()] <= divid... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace EgyptianFractions {
class Program {
class Rational : IComparable<Rational>, IComparable<int> {
public BigInteger Num { get; }
public ... |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then outp... | #Perl | Perl | $str = "eertree";
for $n (1 .. length($str)) {
for $m (1 .. length($str)) {
$strrev = "";
$strpal = substr($str, $n-1, $m);
if ($strpal ne "") {
for $p (reverse 1 .. length($strpal)) {
$strrev .= substr($strpal, $p-1, 1);
}
($strpal eq $strrev) and push @pal... |
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 ... | #Quackery | Quackery | [ 1 & not ] is even ( n --> b )
[ 1 << ] is double ( n --> n )
[ 1 >> ] is halve ( n --> n )
[ dup 0 < unrot abs
[ dup 0 = iff nip done
over double over halve
recurse
swap even
iff nip else + ]
swap if negate ] is e* ( n n... |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #EchoLisp | EchoLisp |
(lib 'types) ;; int32 vectors
(lib 'plot)
(define-constant BIT0 0)
(define-constant BIT1 (rgb 0.8 0.9 0.7)) ;; colored bit 1
;; integer to pattern
(define ( n->pat n)
(for/vector ((i 8))
#:when (bitwise-bit-set? n i)
(for/vector ((j (in-range 2 -1 -1)))
(if (bitwise-bit-set? i j) BIT1 BIT0 ))))
;; tes... |
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... | #Tcl | Tcl | proc ifact n {
for {set i $n; set sum 1} {$i >= 2} {incr i -1} {
set sum [expr {$sum * $i}]
}
return $sum
} |
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... | #.E0.AE.89.E0.AE.AF.E0.AE.BF.E0.AE.B0.E0.AF.8D.2FUyir | உயிர்/Uyir | முதன்மை என்பதின் வகை எண் பணி {{
எ இன் வகை எண்{$5} = 0;
படை வகை சரம்;
"எண்ணைக் கொடுங்கள்? ") ஐ திரை.இடு;
எ = எண்{$5} ஐ விசை.எடு;
ஒருக்கால் (எ.இருமம்(0) == 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... | #VBA | VBA | 4 ways = 4 Functions :
IsEven ==> Use the even and odd predicates
IsEven2 ==> Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even
IsEven3 ==> Divide i by 2. The remainder equals 0 if i is even.
IsEven4 ==> Use modular congruences |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Factor | Factor | USING: accessors io io.encodings.utf8 io.servers io.sockets threads ;
IN: rosetta.echo
CONSTANT: echo-port 12321
: handle-client ( -- )
[ print flush ] each-line ;
: <echo-server> ( -- threaded-server )
utf8 <threaded-server>
"echo server" >>name
echo-port >>insecure
[ handle-client... |
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... | #XPL0 | XPL0 | code Text=12;
string 0; \use zero-terminated convention, instead of MSb set
char S;
[S:= ""; \assign an empty string
if S(0) = 0 then Text(0, "empty
");
S:= "Hello";
if S(0) # 0 then Text(0, "not empty
");
] |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Z80_Assembly | Z80 Assembly | EmptyString:
byte 0 |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Smalltalk | Smalltalk | [] |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #SNOBOL4 | SNOBOL4 | end |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #SNUSP | SNUSP | $#
|
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
use warnings;
use ntheory qw( primes );
my @gaps;
my $primeref = primes( 1e9 );
for my $i ( 2 .. $#$primeref )
{
my $diff = $primeref->[$i] - $primeref->[$i - 1];
$gaps[ $diff >> 1 ] //= $primeref->[$i - 1];
}
... |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Phix | Phix | with javascript_semantics
constant limit = iff(platform()=JS?1e7:1e8),
gslim = 250
sequence primes = get_primes_le(limit*4),
gapstarts = repeat(0,gslim)
for i=2 to length(primes) do
integer gap = primes[i]-primes[i-1]
if gapstarts[gap]=0 then
gapstarts[gap] = primes[i-1]
end if
en... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #C.2B.2B | C++ | #include <cassert>
#include <cmath>
#include <iostream>
#include <valarray>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns) {
elements_.resize(rows * columns);
}
matrix(size_t rows, size_t columns, scalar_type value)
... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #APL | APL |
is←{ t←⍵ ⋄ ⎕this⍎⍺,'←t' } ⍝⍝ the 'Slick Willie' function ;)
'test' is ⍳2 3
test
1 1 1 2 1 3
2 1 2 2 2 3
|
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #BaCon | BaCon |
'---Ported from the c code example to BaCon by bigbass
'==================================================================================
FUNCTION EGYPTIAN_DIVISION(long dividend, long divisor, long remainder) TYPE long
'==================================================================================
'--- re... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #C.2B.2B | C++ | #include <iostream>
#include <optional>
#include <vector>
#include <string>
#include <sstream>
#include <boost/multiprecision/cpp_int.hpp>
typedef boost::multiprecision::cpp_int integer;
struct fraction {
fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {}
integer numerator;
i... |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then outp... | #Phix | Phix | with javascript_semantics
enum LEN,SUFF,CHARS,NEXT
function node(integer len, suffix=1, string chars="", sequence next={})
return {len,suffix,chars,next} -- must match above enum!
end function
function eertree(string s)
sequence tree = {node(-1), -- odd lengths
node(0)} -- even lengths
inte... |
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 ... | #R | R | halve <- function(a) floor(a/2)
double <- function(a) a*2
iseven <- function(a) (a%%2)==0
ethiopicmult <- function(plier, plicand, tutor=FALSE) {
if (tutor) { cat("ethiopic multiplication of", plier, "and", plicand, "\n") }
result <- 0
while(plier >= 1) {
if (!iseven(plier)) { result <- result + plicand }
... |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #Elixir | Elixir | defmodule Elementary_cellular_automaton do
def run(start_str, rule, times) do
IO.puts "rule : #{rule}"
each(start_str, rule_pattern(rule), times)
end
defp rule_pattern(rule) do
list = Integer.to_string(rule, 2) |> String.pad_leading(8, "0")
|> String.codepoints |> Enum.reverse
Enum.ma... |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #F.23 | F# |
// Elementary Cellular Automaton . Nigel Galloway: July 31st., 2019
let eca N=
let N=Array.init 8 (fun n->(N>>>n)%2)
Seq.unfold(fun G->Some(G,[|yield Array.last G; yield! G; yield Array.head G|]|>Array.windowed 3|>Array.map(fun n->N.[n.[2]+2*n.[1]+4*n.[0]])))
|
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... | #TI-83_BASIC | TI-83 BASIC | 10→N
N! ---> 362880
prod(seq(I,I,1,N)) ---> 362880 |
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... | #VBScript | VBScript |
Function odd_or_even(n)
If n Mod 2 = 0 Then
odd_or_even = "Even"
Else
odd_or_even = "Odd"
End If
End Function
WScript.StdOut.Write "Please enter a number: "
n = WScript.StdIn.ReadLine
WScript.StdOut.Write n & " is " & odd_or_even(CInt(n))
WScript.StdOut.WriteLine
|
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... | #Verilog | Verilog | module main;
integer i;
initial begin
for (i = 1; i <= 10; i = i+1) begin
if (i % 2 == 0) $display(i, " is even");
else $display(i, " is odd");
end
$finish ;
end
endmodule |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Forth | Forth | include unix/socket.fs
128 constant size
: (echo) ( sock buf -- sock buf )
begin
cr ." waiting..."
2dup 2dup size read-socket nip
dup 0>
while
." got: " 2dup type
rot write-socket
repeat
drop drop drop ;
create buf size allot
: echo-server ( port -- )
cr ." Listening on " dup .
... |
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... | #zkl | zkl | s:=""; // or s:=String, String is the object ""
s.toBool() //-->False
if (s) println("not empty") |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Zoomscript | Zoomscript | var string
string = ""
if eq string ""
print "The string is empty."
else
print "The string is not empty."
endif |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Sparkling | Sparkling | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #SQL_PL | SQL PL |
SELECT 1 FROM sysibm.sysdummy1;
|
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #SSEM | SSEM | 00000000000000000000000000000000 0. 0 to CI jump to store(0) + 1
00000000000000000000000000000000 1. 0 to CI jump to store(0) + 1 |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Python | Python | """ https://rosettacode.org/wiki/Earliest_difference_between_prime_gaps """
from primesieve import primes
LIMIT = 10**9
pri = primes(LIMIT * 5)
gapstarts = {}
for i in range(1, len(pri)):
if pri[i] - pri[i - 1] not in gapstarts:
gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]
PM, GAP1, = 10, 2
while True:... |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Raku | Raku | use Math::Primesieve;
use Lingua::EN::Numbers;
my $iterator = Math::Primesieve::iterator.new;
my @gaps;
my $last = 2;
for 1..9 {
my $m = exp $_, 10;
my $this;
loop {
$this = (my $p = $iterator.next) - $last;
if !@gaps[$this].defined {
@gaps[$this]= $last;
check-... |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #11l | 11l | F iseban(n)
I n == 0
R 0B
V (b, r) = divmod(n, 1'000'000'000)
(V m, r) = divmod(r, 1'000'000)
(V t, r) = divmod(r, 1'000)
m = I m C 30..66 {m % 10} E m
t = I t C 30..66 {t % 10} E t
r = I r C 30..66 {r % 10} E r
R Set([b, m, t, r]) <= Set([0, 2, 4, 6])
print(‘eban numbers up to and inclu... |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not u... | #ALGOL_68 | ALGOL 68 | BEGIN # find Duffinian numbers: non-primes relatively prime to their divisor count #
INT max number := 500 000; # largest number we will consider #
# iterative Greatest Common Divisor routine, returns the gcd of m and n #
PROC gcd = ( INT m, n )INT:
BEGIN
INT a ... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Clojure | Clojure | (defn initial-mtx [i1 i2 value]
(vec (repeat i1 (vec (repeat i2 value)))))
(defn operation [f mtx1 mtx2]
(if (vector? mtx1)
(vec (map #(vec (map f %1 %2)) mtx1 mtx2)))
(recur f (initial-mtx (count mtx2) (count (first mtx2)) mtx1) mtx2)
)) |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Arturo | Arturo | name: strip input "enter a variable name: "
value: strip input "enter a variable value: "
let name value
print ["the value of variable" name "is:" var name] |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #AutoHotkey | AutoHotkey | InputBox, Dynamic, Variable Name
%Dynamic% = hello
ListVars
MsgBox % %dynamic% ; says hello |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
uint64_t egyptian_division(uint64_t dividend, uint64_t divisor, uint64_t *remainder) {
// remainder is an out parameter, pass NULL if you do not need the remainder
static uint64_t powers[64];
static uint64_t doublings[64];
int i;... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #Common_Lisp | Common Lisp | (defun egyption-fractions (x y &optional acc)
(let* ((a (/ x y)))
(cond
((> (numerator a) (denominator a))
(multiple-value-bind (q r) (floor x y)
(if (zerop r)
(cons q acc)
(egyption-fractions r y (cons q acc)))))
((= (numerator a) 1) (reverse (cons a acc)))
(t (let ((b (ceiling y ... |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then outp... | #Python | Python | #!/bin/python
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {} # edges (or forward links)
self.link = None # suffix link (backward links)
self.len = 0 # the length of the node
class Eertree(object):
def __init__(self):
self.nodes = []
# two initial root nodes... |
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 ... | #Racket | Racket | #lang racket
(define (halve i) (quotient i 2))
(define (double i) (* i 2))
;; `even?' is built-in
(define (ethiopian-multiply x y)
(cond [(zero? x) 0]
[(even? x) (ethiopian-multiply (halve x) (double y))]
[else (+ y (ethiopian-multiply (halve x) (double y)))]))
(ethiopian-multiply 17 34) ; -> 5... |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #Factor | Factor | USING: assocs formatting grouping io kernel math math.bits
math.combinatorics sequences sequences.extras ;
: make-rules ( n -- assoc )
{ f t } 3 selections swap make-bits 8 f pad-tail zip ;
: next-state ( assoc seq -- assoc seq' )
dupd 3 circular-clump -1 rotate [ of ] with map ;
: first-state ( -- seq ) ... |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #FreeBASIC | FreeBASIC |
#define NCELLS 400
#define border 16
dim as ubyte rule = 110
sub evolve( row as uinteger, rule as ubyte, pattern() as ubyte )
dim as ubyte newp(NCELLS)
dim as uinteger i
dim as ubyte lookup
for i = 0 to NCELLS-1
pset (i + border, row + border ), pattern(i)*15
lookup = 4*pattern((i-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... | #TI-89_BASIC | TI-89 BASIC | factorial(x)
Func
Return Π(y,y,1,x)
EndFunc |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Dim str As String
Dim num As Integer
While True
Console.Write("Enter an integer or 0 to finish: ")
str = Console.ReadLine()
If Integer.TryParse(str, num) Then
If num = 0 Then
Exit While
... |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Go | Go | package main
import (
"fmt"
"net"
"bufio"
)
func echo(s net.Conn, i int) {
defer s.Close();
fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr())
b := bufio.NewReader(s)
for {
line, e := b.ReadBytes('\n')
if e != nil {
break
}
s.Write(line)
}
fmt.Printf("%d: closed\n", i)
}
func ma... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | const std = @import("std");
pub fn main() !void {
// default is [:0]const u8, which is a 0-terminated string with len field
const str = "";
if (str.len == 0) {
std.debug.print("string empty\n", .{});
}
if (str.len != 0) {
std.debug.print("string empty\n", .{});
}
} |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Zig | Zig | const std = @import("std");
pub fn main() !void {
// default is [:0]const u8, which is a 0-terminated string with len field
const str = "";
if (str.len == 0) {
std.debug.print("string empty\n", .{});
}
if (str.len != 0) {
std.debug.print("string empty\n", .{});
}
} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Standard_ML | Standard ML | ; |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Stata | Stata | program define nop
version 15
end |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Suneido | Suneido | function () { } |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Rust | Rust | // [dependencies]
// primal = "0.3"
fn main() {
use std::collections::HashMap;
let mut primes = primal::Primes::all();
let mut last_prime = primes.next().unwrap();
let mut gap_starts = HashMap::new();
let mut find_gap_start = move |gap: usize| -> usize {
if let Some(start) = gap_starts... |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Sidef | Sidef | func prime_gap_records(upto) {
var gaps = []
var p = 3
each_prime(p.next_prime, upto, {|q|
gaps[q-p] := p
p = q
})
gaps.grep { defined(_) }
}
var gaps = prime_gap_records(1e8)
for m in (1 .. gaps.max.len) {
gaps.each_cons(2, {|p,q|
if (abs(q-p) > 10**m) {
... |
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps | Earliest difference between prime gaps | When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe... | #Wren | Wren | import "./math" for Int
import "/fmt" for Fmt
var limit = 1e9
var gapStarts = {}
var primes = Int.segmentedSieve(limit * 5, 8 * 1024 * 1024) // 8 MB cache
for (i in 1...primes.count) {
var gap = primes[i] - primes[i-1]
if (!gapStarts[gap]) gapStarts[gap] = primes[i-1]
}
var pm = 10
var gap1 = 2
while (true) {... |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #AppleScript | AppleScript | (*
Quickly generate all the (positive) eban numbers up to and including the
specified end number, then lose those before the start number.
0 is taken as "zero" rather than as "nought" or "nil".
WARNING: The getEbans() handler returns a potentially very long list of numbers.
Don't let such a list g... |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not u... | #AppleScript | AppleScript | on aliquotSum(n)
if (n < 2) then return 0
set sum to 1
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set sum to sum + limit
set limit to limit - 1
end if
repeat with i from 2 to limit
if (n mod i is 0) then set sum to sum + i + n div i
end rep... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #Common_Lisp | Common Lisp | (defun element-wise-matrix (fn A B)
(let* ((len (array-total-size A))
(m (car (array-dimensions A)))
(n (cadr (array-dimensions A)))
(C (make-array `(,m ,n) :initial-element 0.0d0)))
(loop for i from 0 to (1- len) do
(setf (row-major-aref C i)
(funcall f... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #AWK | AWK |
# syntax: GAWK -f DYNAMIC_VARIABLE_NAMES.AWK
# Variables created in GAWK's internal SYMTAB (symbol table) can only be accessed via SYMTAB[name]
BEGIN {
PROCINFO["sorted_in"] = "@ind_str_asc"
show_symbol_table()
while (1) {
printf("enter variable name? ")
getline v_name
if (v_name in SYMT... |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #C.23 | C# |
using System;
using System.Collections;
namespace Egyptian_division
{
class Program
{
public static void Main(string[] args)
{
Console.Clear();
Console.WriteLine();
Console.WriteLine(" Egyptian division ");
Console.WriteLine();
Console.Write(" Enter value of dividend : ");
int dividend = int... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #D | D | import std.stdio, std.bigint, std.algorithm, std.range, std.conv, std.typecons,
arithmetic_rational: Rat = Rational;
Rat[] egyptian(Rat r) pure nothrow {
typeof(return) result;
if (r >= 1) {
if (r.denominator == 1)
return [r, Rat(0, 1)];
result = [Rat(r.numerator / r.denom... |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then outp... | #Racket | Racket | #lang racket
(struct node (edges ; edges (or forward links)
link ; suffix link (backward links)
len) ; the length of the node
#:mutable)
(define (new-node link len) (node (make-hash) link len))
(struct eertree (nodes
rto ; odd length root node, or node -1
... |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then outp... | #Raku | Raku | my $str = "eertree";
my @pal = ();
my ($strrev,$strpal);
for (1 .. $str.chars) -> $n {
for (1 .. $str.chars) -> $m {
$strrev = "";
$strpal = $str.substr($n-1, $m);
if ($strpal ne "") {
for ($strpal.chars ... 1) -> $p {
$strrev ~= $strpal.substr($p-1,1);
}
($... |
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 ... | #Raku | Raku | sub halve (Int $n is rw) { $n div= 2 }
sub double (Int $n is rw) { $n *= 2 }
sub even (Int $n --> Bool) { $n %% 2 }
sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) {
my Int $r = 0;
while $a {
even $a or $r += $b;
halve $a;
double $b;
}
return $r;
}
say ethiopic-mult(17,34); |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #F.C5.8Drmul.C3.A6 | Fōrmulæ |
argc 4 < { ."Usage: " 0 argv sprint SPACE 1 argv sprint SPACE ."rule size\n"
."The \"rule\" and \"size\" are numbers.\n"
."0<=rule<=255\n" end }
zero gen
3 argv #s (#g) sto maxcell
2 argv (#g) sto rule
#g argc 5 >= { 4 argv #s (#g) sto gen }
@maxcell mem !maximize sto livingspace
@maxcell mem sto originallivingspace
... |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #Furor | Furor |
argc 4 < { ."Usage: " 0 argv sprint SPACE 1 argv sprint SPACE ."rule size\n"
."The \"rule\" and \"size\" are numbers.\n"
."0<=rule<=255\n" end }
zero gen
3 argv #s (#g) sto maxcell
2 argv (#g) sto rule
#g argc 5 >= { 4 argv #s (#g) sto gen }
@maxcell mem !maximize sto livingspace
@maxcell mem sto originallivingspace
... |
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... | #TorqueScript | TorqueScript | function Factorial(%num)
{
if(%num < 2)
return 1;
for(%a = %num-1; %a > 1; %a--)
%num *= %a;
return %num;
} |
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... | #Vlang | Vlang | fn test(n i64) {
print('Testing integer $n')
if n&1 == 0 {
print(' even')
}else{
print(' odd')
}
if n%2 == 0 {
println(' even')
}else{
println(' odd')
}
}
fn main(){
test(-2)
test(-1)
test(0)
test(1)
test(2)
} |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #WDTE | WDTE | let s => import 'stream';
let str => import 'strings';
let evenOrOdd n => (
let even n => == (% n 2) 0;
switch n {
even => 'even';
default => 'odd';
};
);
s.range 10
-> s.map (@ s n => str.format '{} is {}.' n (evenOrOdd n))
-> s.map (io.writeln io.stdout)
-> s.drain; |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Haskell | Haskell | module Main where
import Network (withSocketsDo, accept, listenOn, sClose, PortID(PortNumber))
import Control.Monad (forever)
import System.IO (hGetLine, hPutStrLn, hFlush, hClose)
import System.IO.Error (isEOFError)
import Control.Concurrent (forkIO)
import Control.Exception (bracket)
-- For convenience in testing, ... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Swift | Swift | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Symsyn | Symsyn | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Tcl | Tcl | |
http://rosettacode.org/wiki/Eban_numbers | Eban numbers |
Definition
An eban number is a number that has no letter e in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter e are banned.
The American version of spelling numbers will be used here (as opposed to the British).
2,000,000,000 is two billio... | #AutoHotkey | AutoHotkey | eban_numbers(min, max, show:=0){
counter := 0, output := ""
i := min
while ((i+=2) <= max)
{
b := floor(i / 1000000000)
r := Mod(i, 1000000000)
m := floor(r / 1000000)
r := Mod(i, 1000000)
t := floor(r / 1000)
r := Mod(r, 1000)
if (m >= 30 && m <= 66)
m := Mod(m, 10)
if (t >= 30 && t <= 66)
... |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not u... | #Arturo | Arturo | duffinian?: function [n]->
and? [not? prime? n]
[
fn: factors n
[1] = intersection factors sum fn fn
]
first50: new []
i: 0
while [50 > size first50][
if duffinian? i -> 'first50 ++ i
i: i + 1
]
print "The first 50 Duffinian numbers:"
loop split.every: 10 firs... |
http://rosettacode.org/wiki/Duffinian_numbers | Duffinian numbers | A Duffinian number is a composite number k that is relatively prime to its sigma sum σ.
The sigma sum of k is the sum of the divisors of k.
E.G.
161 is a Duffinian number.
It is composite. (7 × 23)
The sigma sum 192 (1 + 7 + 23 + 161) is relatively prime to 161.
Duffinian numbers are very common.
It is not u... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
bool duffinian(int n) {
if (n == 2)
return false;
int total = 1, power = 2, m = n;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (int p = 3; p * p <= n; p += 2) {
int sum = 1;
... |
http://rosettacode.org/wiki/Element-wise_operations | Element-wise operations | This task is similar to:
Matrix multiplication
Matrix transposition
Task
Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.
Implement:
addition
subtraction
multiplication
division
exponentiation
Extend the task if ... | #D | D | import std.stdio, std.typetuple, std.traits;
T[][] elementwise(string op, T, U)(in T[][] A, in U B) {
auto R = new typeof(return)(A.length, A[0].length);
foreach (r, row; A)
R[r][] = mixin("row[] " ~ op ~ (isNumeric!U ? "B" : "B[r][]"));
return R;
}
void main() {
const M = [[3, 5, 7], [1, 2, 3], [2, 4, ... |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #BASIC | BASIC | 10 INPUT "Enter a variable name", v$
20 KEYIN "LET "+v$+"=42" |
http://rosettacode.org/wiki/Dynamic_variable_names | Dynamic variable names | Task
Create a variable with a user-defined name.
The variable name should not be written in the program text, but should be taken from the user dynamically.
See also
Eval in environment is a similar task.
| #Batch_File | Batch File | @echo off
setlocal enableDelayedExpansion
set /p "name=Enter a variable name: "
set /p "value=Enter a value: "
::Create the variable and set its value
set "%name%=%value%"
::Display the value without delayed expansion
call echo %name%=%%%name%%%
::Display the value using delayed expansion
echo %name%=!%name%! |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #C.2B.2B | C++ | #include <cassert>
#include <iostream>
typedef unsigned long ulong;
/*
* Remainder is an out paramerter. Use nullptr if the remainder is not needed.
*/
ulong egyptian_division(ulong dividend, ulong divisor, ulong* remainder) {
constexpr int SIZE = 64;
ulong powers[SIZE];
ulong doublings[SIZE];
int... |
http://rosettacode.org/wiki/Egyptian_fractions | Egyptian fractions | An Egyptian fraction is the sum of distinct unit fractions such as:
1
2
+
1
3
+
1
16
(
=
43
48
)
{\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})}
Each fraction in the expression has a numerator equal to 1 (unity) and a denominator that... | #Erlang | Erlang | -module(egypt).
-import(lists, [reverse/1, seq/2]).
-export([frac/2, show/2, rosetta/0]).
rosetta() ->
Fractions = [{N, D, second(frac(N, D))} || N <- seq(2,99), D <- seq(N+1, 99)],
{Longest, A1, B1} = findmax(fun length/1, Fractions),
io:format("~b/~b has ~b terms.~n", [A1, B1, Longest]),
{Largest,... |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then outp... | #REXX | REXX | /*REXX program creates a list of (unique) sub─palindromes that exist in an input string.*/
parse arg x . /*obtain optional input string from CL.*/
if x=='' | x=="," then x= 'eertree' /*Not specified? Then use the default.*/
L= length(x) ... |
http://rosettacode.org/wiki/Eertree | Eertree | An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both tries and suffix trees.
See links below.
Task
Construct an eertree for the string "eertree", then outp... | #Ring | Ring |
# Project : Eertree
str = "eertree"
pal = []
for n=1 to len(str)
for m=1 to len(str)
strrev = ""
strpal = substr(str, n, m)
if strpal != ""
for p=len(strpal) to 1 step -1
strrev = strrev + strpal[p]
next
if strpal = strrev
ad... |
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 ... | #Rascal | Rascal | import IO;
public int halve(int n) = n/2;
public int double(int n) = n*2;
public bool uneven(int n) = (n % 2) != 0);
public int ethiopianMul(int n, int m) {
result = 0;
while(n >= 1) {
if(uneven(n))
result += m;
n = halve(n);
m = double(m);
}
return result;
} |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #GFA_Basic | GFA Basic |
'
' Elementary One-Dimensional Cellular Automaton
'
' World is cyclic, and rules are defined by a parameter
'
' start$="01110110101010100100" ! start state for world
' rules%=104 ! number defining rule-set to use
start$="00000000000000000000100000000000000000000"
rules%=18
max_cycles%=20 ! give a maximum depth to wor... |
http://rosettacode.org/wiki/Elementary_cellular_automaton | Elementary cellular automaton | An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three ... | #Go | Go | package main
import (
"fmt"
"math/big"
"math/rand"
"strings"
)
func main() {
const cells = 20
const generations = 9
fmt.Println("Single 1, rule 90:")
a := big.NewInt(1)
a.Lsh(a, cells/2)
elem(90, cells, generations, a)
fmt.Println("Random intial state, rule 30:")
a = ... |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #TransFORTH | TransFORTH | : FACTORIAL
1 SWAP
1 + 1 DO
I * LOOP ; |
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... | #WebAssembly | WebAssembly | (module
;; function isOdd: returns 1 if its argument is odd, 0 if it is even.
(func $isOdd (param $n i32) (result i32)
get_local $n
i32.const 1
i32.and ;; computes (n & 1), i.e. returns low bit of n
)
(export "isOdd" (func $isOdd))
) |
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... | #Wren | Wren | import "/fmt" for Fmt
var isEven1 = Fn.new { |i| i & 1 == 0 }
var isEven2 = Fn.new { |i| i % 2 == 0 }
var tests = [10, 11, 0, 57, 34, -23, -42]
System.print("Tests : %(Fmt.v("s", -4, tests, 0, " ", ""))")
var res1 = tests.map { |t| isEven1.call(t) ? "even" : "odd" }.toList
System.print("Method 1 : %(Fmt.v(... |
http://rosettacode.org/wiki/Echo_server | Echo server | Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local... | #Icon_and_Unicon | Icon and Unicon | global mlck, nCons
procedure main()
mlck := mutex()
nCons := 0
while f := open(":12321","na") do {
handle_client(f)
critical mlck: if nCons <= 0 then close(f)
}
end
procedure handle_client(f)
critical mlck: nCons +:= 1
thread {
select(f,1000) & repeat writes(f,rea... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #TI-83_BASIC | TI-83 BASIC | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #TI-83_Hex_Assembly | TI-83 Hex Assembly | PROGRAM:EMPTY
:AsmPrgmC9 |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #TI-89_BASIC | TI-89 BASIC | Prgm
EndPrgm
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.