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/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... | #Common_Lisp | Common Lisp | (ql:quickload (list :usocket))
(defpackage :echo (:use :cl :usocket))
(in-package :echo)
(defun read-all (stream)
(loop for char = (read-char-no-hang stream nil :eof)
until (or (null char) (eql char :eof)) collect char into msg
finally (return (values msg char))))
(defun echo-server (port &optional (log... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Phix | Phix | with javascript_semantics
string s = ".#.",
t=s, r = "........"
integer rule = 18, k, l = length(s), w = 0
for i=1 to 8 do
r[i] = iff(mod(rule,2)?'#':'.')
rule = floor(rule/2)
end for
for i=0 to 25 do
?repeat(' ',floor((55-length(s))/2))&s
for j=1 to l do
k = (s[iff(j=1?l:j-1)]='#')*4
... |
http://rosettacode.org/wiki/EKG_sequence_convergence | EKG sequence convergence | The sequence is from the natural numbers and is defined by:
a(1) = 1;
a(2) = Start = 2;
for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used.
The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).... | #REXX | REXX | /*REXX program can generate and display several EKG sequences (with various starts).*/
parse arg nums start /*obtain optional arguments from the CL*/
if nums=='' | nums=="," then nums= 50 /*Not specified? Then use the default.*/
if start= '' | start= "," then start=2 5 7 9 1... |
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... | #UNIX_Shell | UNIX Shell | # assign an empty string to a variable
s=""
# the "test" command can determine truth by examining the string itself
if [ "$s" ]; then echo "not empty"; else echo "empty"; fi
# compare the string to the empty string
if [ "$s" = "" ]; then echo "s is the empty string"; fi
if [ "$s" != "" ]; then echo "s is 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... | #Ursa | Ursa | decl string s
set s ""
if (= s "")
out "empty" endl console
else
out "not empty" endl console
end if |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Retro | Retro | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #REXX | REXX | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Rhope | Rhope | Main(0,0)
|: :|
|
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 ... | #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
MODE SCALAR = REAL;
FORMAT scalar fmt = $g(0, 2)$;
MODE MATRIX = [3, 3]SCALAR;
FORMAT vector fmt = $"("n(2 UPB LOC MATRIX - 2 LWB LOC MATRIX)(f(scalar fmt)", ")f(scalar fmt)")"$;
FORMAT matrix fmt = $"("n(1 UPB LOC MATRIX - 1 LWB LOC MATRIX)(f(vector fmt)","l" ")f(vector fmt)")"$;
... |
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... | #11l | 11l | F egyptian_divmod(dividend, divisor)
assert(divisor != 0)
V (pwrs, dbls) = ([1], [divisor])
L dbls.last <= dividend
pwrs.append(pwrs.last * 2)
dbls.append(pwrs.last * divisor)
V (ans, accum) = (0, 0)
L(pwr, dbl) zip(pwrs[((len)-2 ..).step(-1)], dbls[((len)-2 ..).step(-1)])
I accum + dbl... |
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... | #Go | Go | package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoo... |
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 ... | #Plain_English | Plain English | \All required helper routines already exist in Plain English:
\
\To cut a number in half:
\Divide the number by 2.
\
\To double a number:
\Add the number to the number.
\
\To decide if a number is odd:
\Privatize the number.
\Bitwise and the number with 1.
\If the number is 0, say no.
\Say yes.
To run:
Start up.
Put ... |
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 ... | #C | C | #include <stdio.h>
#include <limits.h>
typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))
void evolve(ull state, int rule)
{
int i;
ull st;
printf("Rule %d:\n", rule);
do {
st = state;
for (i = N; i--; ) putchar(st & B(i) ? '#' : '.');
putchar('\n');
for (... |
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... | #Standard_ML | Standard ML | fun factorial n =
if n <= 0 then 1
else n * factorial (n-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... | #SSEM | SSEM | 11110000000000100000000000000000 0. -15 to c
00000000000000110000000000000000 1. Test
11110000000001100000000000000000 2. c to 15
11110000000000100000000000000000 3. -15 to c
00001000000001100000000000000000 4. c to 16
00001000000000100000000000000000 5. -16 to c
01110000000000010000000000000000 6. Sub. 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... | #Standard_ML | Standard ML | fun even n =
n mod 2 = 0;
fun odd n =
n mod 2 <> 0;
(* bitwise and *)
type werd = Word.word;
fun evenbitw(w: werd) =
Word.andb(w, 0w2) = 0w0;
fun oddbitw(w: werd) =
Word.andb(w, 0w2) <> 0w0; |
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... | #D | D | import std.array, std.socket;
void main() {
auto listener = new TcpSocket;
assert(listener.isAlive);
listener.bind(new InternetAddress(12321));
listener.listen(10);
Socket currSock;
uint bytesRead;
ubyte[1] buff;
while (true) {
currSock = listener.accept();
while ((... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Python | Python | def _notcell(c):
return '0' if c == '1' else '1'
def eca_infinite(cells, rule):
lencells = len(cells)
rulebits = '{0:08b}'.format(rule)
neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}
c = cells
while True:
yield c
c = _notcell(c[0])*2 + c + _notcell(... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Racket | Racket | #lang racket
; below is the code from the parent task
(require "Elementary_cellular_automata.rkt")
(require racket/fixnum)
(define (wrap-rule-infinite v-in vl-1 offset)
(define l-bit-set? (bitwise-bit-set? (fxvector-ref v-in 0) usable-bits/fixnum-1))
(define r-bit-set? (bitwise-bit-set? (fxvector-ref v-in vl-1) 0... |
http://rosettacode.org/wiki/EKG_sequence_convergence | EKG sequence convergence | The sequence is from the natural numbers and is defined by:
a(1) = 1;
a(2) = Start = 2;
for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used.
The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).... | #Sidef | Sidef | class Seq(terms, callback) {
method next {
terms += callback(terms)
}
method nth(n) {
while (terms.len < n) {
self.next
}
terms[n-1]
}
method first(n) {
while (terms.len < n) {
self.next
}
terms.first(n)
}
}
fu... |
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... | #VAX_Assembly | VAX Assembly | desc: .ascid "not empty" ;descriptor (len+addr) and text
.entry empty, ^m<>
tstw desc ;check length field
beql is_empty
;... not empty
clrw desc ;set length to zero -> empty
is_empty:
;... empty
ret
.end 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... | #VBA | VBA |
dim s as string
' assign an empty string to a variable (six bytes):
s = ""
' assign null string pointer to a variable (zero bytes, according to RubberduckVBA):
s = vbNullString
' if your VBA code interacts with non-VBA code, this difference may become significant!
' test if a string is empty:
if s = "" then Debug.... |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Ring | Ring | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Robotic | Robotic | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Ruby | Ruby | #!/usr/bin/env ruby |
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 ... | #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
main:
/* create an integer random array */
A=-1,{10}rand array(A), mulby(10), ceil, mov(A)
{","}tok sep
{"\ENF","ORIGINAL ARRAY :",A,"\OFF\n","="}reply(90),
println
{"Increment :\t"}, ++A,{A} println
{"Decrement :\t"}, --A,{A} println
{"post Increment: "}... |
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... | #Action.21 | Action! | TYPE Answer=[CARD result,reminder]
PROC EgyptianDivision(CARD dividend,divisor Answer POINTER res)
DEFINE SIZE="16"
CARD ARRAY powers(SIZE),doublings(SIZE)
CARD power,doubling,accumulator
INT i,count
count=0 power=1 doubling=divisor
WHILE count<SIZE AND doubling<=dividend
DO
powers(count)=power
... |
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... | #Ada | Ada |
with Ada.Text_IO;
procedure Egyptian_Division is
procedure Divide (a : Natural; b : Positive; q, r : out Natural) is
doublings : array (0..31) of Natural; -- The natural type holds values < 2^32 so no need going beyond
m, sum, last_index_touched : Natural := 0;
begin
for i in doublings'Range... |
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... | #Java | Java | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Eertree {
public static void main(String[] args) {
List<Node> tree = eertree("eertree");
List<String> result = subPalindromes(tree);
System.out.println(result);
}
priva... |
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 ... | #Powerbuilder | Powerbuilder | public function boolean wf_iseven (long al_arg);return mod(al_arg, 2 ) = 0
end function
public function long wf_halve (long al_arg);RETURN int(al_arg / 2)
end function
public function long wf_double (long al_arg);RETURN al_arg * 2
end function
public function long wf_ethiopianmultiplication (long al_multiplicand,... |
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 ... | #C.23 | C# |
using System;
using System.Collections;
namespace ElementaryCellularAutomaton
{
class Automata
{
BitArray cells, ncells;
const int MAX_CELLS = 19;
public void run()
{
cells = new BitArray(MAX_CELLS);
ncells = new BitArray(MAX_CELLS);
while ... |
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... | #Stata | Stata | mata
real scalar function fact1(real scalar n) {
if (n<2) return(1)
else return(fact1(n-1)*n)
}
real scalar function fact2(real scalar n) {
a=1
for (i=2;i<=n;i++) a=a*i
return(a)
}
printf("%f\n",fact1(8))
printf("%f\n",fact2(8))
printf("%f\n",factorial(8)) |
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... | #Stata | Stata | mata
function iseven(n) {
return(mod(n,2)==0)
}
function isodd(n) {
return(mod(n,2)==1)
}
end |
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #Swift | Swift | func isEven(n:Int) -> Bool {
// Bitwise check
if (n & 1 != 0) {
return false
}
// Mod check
if (n % 2 != 0) {
return false
}
return true
} |
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... | #Delphi | Delphi | program EchoServer;
{$APPTYPE CONSOLE}
uses SysUtils, IdContext, IdTCPServer;
type
TEchoServer = class
private
FTCPServer: TIdTCPServer;
public
constructor Create;
destructor Destroy; override;
procedure TCPServerExecute(AContext: TIdContext);
end;
constructor TEchoServer.Create;
begin
... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Raku | Raku | class Automaton {
has $.rule;
has @.cells;
has @.code = $!rule.fmt('%08b').flip.comb».Int;
method gist { @!cells.map({+$_ ?? '▲' !! '░'}).join }
method succ {
self.new: :$!rule, :@!code, :cells(
' ',
|@!code[
4 «*« @!cells.rotate(-1)
... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Ruby | Ruby | def notcell(c)
c.tr('01','10')
end
def eca_infinite(cells, rule)
neighbours2next = Hash[8.times.map{|i|["%03b"%i, "01"[rule[i]]]}]
c = cells
Enumerator.new do |y|
loop do
y << c
c = notcell(c[0])*2 + c + notcell(c[-1])*2 # Extend and pad the ends
c = (1..c.size-2).map{|i| neighbou... |
http://rosettacode.org/wiki/EKG_sequence_convergence | EKG sequence convergence | The sequence is from the natural numbers and is defined by:
a(1) = 1;
a(2) = Start = 2;
for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used.
The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).... | #.7B.7Bheader.7CVlang.7D | {{header|Vlang} | fn gcd(aa int, bb int) int {
mut a,mut b:=aa,bb
for a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
fn are_same(ss []int, tt []int) bool {
mut s,mut t:=ss.clone(),tt.clone()
le := s.len
if le != t.len {
return false
}
... |
http://rosettacode.org/wiki/EKG_sequence_convergence | EKG sequence convergence | The sequence is from the natural numbers and is defined by:
a(1) = 1;
a(2) = Start = 2;
for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used.
The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).... | #Wren | Wren | import "/sort" for Sort
import "/math" for Int
import "/fmt" for Fmt
var areSame = Fn.new { |s, t|
var le = s.count
if (le != t.count) return false
Sort.quick(s)
Sort.quick(t)
for (i in 0...le) if (s[i] != t[i]) return false
return true
}
var limit = 100
var starts = [2, 5, 7, 9, 10]
var ekg... |
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... | #VBScript | VBScript | Dim s As String
' Assign empty string:
s = ""
' or
s = String.Empty
' Check for empty string only (false if s is null):
If s IsNot Nothing AndAlso s.Length = 0 Then
End If
' Check for null or empty (more idiomatic in .NET):
If String.IsNullOrEmpty(s) Then
End If |
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... | #Visual_Basic | Visual Basic | Dim s As String
' Assign empty string:
s = ""
' or
s = String.Empty
' Check for empty string only (false if s is null):
If s IsNot Nothing AndAlso s.Length = 0 Then
End If
' Check for null or empty (more idiomatic in .NET):
If String.IsNullOrEmpty(s) Then
End If |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Run_BASIC | Run BASIC | end ' actually a blank is ok |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Rust | Rust | fn main(){} |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Scala | Scala | object emptyProgram extends App {} |
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... | #C.2B.2B | C++ | #include <iostream>
#include <locale>
#include <unordered_map>
#include <primesieve.hpp>
class prime_gaps {
public:
prime_gaps() { last_prime_ = iterator_.next_prime(); }
uint64_t find_gap_start(uint64_t gap);
private:
primesieve::iterator iterator_;
uint64_t last_prime_;
std::unordered_map<uint... |
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 ... | #AutoHotkey | AutoHotkey | ElementWise(M, operation, Val){
A := Obj_Copy(M),
for r, obj in A
for c, v in obj {
V := IsObject(Val) ? Val[r, c] : Val
switch, operation {
case "+": A[r, c] := A[r, c] + V
case "-": A[r, c] := A[r, c] - V
case "*": A[r, c] := A[r... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
# performs Egyptian division of dividend by divisor, setting quotient and remainder #
# this uses 32 bit numbers, so a table of 32 powers of 2 should be sufficient #
# ( divisors > 2^30 will probably overflow - this is not checked here ) #
PROC egyptian division = ( INT dividend,... |
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... | #Julia | Julia | mutable struct Node
edges::Dict{Char, Node}
link::Union{Node, Missing}
sz::Int
Node() = new(Dict(), missing, 0)
end
sizednode(x) = (n = Node(); n.sz = x; n)
function eertree(str)
nodes = Vector{Node}()
oddroot = sizednode(-1)
evenroot = sizednode(0)
oddroot.link = evenroot
evenro... |
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... | #Kotlin | Kotlin | // version 1.1.4
class Node {
val edges = mutableMapOf<Char, Node>() // edges (or forward links)
var link: Node? = null // suffix link (backward links)
var len = 0 // the length of the node
}
class Eertree(str: String) {
val nodes = mutableListOf<Node>()... |
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 ... | #PowerShell | PowerShell | function isEven {
param ([int]$value)
return [bool]($value % 2 -eq 0)
}
function doubleValue {
param ([int]$value)
return [int]($value * 2)
}
function halveValue {
param ([int]$value)
return [int]($value / 2)
}
function multiplyValues {
param (
[int]$plier,
[int]$plicand,
[int]$temp = 0
)
while (... |
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 ... | #C.2B.2B | C++ | #include <bitset>
#include <stdio.h>
#define SIZE 80
#define RULE 30
#define RULE_TEST(x) (RULE & 1 << (7 & (x)))
void evolve(std::bitset<SIZE> &s) {
int i;
std::bitset<SIZE> t(0);
t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );
t[ 0] = RULE_TEST( ... |
http://rosettacode.org/wiki/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... | #Swift | Swift | func factorial(_ n: Int) -> Int {
return n < 2 ? 1 : (2...n).reduce(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... | #Symsyn | Symsyn |
n : 23
if n bit 0
'n is odd' []
else
'n is even' []
|
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... | #Tcl | Tcl | package require Tcl 8.5
# Bitwise test is the most efficient
proc tcl::mathfunc::isOdd x { expr {$x & 1} }
proc tcl::mathfunc::isEven x { expr {!($x & 1)} }
puts " # O E"
puts 24:[expr isOdd(24)],[expr isEven(24)]
puts 49:[expr isOdd(49)],[expr isEven(49)] |
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... | #Erlang | Erlang | -module(echo).
-export([start/0]).
start() ->
spawn(fun () -> {ok, Sock} = gen_tcp:listen(12321, [{packet, line}]),
echo_loop(Sock)
end).
echo_loop(Sock) ->
{ok, Conn} = gen_tcp:accept(Sock),
io:format("Got connection: ~p~n", [Conn]),
Handler = spawn(fun () -> handle(Co... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Sidef | Sidef | func evolve(rule, bin) {
var offset = 0
var (l='', r='')
Inf.times {
bin.sub!(/^((.)\g2*)/, {|_s1, s2| l = s2; offset -= s2.len; s2*2 })
bin.sub!(/(.)\g1*$/, {|s1| r = s1; s1*2 })
printf("%5d| %s%s\n", offset, ' ' * (40 + offset), bin.tr('01','.#'))
bin = [l*3, 0.to(bin.len-3... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Tcl | Tcl | package require Tcl 8.6
oo::class create InfiniteElementaryAutomaton {
variable rules
# Decode the rule number to get a collection of state mapping rules.
# In effect, "compiles" the rule number
constructor {ruleNumber} {
set ins {111 110 101 100 011 010 001 000}
set bits [split [string range [forma... |
http://rosettacode.org/wiki/EKG_sequence_convergence | EKG sequence convergence | The sequence is from the natural numbers and is defined by:
a(1) = 1;
a(2) = Start = 2;
for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used.
The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).... | #XPL0 | XPL0 | int N, A(1+30);
func Used; int M; \Return 'true' if M is in array A
int I;
[for I:= 1 to N-1 do
if M = A(I) then return true;
return false;
];
func MinFactor; int Num; \Return minimum unused factor
int Fac, Val, Min;
[Fac:= 2;
Min:= -1>>1;
repeat if rem(Num/Fac) = 0 then \found a factor
... |
http://rosettacode.org/wiki/EKG_sequence_convergence | EKG sequence convergence | The sequence is from the natural numbers and is defined by:
a(1) = 1;
a(2) = Start = 2;
for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used.
The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).... | #zkl | zkl | fcn ekgW(N){ // --> iterator
Walker.tweak(fcn(rp,buf,w){
foreach n in (w){
if(rp.value.gcd(n)>1)
{ rp.set(n); w.push(buf.xplode()); buf.clear(); return(n); }
buf.append(n); // save small numbers not used yet
}
}.fp(Ref(N),List(),Walker.chain([2..N-1],[N+1..]))).push(1,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... | #Visual_Basic_.NET | Visual Basic .NET | Dim s As String
' Assign empty string:
s = ""
' or
s = String.Empty
' Check for empty string only (false if s is null):
If s IsNot Nothing AndAlso s.Length = 0 Then
End If
' Check for null or empty (more idiomatic in .NET):
If String.IsNullOrEmpty(s) Then
End If |
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... | #Vlang | Vlang | // define and initialize an empty string
mut s := ""
// assign an empty string to a variable
s = ""
// check that a string is empty, any of:
s == ""
s.len() == 0
// check that a string is not empty, any of:
s != ""
s.len() != 0 // or > 0 |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Scheme | Scheme | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Scilab | Scilab | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #ScratchScript | ScratchScript | // |
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... | #F.23 | F# |
// Earliest difference between prime gaps. Nigel Galloway: December 1st., 2021
let fN y=let i=System.Collections.Generic.SortedDictionary<int64,int64>()
let fN()=i|>Seq.pairwise|>Seq.takeWhile(fun(n,g)->g.Key=n.Key+2L)|>Seq.tryFind(fun(n,g)->abs(n.Value-g.Value)>y)
(fun(n,g)->let e=g-n in match i.Tr... |
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... | #Go | Go | package main
import (
"fmt"
"rcu"
)
func main() {
limit := int(1e9)
gapStarts := make(map[int]int)
primes := rcu.Primes(limit * 5)
for i := 1; i < len(primes); i++ {
gap := primes[i] - primes[i-1]
if _, ok := gapStarts[gap]; !ok {
gapStarts[gap] = primes[i-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 ... | #BBC_BASIC | BBC BASIC | DIM a(1,2), b(1,2), c(1,2)
a() = 7, 8, 7, 4, 0, 9 : b() = 4, 5, 1, 6, 2, 1
REM Matrix-Matrix:
c() = a() + b() : PRINT FNshowmm(a(), "+", b(), c())
c() = a() - b() : PRINT FNshowmm(a(), "-", b(), c())
c() = a() * b() : PRINT FNshowmm(a(), "*", b(), c())
c() = a() / b() : PRINT... |
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... | #AppleScript | AppleScript | -- EGYPTIAN DIVISION ------------------------------------
-- eqyptianQuotRem :: Int -> Int -> (Int, Int)
on egyptianQuotRem(m, n)
script expansion
on |λ|(ix)
set {i, x} to ix
if x > m then
Nothing()
else
Just({ix, {i + i, x + x}})
... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN # compute some Egytian fractions #
PR precision 2000 PR # set the number of digits for LONG LONG INT #
PROC gcd = ( LONG LONG INT a, b )LONG LONG INT:
IF b = 0 THEN
IF a < 0 THEN
- a
ELSE
a
FI
ELSE
gcd( b, a MO... |
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... | #M2000_Interpreter | M2000 Interpreter |
If Version<9.5 Then exit
If Version=9.5 And Revision<2 Then Exit
Class Node {
inventory myedges
length, suffix=0
Function edges(s$) {
=-1 : if exist(.myedges, s$) then =eval(.myedges)
}
Module edges_append (a$, where) {
Append .myedges, a$:=where
}
Class:
... |
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... | #Nim | Nim | import algorithm, strformat, strutils, tables
type
Node = ref object
edges: Table[char, Node] # Edges (forward links).
link: Node # Suffix link (backward link).
len: int # Length of the node.
Eertree = object
nodes: seq[Node]
rto: Node # Odd... |
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 ... | #Prolog | Prolog | halve(X,Y) :- Y is X // 2.
double(X,Y) :- Y is 2*X.
is_even(X) :- 0 is X mod 2.
% columns(First,Second,Left,Right) is true if integers First and Second
% expand into the columns Left and Right, respectively
columns(1,Second,[1],[Second]).
columns(First,Second,[First|Left],[Second|Right]) :-
halve(First,Halved),
... |
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 ... | #Ceylon | Ceylon | class Rule(number) satisfies Correspondence<Boolean[3], Boolean> {
shared Byte number;
"all 3 bit patterns will return a value so this is always true"
shared actual Boolean defines(Boolean[3] key) => true;
shared actual Boolean? get(Boolean[3] key) =>
number.get((key[0] then 4 else 0) + (key[1] then 2 els... |
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 ... | #Common_Lisp | Common Lisp | (defun automaton (init rule &optional (stop 10))
(labels ((next-gen (cells)
(mapcar #'new-cell
(cons (car (last cells)) cells)
cells
(append (cdr cells) (list (car cells)))))
(new-cell (left current right)
(let ((sh... |
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... | #Symsyn | Symsyn |
fact
if n < 1
return
endif
* n fn fn
- n
call fact
return
start
if i < 20
1 fn
i n
call fact
fn []
+ i
goif
endif
|
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... | #TI-83_BASIC | TI-83 BASIC |
If fPart(.5Ans
Then
Disp "ODD
Else
Disp "EVEN
End
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
LOOP n=-5,5
x=MOD(n,2)
SELECT x
CASE 0
PRINT n," is even"
DEFAULT
PRINT n," is odd"
ENDSELECT
ENDLOOP |
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... | #Elixir | Elixir | defmodule Echo.Server do
def start(port) do
tcp_options = [:binary, {:packet, 0}, {:active, false}]
{:ok, socket} = :gen_tcp.listen(port, tcp_options)
listen(socket)
end
defp listen(socket) do
{:ok, conn} = :gen_tcp.accept(socket)
spawn(fn -> recv(conn) end)
listen(socket)
end
defp r... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #Wren | Wren | import "/fmt" for Fmt
var addNoCells = Fn.new { |s|
var l = (s[0] == "*") ? "." : "*"
var r = (s[-1] == "*") ? "." : "*"
for (i in 0..1) {
s.insert(0, l)
s.add(r)
}
}
var step = Fn.new { |cells, rule|
var newCells = []
for (i in 0...cells.count - 2) {
var bin = 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... | #Wee_Basic | Wee Basic | let string$=""
if string$=""
print 1 "The string is empty."
elseif string$<>""
print 1 "The string is not empty."
endif
end |
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... | #Wren | Wren | var isEmpty = Fn.new { |s| s == "" }
var s = ""
var t = "0"
System.print("'s' is empty? %(isEmpty.call(s))")
System.print("'t' is empty? %(isEmpty.call(t))") |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is noop; |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Set_lang | Set lang | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #Sidef | Sidef | |
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... | #Java | Java | import java.util.HashMap;
import java.util.Map;
public class PrimeGaps {
private Map<Integer, Integer> gapStarts = new HashMap<>();
private int lastPrime;
private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);
public static void main(String[] args) {
final int limit = 1000... |
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... | #Julia | Julia | using Formatting
using Primes
function primegaps(limit = 10^9)
c(n) = format(n, commas=true)
pri = primes(limit * 5)
gapstarts = Dict{Int, Int}()
for i in 2:length(pri)
get!(gapstarts, pri[i] - pri[i - 1], pri[i - 1])
end
pm, gap1 = 10, 2
while true
while !haskey(gapstarts,... |
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 | C | #include <math.h>
#define for_i for(i = 0; i < h; i++)
#define for_j for(j = 0; j < w; j++)
#define _M double**
#define OPM(name, _op_) \
void eop_##name(_M a, _M b, _M c, int w, int h){int i,j;\
for_i for_j c[i][j] = a[i][j] _op_ b[i][j];}
OPM(add, +);OPM(sub, -);OPM(mul, *);OPM(div, /);
#define OPS(name, res) ... |
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... | #Arturo | Arturo | egyptianDiv: function [dividend, divisor][
ensure -> and? dividend >= 0
divisor > 0
if dividend < divisor -> return @[0, dividend]
powersOfTwo: new [1]
doublings: new @[divisor]
d: divisor
while [true][
d: 2 * d
if d > dividend -> break
'powersOfT... |
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 | C | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
typedef int64_t integer;
struct Pair {
integer md;
int tc;
};
integer mod(integer x, integer y) {
return ((x % y) + y) % y;
}
integer gcd(integer a, integer b) {
if (0 == a) return b;
if (0 == b) return a;
if (a == b) return a;
... |
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... | #Objeck | Objeck | use Collection.Generic;
class Eertree {
function : Main(args : String[]) ~ Nil {
tree := GetEertree("eertree");
Show(SubPalindromes(tree));
}
function : GetEertree(s : String) ~ Vector<Node> {
tree := Vector->New()<Node>;
tree->AddBack(Node->New(0, Nil, 1));
tree->AddBack(Node->New(-1, Nil... |
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 ... | #Python | Python | tutor = True
def halve(x):
return x // 2
def double(x):
return x * 2
def even(x):
return not x % 2
def ethiopian(multiplier, multiplicand):
if tutor:
print("Ethiopian multiplication of %i and %i" %
(multiplier, multiplicand))
result = 0
while multiplier >= 1:
... |
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 ... | #D | D | import std.stdio, std.string, std.conv, std.range, std.algorithm, std.typecons;
enum mod = (in int n, in int m) pure nothrow @safe @nogc => ((n % m) + m) % m;
struct ECAwrap {
public string front;
public enum bool empty = false;
private immutable const(char)[string] next;
this(in string cells_, in... |
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... | #Tailspin | Tailspin |
templates factorial
when <0..> do
@: 1;
1..$ -> @: $@ * $;
$@ !
end factorial
|
http://rosettacode.org/wiki/Even_or_odd | Even or odd | Task
Test whether an integer is even or odd.
There is more than one way to solve this task:
Use the even and odd predicates, if the language provides them.
Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd.
Divide i by 2. The remainder equals... | #UNIX_Shell | UNIX Shell | iseven() {
[[ $(($1%2)) -eq 0 ]] && return 0
return 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... | #Ursa | Ursa | decl int input
set input (in int console)
if (= (mod input 2) 1)
out "odd" endl console
else
out "even" endl console
end if |
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... | #F.23 | F# | open System.IO
open System.Net
open System.Net.Sockets
let service (client:TcpClient) =
use stream = client.GetStream()
use out = new StreamWriter(stream, AutoFlush = true)
use inp = new StreamReader(stream)
while not inp.EndOfStream do
match inp.ReadLine() with
| line -> printfn "< %s... |
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length | Elementary cellular automaton/Infinite length | The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o... | #zkl | zkl | nLines,flipCell := 25, fcn(c){ (c=="1") and "0" or "1" };
foreach rule in (T(90,30)){
println("\nRule: ", rule);
ruleBits:="%08.2B".fmt(rule); // eg 90-->"01011010"
neighs2next:=(8).pump(Dictionary(),
'wrap(n){ T("%03.2B".fmt(n), ruleBits.reverse()[n]) });
C:="1"; // C is "1"s and "0"s, I'll auto ca... |
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... | #X86-64_Assembly | X86-64 Assembly |
option casemap:none
printf proto :qword, :VARARG
exit proto :dword
.data
e_str db 1 dup (0)
.code
main proc
xor rcx, rcx
lea rax, e_str
cmp byte ptr [rax+rcx],0 ;; Is e_str[0] equal to 0?
je _isempty ;; Yes so goto isEmpty
jne _notempty ;;... |
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... | #XLISP | XLISP | [1] (define my-empty-string "") ;; assign an empty string to a variable
MY-EMPTY-STRING
[2] (string-null? my-empty-string)
#T
[3] (string-null? "A non-empty string")
() |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #SimpleCode | SimpleCode |
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.