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 | response_seed stringclasses 1
value | instruction_seed stringlengths 27 14.4k | _source stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method | Pseudo-random numbers/Middle-square method | Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i... | #ALGOL_68 | ALGOL 68 | BEGIN # generate random numbers by the middle-square method #
INT seed := 675248;
# returns the next middle-square random number #
PROC ms random = INT: seed := SHORTEN( ( ( LONG INT( seed ) * LONG INT( seed ) ) OVER 1000 ) MOD 1 000 000 );
# test the ms random procedure #
FOR i TO 5 DO
prin... | Give a code snippet in #ALGOL_68
Middle-square_method Generator
The Method
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer | Keyboard input/Flush the keyboard buffer | Flush the keyboard buffer.
This reads characters from the keyboard input and
discards them until there are no more currently buffered,
and then allows the program to continue.
The program must not wait for users to type anything.
| #Vedit_macro_language | Vedit macro language | Key_Purge() | Give a code snippet in #Vedit_macro_language
Flush the keyboard buffer.
This reads characters from the keyboard input and
discards them until there are no more currently buffered,
and then allows the program to continue.
The program must not wait for users to type anything.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Go | Go | package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synops... | Give a code snippet in #Go
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Groovy | Groovy | class Main {
static void main(String[] args) {
String[] tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k"]
for (String s : tests) {
analyze(s)
}
}
static void analyze(String s) {
println("Examining [$s] which has a length of ${s.length()}")
if... | Give a code snippet in #Groovy
Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer cou... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func integer: countSubstring (in string: stri, in string: searched) is func
result
var integer: count is 0;
local
var integer: offset is 0;
begin
offset := pos(stri, searched);
while offset <> 0 do
incr(count);
offset := pos(stri, searched, offset + le... | Give a code snippet in #Seed7
Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function... | #Metafont | Metafont | def print_arg(text t) =
for x = t:
if unknown x: message "unknown value"
elseif numeric x: message decimal x
elseif string x: message x
elseif path x: message "a path"
elseif pair x: message decimal (xpart(x)) & ", " & decimal (ypart(x))
elseif boolean x: if x: message "true!" else: message "false!" fi
el... | Give a code snippet in #Metafont
Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Erlang | Erlang | -module(lcg).
-export([bsd_seed/1, ms_seed/1, bsd_rand/0, ms_rand/0]).
bsd_seed(Seed) -> put(bsd_state, Seed).
ms_seed(Seed) -> put(ms_state, Seed).
bsd_rand() ->
State = (get(bsd_state) * 1103515245 + 12345) rem 2147483648,
put(bsd_state,State),
State.
ms_rand() ->
State = (get(ms_state) * 214013 + 25... | Give a code snippet in #Erlang
The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Prime_decomposition | Prime decomposition | The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given ... | #360_Assembly | 360 Assembly | PRIMEDE CSECT
USING PRIMEDE,R13
B 80(R15) skip savearea
DC 17F'0' savearea
DC CL8'PRIMEDE'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 end prolog
LA R2,0
... | Give a code snippet in #360_Assembly
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contai... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Huffman_coding | Huffman coding | Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols.
For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi... | #PicoLisp | PicoLisp | (de prio (Idx)
(while (cadr Idx) (setq Idx @))
(car Idx) )
(let (A NIL P NIL L NIL)
(for C (chop "this is an example for huffman encoding")
(accu 'A C 1) ) # Count characters
(for X A # Build index tree as priority queue
(idx 'P (cons (cdr X) (car ... | Give a code snippet in #PicoLisp
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols.
For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then yo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multiplication_tables | Multiplication tables | Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| #Lua | Lua | io.write( " |" )
for i = 1, 12 do
io.write( string.format( "%#5d", i ) )
end
io.write( "\n", string.rep( "-", 12*5+4 ), "\n" )
for i = 1, 12 do
io.write( string.format( "%#2d |", i ) )
for j = 1, 12 do
if j < i then
io.write( " " )
else
io.write( string.form... | Give a code snippet in #Lua
Task
Produce a formatted 12×12 multiplication table of the kind memorized by rote when in primary (or elementary) school.
Only print the top half triangle of products.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort | Sorting algorithms/Patience sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <stack>
#include <iterator>
#include <algorithm>
#include <cassert>
template <class E>
struct pile_less {
bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {
return pile1.top() < pile2.top();
}
};
template <class E>
struct pile_great... | Give a code snippet in #C.2B.2B
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #PureBasic | PureBasic | Procedure.s sortLetters(*word.Character, wordLength) ;returns a string with the letters of a word sorted
Protected Dim letters.c(wordLength)
Protected *letAdr = @letters()
CopyMemoryString(*word, @*letAdr)
SortArray(letters(), #PB_Sort_Ascending, 0, wordLength - 1)
ProcedureReturn PeekS(@letters(), wordLeng... | Give a code snippet in #PureBasic
An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file lo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selecte... | #Go | Go | package main
import "fmt"
func menu(choices []string, prompt string) string {
if len(choices) == 0 {
return ""
}
var c int
for {
fmt.Println("")
for i, s := range choices {
fmt.Printf("%d. %s\n", i+1, s)
}
fmt.Print(prompt)
_, err := fmt.S... | Give a code snippet in #Go
Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Select[Table[M = 2^p - 1;
For[i = 1; s = 4, i <= p - 2, i++, s = Mod[s^2 - 2, M]];
If[s == 0, "M" <> ToString@p, p], {p,
Prime /@ Range[300]}], StringQ]
=> {M3, M5, M7, M13, M17, M19, M31, M61, M89, M107, M127, M521, M607, M1279} | Give a code snippet in #Mathematica.2FWolfram_Language
Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Parallel_calculations | Parallel calculations | Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want to find the one
with the largest ... | #Kotlin | Kotlin | // version 1.1.51
import java.util.stream.Collectors
/* returns the number itself, its smallest prime factor and all its prime factors */
fun primeFactorInfo(n: Int): Triple<Int, Int, List<Int>> {
if (n <= 1) throw IllegalArgumentException("Number must be more than one")
if (isPrime(n)) return Triple(n, n, ... | Give a code snippet in #Kotlin
Many programming languages allow you to specify computations to be run in parallel.
While Concurrent computing is focused on concurrency,
the purpose of this task is to distribute time-consuming calculations
on as many CPUs as possible.
Assume we have a collection of numbers, and want t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #TXR | TXR | (defstruct shape ()
cached-area
(:init (self)
(put-line `@self is born!`))
(:fini (self)
(put-line `@self says goodbye!`))
(:method area (self)
(or self.cached-area
(set self.cached-area self.(calc-area)))))
(defstruct circle shape
(radius 1.0)
(:method calc-area (self)
(* ... | Give a code snippet in #TXR
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #PARI.2FGP | PARI/GP | isNumeric(s)={
my(t=type(eval(s)));
t == "t_INT" || t == "T_REAL"
}; | Give a code snippet in #PARI.2FGP
Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metric... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #Go | Go | package main
import (
"fmt"
"log"
"strconv"
)
// A casting out nines algorithm.
// Quoting from: http://mathforum.org/library/drmath/view/55926.html
/*
First, for any number we can get a single digit, which I will call the
"check digit," by repeatedly adding the digits. That is, we add the
digits of... | Give a code snippet in #Go
Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compiler/AST_interpreter | Compiler/AST interpreter | An AST interpreter interprets an Abstract Syntax Tree (AST)
produced by a Syntax Analyzer.
Task[edit]
Take the AST output from the Syntax analyzer task, and interpret it as appropriate.
Refer to the Syntax analyzer task for details of the AST.
Loading the AST from the syntax analyzer is as simple as (pseudo code)
de... | #COBOL | COBOL | >>SOURCE FORMAT IS FREE
identification division.
*> this code is dedicated to the public domain
*> (GnuCOBOL) 2.3-dev.0
program-id. astinterpreter.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01 program-name pic x(32) value spaces glo... | Give a code snippet in #COBOL
An AST interpreter interprets an Abstract Syntax Tree (AST)
produced by a Syntax Analyzer.
Task[edit]
Take the AST output from the Syntax analyzer task, and interpret it as appropriate.
Refer to the Syntax analyzer task for details of the AST.
Loading the AST from the syntax analyzer is... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters... | #Tcl | Tcl | set data [lrange [split [read [open "readings.txt" "r"]] "\n"] 0 end-1]
set total [llength $data]
set correct $total
set datestamps {}
foreach line $data {
set formatOk true
set hasAllMeasurements true
set date [lindex $line 0]
if {[llength $line] != 49} { set formatOk false }
if {![regexp {\d{4... | Give a code snippet in #Tcl
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Singleton | Singleton | A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| #C.2B.2B | C++ |
#include <stdexcept>
template <typename Self>
class singleton
{
protected:
static Self*
sentry;
public:
static Self&
instance()
{
return *sentry;
}
singleton()
{
if(sentry)
throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!");
sentry = (Self*)this;
}
vi... | Give a code snippet in #C.2B.2B
A Global Singleton is a class of which only one instance exists within a program.
Any attempt to use non-static members of the class involves performing operations on this one instance.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Visual_Basic | Visual Basic | Function GCD(ByVal a As Long, ByVal b As Long) As Long
Dim h As Long
If a Then
If b Then
Do
h = a Mod b
a = b
b = h
Loop While b
End If
GCD = Abs(a)
Else
GCD = Abs(b)
End If
End Function
Sub Main()
... | Give a code snippet in #Visual_Basic
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and g... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) ... | #Perl | Perl | # 20220120 Perl programming solution
use strict;
use warnings;
use lib '/home/hkdtam/lib';
use Image::EdgeDetect;
my $detector = Image::EdgeDetect->new();
$detector->process('./input.jpg', './output.jpg') or die; # na.cx/i/pHYdUrV.jpg | Give a code snippet in #Perl
Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #zkl | zkl | fcn convert(price){ // float --> float
// < -->, increments of 0.05 but tables are easier to update
var vert=T( T(0.06, 0.10), T(0.11, 0.18), T(0.16, 0.26),
T(0.21, 0.32), T(0.26, 0.38), T(0.31, 0.44),
T(0.36, 0.50), T(0.41, 0.54), T(0.46, 0.58),
T(0.51, 0.62), T(0.56, 0.66)... | Give a code snippet in #zkl
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/The_ISAAC_Cipher | The ISAAC Cipher | ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming... | #REXX | REXX | /* REXX ---------------------------------------------------------------
* 24.07.2014 Walter Pachl translated from Pascal
* extend with decryption (following Pascal)
* 25.07.2014 WP changed i+=8 to I=I+8 (courtesy GS)
* 26.07-2014 WP removed extraneous semicolons
*---------------------------------------------... | Give a code snippet in #REXX
ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architect... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Raku | Raku | sub counting-sort (@ints) {
my $off = @ints.min;
(my @counts)[$_ - $off]++ for @ints;
flat @counts.kv.map: { ($^k + $off) xx ($^v // 0) }
}
# Testing:
constant @age-range = 2 .. 102;
my @ages = @age-range.roll(50);
say @ages.&counting-sort;
say @ages.sort;
say @ages.&counting-sort.join eq @ages.sort.joi... | Give a code snippet in #Raku
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sor... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #LiveCode | LiveCode | function LuhnTest cc
local s1,evens, s2
repeat with n = 1 to len(cc)
if n mod 2 is not 0 then
add (char -n of cc) to s1
else
put (char -n of cc) * 2 into evens
if evens > 9 then subtract 9 from evens
add evens to s2
end if
end repeat
... | Give a code snippet in #LiveCode
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously | Loop over multiple arrays simultaneously | Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
... | #Frink | Frink | a1 = ["a", "b", "c"]
a2 = ["A", "B", "C"]
a3 = ["1", "2", "3"]
m = [a1, a2, a3]
for row = m.transpose[]
println[join["",row]] | Give a code snippet in #Frink
Task
Loop over multiple arrays (or lists or tuples or whatever they're called in
your language) and display the i th element of each.
Use your language's "for each" loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this exam... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #PL.2FI | PL/I | shuffle: procedure options (main); /* 14/1/2011 */
declare (s, saves) character (20) varying, c character (1);
declare t(length(s)) bit (1);
declare (i, k, moves initial (0)) fixed binary;
get edit (s) (L);
put skip list (s);
saves = s;
t = '0'b;
do i = 1 to length (s);
... | Give a code snippet in #PL.2FI
Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Delphi | Delphi |
// Generate cuban primes. Nigel Galloway: June 9th., 2019
let cubans=Seq.unfold(fun n->Some(n*n*n,n+1L)) 1L|>Seq.pairwise|>Seq.map(fun(n,g)->g-n)|>Seq.filter(isPrime64)
let cL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:int64)->n.ToString("N0",g))
| Give a code snippet in #Delphi
The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #E | E | def compareBy(keyfn) { # This ought to be in the standard library
return def comparer(a, b) {
return keyfn(a).op__cmp(keyfn(b))
}
}
def x := [
["Joe",3],
["Bill",4],
["Alice",20],
["Harry",3],
]
println(x.sort(compareBy(fn [name,_] { name }))) | Give a code snippet in #E
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #ALGOL_68 | ALGOL 68 | PROC step up = VOID:
BEGIN
WHILE NOT step DO
step up
OD
END # step up #; | Give a code snippet in #ALGOL_68
From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #PureBasic.2BSQLite | PureBasic+SQLite |
UseSQLiteDatabase()
Procedure CheckDatabaseUpdate(Database, Query$)
Result = DatabaseUpdate(Database, Query$)
If Result = 0
Print(DatabaseError())
EndIf
ProcedureReturn Result
EndProcedure
openconsole()
DatabaseFile$ = GetCurrentDirectory()+"/rosettadb.sdb"
If CreateFile(0, DatabaseFile$)
CloseFi... | Give a code snippet in #PureBasic.2BSQLite
Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort | Sorting algorithms/Gnome sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #DWScript | DWScript | procedure GnomeSort(a : array of Integer);
var
i, j : Integer;
begin
i := 1;
j := 2;
while i < a.Length do begin
if a[i-1] <= a[i] then begin
i := j;
j := j + 1;
end else begin
a.Swap(i-1, i);
i := i - 1;
if i = 0 then begin
i := j;
... | Give a code snippet in #DWScript
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Left_factorials | Left factorials | Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n
n¡
(It may not be vis... | #Sidef | Sidef | say 20.of { .left_factorial } | Give a code snippet in #Sidef
Left factorials, !n, may refer to either subfactorials or to factorial sums;
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, subfactorials (also known as derangements) may use any of the notations:
!n`
!n ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Kotlin | Kotlin | // version 1.2.0
import java.io.*
open class Entity(val name: String = "Entity"): Serializable {
override fun toString() = name
companion object {
val serialVersionUID = 3504465751164822571L
}
}
class Person(name: String = "Brian"): Entity(name), Serializable {
companion object {
... | Give a code snippet in #Kotlin
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #UTFool | UTFool |
···
http://rosettacode.org/wiki/Chinese_zodiac
···
■ ChineseZodiac
§ static
tiangan⦂ String[][]: ¤ · 10 celestial stems
¤ "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"
¤ "jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi"
dizhi⦂ String[][]: ¤ · 12 terrestrial branches
¤ ... | Give a code snippet in #UTFool
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities resul... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Leap_year | Leap year | Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| #Pascal | Pascal | program LeapYear;
uses
sysutils;//includes isLeapYear
procedure TestYear(y: word);
begin
if IsLeapYear(y) then
writeln(y,' is a leap year')
else
writeln(y,' is NO leap year');
end;
Begin
TestYear(1900);
TestYear(2000);
TestYear(2100);
TestYear(1904);
end. | Give a code snippet in #Pascal
Task
Determine whether a given year is a leap year in the Gregorian calendar.
See also
Leap year (wiki)
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #PowerShell | PowerShell | [int64]$i = 0
While ( $True )
{
[Convert]::ToString( ++$i, 8 )
} | Give a code snippet in #PowerShell
Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reach... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Elena | Elena | class MyException : Exception
{
constructor new()
<= new("MyException raised");
} | Give a code snippet in #Elena
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The ba... | #Nim | Nim | type Stack[T] = distinct seq[T]
func initStack[T](initialSize = 32): Stack[T] =
Stack[T](newSeq[T](initialSize))
func isEmpty[T](stack: Stack[T]): bool =
seq[T](stack).len == 0
func push[T](stack: var Stack[T]; item: sink T) =
seq[T](stack).add(item)
func pop[T](stack: var Stack[T]): T =
if stack.isEmpt... | Give a code snippet in #Nim
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is acce... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #LiveCode | LiveCode | command assocArray
local tArray
put "value 1" into tArray["key 1"]
put 123 into tArray["key numbers"]
put "a,b,c" into tArray["abc"]
put "number of elements:" && the number of elements of tArray & return & \
"length of item 3:" && the length of tArray["abc"] & return & \
"keys:... | Give a code snippet in #LiveCode
Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character | Terminal control/Display an extended character | Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| #beeswax | beeswax | _4~9P.P.M} | Give a code snippet in #beeswax
Task
Display an extended (non ASCII) character onto the terminal.
Specifically, display a £ (GBP currency sign).
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment | Runtime evaluation/In an environment | x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general examples and language-specific details, see... | #Common_Lisp | Common Lisp | (defun eval-with-x (program a b)
(let ((at-a (eval `(let ((x ',a)) ,program)))
(at-b (eval `(let ((x ',b)) ,program))))
(- at-b at-a))) | Give a code snippet in #Common_Lisp
x
x
x
Do so in a way which:
does not involve string manipulation of the input source code
is plausibly extensible to a runtime-chosen set of bindings rather than just x
does not make x a global variable
or note that these are impossible.
See also
For more general exampl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Matrix_multiplication | Matrix multiplication | Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| #Sidef | Sidef | func matrix_multi(a, b) {
var m = [[]]
for r in ^a {
for c in ^b[0] {
for i in ^b {
m[r][c] := 0 += (a[r][i] * b[i][c])
}
}
}
return m
}
var a = [
[1, 2],
[3, 4],
[5, 6],
[7, 8]
]
var b = [
... | Give a code snippet in #Sidef
Task
Multiply two matrices together.
They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
R... | #Perl | Perl | sub cubLine ($$$$) {
my ($n, $dx, $dy, $cde) = @_;
printf '%*s', $n + 1, substr($cde, 0, 1);
for (my $d = 9 * $dx - 1 ; $d > 0 ; --$d) {
print substr($cde, 1, 1);
}
print substr($cde, 0, 1);
printf "%*s\n", $dy + 1, substr($cde, 2, 1);
}
sub cuboid ($$$) {
my ($dx, $dy, $dz) ... | Give a code snippet in #Perl
Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the... | #11l | 11l | [Float] a
[String = ((Float, Float) -> Float)] b
b[‘+’] = (x, y) -> y + x
b[‘-’] = (x, y) -> y - x
b[‘*’] = (x, y) -> y * x
b[‘/’] = (x, y) -> y / x
b[‘^’] = (x, y) -> y ^ x
L(c) ‘3 4 2 * 1 5 - 2 3 ^ ^ / +’.split(‘ ’)
I c C b
V first = a.pop()
V second = a.pop()
a.append(b[c](first, second))
... | Give a code snippet in #11l
Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Menu | Menu | Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the string corresponding to the selecte... | #Perl | Perl | sub menu
{
my ($prompt,@array) = @_;
return '' unless @array;
print " $_: $array[$_]\n" for(0..$#array);
print $prompt;
$n = <>;
return $array[$n] if $n =~ /^\d+$/ and defined $array[$n];
return &menu($prompt,@array);
}
@a = ('fee fie', 'huff and puff', 'mirr... | Give a code snippet in #Perl
Task
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
prompts the user to enter a number;
returns the strin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Comma_quibbling | Comma quibbling | Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An input of just one word, e.g. ["AB... | #Ada | Ada | with Ada.Text_IO, Ada.Command_Line; use Ada.Command_Line;
procedure Comma_Quibble is
begin
case Argument_Count is
when 0 => Ada.Text_IO.Put_Line("{}");
when 1 => Ada.Text_IO.Put_Line("{" & Argument(1) & "}");
when others =>
Ada.Text_IO.Put("{");
for I in 1 .. Argument_Count-2 loop
Ada... | Give a code snippet in #Ada
Comma quibbling is a task originally set by Eric Lippert in his blog.
Task
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
An input of no words produces the output string of just the two brace characters "{}".
An inpu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one dow... | #Haxe | Haxe | class RosettaDemo
{
static public function main()
{
singBottlesOfBeer(100);
}
static function singBottlesOfBeer(bottles : Int)
{
var plural : String = 's';
while (bottles >= 1)
{
Sys.println(bottles + " bottle" + plural + " of beer on the wall,");
... | Give a code snippet in #Haxe
Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Quine | Quine | A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
self-reproducing program ... | #Gambas | Gambas | dim s as string="dim s as string=&1&2&3&4print subst(s,chr(34),s,chr(34),chr(10))"
print subst(s,chr(34),s,chr(34),chr(10))
| Give a code snippet in #Gambas
A quine is a self-referential program that can,
without any external access, output its own source.
A quine (named after Willard Van Orman Quine) is also known as:
self-reproducing automata (1972)
self-replicating program or self-replicating computer program
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #FreeBASIC | FreeBASIC | ' version 18-03-2017
' compile with: fbc -s console
Function crc32(buf As String) As UInteger<32>
Static As UInteger<32> table(256)
Static As UInteger<32> have_table
Dim As UInteger<32> crc, k
Dim As ULong i, j
If have_table = 0 Then
For i = 0 To 255
k = i
For j... | Give a code snippet in #FreeBASIC
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Arithmetic_mean | Averages/Arithmetic mean | Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const array float: numVector is [] (1.0, 2.0, 3.0, 4.0, 5.0);
const func float: mean (in array float: numbers) is func
result
var float: result is 0.0;
local
var float: total is 0.0;
var float: num is 0.0;
begin
if length(numbers) <> 0 then
... | Give a code snippet in #Seed7
Task[edit]
Write a program to find the mean (arithmetic average) of a numeric vector.
In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an esta... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #ALGOL_W | ALGOL W | begin % compare some numeric integration methods %
long real procedure leftRect ( long real procedure f
; long real value a, b
; integer value n
) ;
begin
long real ... | Give a code snippet in #ALGOL_W
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Topswops | Topswops | Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is composed of reversing the first ... | #Phix | Phix | with javascript_semantics
function fannkuch(integer n)
sequence count = tagset(n),
perm1 = tagset(n)
integer maxFlipsCount = 0, r = n+1
while true do
while r!=1 do
count[r-1] = r
r -= 1
end while
if not (perm1[1]=1 or perm1[n]=n) then
... | Give a code snippet in #Phix
Topswops is a card game created by John Conway in the 1970's.
Assume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top.
A round is com... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Achilles_numbers | Achilles numbers |
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
An Achilles number is a number that is powerful but imperfect. Na... | #Perl | Perl | use strict;
use warnings;
use feature <say current_sub>;
use experimental 'signatures';
use List::AllUtils <max head uniqint>;
use ntheory <is_square_free is_power euler_phi>;
use Math::AnyNum <:overload idiv iroot ipow is_coprime>;
sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_... | Give a code snippet in #Perl
This page uses content from Wikipedia. The original article was at Achilles number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
An Achilles number is a number that... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Emirp_primes | Emirp primes | An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th emirp
In each list, the numbe... | #Scala | Scala | def isEmirp( v:Long ) : Boolean = {
val b = BigInt(v.toLong)
val r = BigInt(v.toString.reverse.toLong)
b != r && b.isProbablePrime(16) && r.isProbablePrime(16)
}
// Generate the output
{
val (a,b1,b2,c) = (20,7700,8000,10000)
println( "%32s".format( "First %d emirps: ".format( a )) + Stream.from(2).fi... | Give a code snippet in #Scala
An emirp (prime spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
(This rules out palindromic primes.)
Task
show the first twenty emirps
show all emirps between 7,700 and 8,000
show the 10,000th ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mind_boggling_card_trick | Mind boggling card trick | Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics th... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | s = RandomSample@Flatten[{Table[0, 26], Table[1, 26]}]
g = Take[s, {1, -1, 2}]
d = Take[s, {2, -1, 2}]
a = b = {};
Table[If[g[[i]] == 1, AppendTo[a, d[[i]]], AppendTo[b, d[[i]]]], {i,
Length@g}];
a
b
dice = RandomInteger[{1, 6}]
ra = Sort@RandomSample[Range@Length@a, dice]
a = {Delete[a, List /@ ra], a[[ra]]}
rb = ... | Give a code snippet in #Mathematica.2FWolfram_Language
Mind boggling card trick
You are encouraged to solve this task according to the task description, using any language you may know.
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
T... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Logo | Logo | print apply "sum map [? * ?] [1 2 3 4 5] ; 55 | Give a code snippet in #Logo
Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters... | #Clojure | Clojure |
(defn parse-line [s]
(let [[date & data-toks] (str/split s #"\s+")
data-fields (map read-string data-toks)
valid-date? (fn [s] (re-find #"\d{4}-\d{2}-\d{2}" s))
valid-line? (and (valid-date? date)
(= 48 (count data-toks))
(every? number? data... | Give a code snippet in #Clojure
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be on... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were s... | #BBC_BASIC | BBC BASIC | REM >tokenizer
PROC_tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")
END
:
DEF PROC_tokenize(src$, sep$, esc$)
LOCAL field%, char$, escaping%, i%
field% = 1
escaping% = FALSE
PRINT field%; " ";
FOR i% = 1 TO LEN src$
char$ = MID$(src$, i%, 1)
IF escaping% THEN
PRINT char$;
escaping% = FALSE
ELSE... | Give a code snippet in #BBC_BASIC
Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #Groovy | Groovy | println ((-22).abs()) | Give a code snippet in #Groovy
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #VBA | VBA | Public Sub main()
s = [{1,2,3,3,3,4,4,4,5,5,6}]
t = WorksheetFunction.Mode_Mult(s)
For Each x In t
Debug.Print x;
Next x
End Sub | Give a code snippet in #VBA
Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if poss... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Inform_7 | Inform 7 | Sum And Product is a room.
To decide which number is the sum of (N - number) and (M - number) (this is summing):
decide on N + M.
To decide which number is the product of (N - number) and (M - number) (this is production):
decide on N * M.
When play begins:
let L be {1, 2, 3, 4, 5};
say "List: [L in brace not... | Give a code snippet in #Inform_7
Task
Compute the sum and product of an array of integers.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #ACL2 | ACL2 | (defun sum-of-squares (xs)
(if (endp xs)
0
(+ (* (first xs) (first xs))
(sum-of-squares (rest xs))))) | Give a code snippet in #ACL2
Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| christopher/rosetta-code | |
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer | 9 billion names of God the integer | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has 3 names “1+1+1”, “2+1”, ... | #Java | Java | import java.math.BigInteger;
import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
import static java.lang.Math.min;
public class Test {
static List<BigInteger> cumu(int n) {
List<List<BigInteger>> cac... | Give a code snippet in #Java
This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a “name”:
The integer 1 has 1 name “1”.
The integer 2 has 2 names “1+1”, and “2”.
The integer 3 has ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #C.2B.2B | C++ | // standard C++ string stream operators
#include <cstdlib>
#include <string>
#include <sstream>
// inside a function or method...
std::string s = "12345";
int i;
std::istringstream(s) >> i;
i++;
//or:
//int i = std::atoi(s.c_str()) + 1;
std::ostringstream oss;
if (oss << i) s = oss.str(); | Give a code snippet in #C.2B.2B
Task
Increment a numerical string.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Go | Go | package main
import "fmt"
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
func main() {
fmt.Println("before:", a)
stoogesort(a)
fmt.Println("after: ", a)
fmt.Println("nyuk nyuk nyuk")
}
func stoogesort(a []int) {
last := len(a) - 1
if a[last] < a[0] {
a[0], a[last] = a[last], a[... | Give a code snippet in #Go
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #ALGOL_68 | ALGOL 68 | BEGIN
# a number wheel element #
MODE NWELEMENT = UNION( CHAR # wheel name #, INT # wheel value # );
# a number wheel #
MODE NW = STRUCT( CHAR name, REF INT position, FLEX[ 1 : 0 ]NWELEMENT values )... | Give a code snippet in #ALGOL_68
A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Soundex | Soundex | Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
There is a major issue in many of the ... | #FutureBasic | FutureBasic | include "NSLog.incl"
local fn SoundexCode( charCode as unsigned char ) as unsigned char
select charCode
case _"B", _"F", _"P", _"V"
charCode = _"1"
case _"C", _"G", _"J", _"K", _"Q", _"S", _"X", _"Z"
charCode = _"2"
case _"D", _"T"
charCode = _"3"
case _"L"
charCode = _"4"
... | Give a code snippet in #FutureBasic
Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
T... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Non-transitive_dice | Non-transitive dice | Let our dice select numbers on their faces with equal probability, i.e. fair dice.
Dice may have more or less than six faces. (The possibility of there being a
3D physical shape that has that many "faces" that allow them to be fair dice,
is ignored for this task - a die with 3 or 33 defined sides is defined by the
numb... | #Wren | Wren | import "/sort" for Sort
var fourFaceCombs = Fn.new {
var res = []
var found = List.filled(256, false)
for (i in 1..4) {
for (j in 1..4) {
for (k in 1..4) {
for (l in 1..4) {
var c = [i, j, k, l]
Sort.insertion(c)
... | Give a code snippet in #Wren
Let our dice select numbers on their faces with equal probability, i.e. fair dice.
Dice may have more or less than six faces. (The possibility of there being a
3D physical shape that has that many "faces" that allow them to be fair dice,
is ignored for this task - a die with 3 or 33 define... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Wren | Wren | var rot13 = Fn.new { |s|
var bytes = s.bytes.toList
for (i in 0...bytes.count) {
var c = bytes[i]
if ((c >= 65 && c <= 77) || (c >= 97 && c <= 109)) {
bytes[i] = c + 13
} else if ((c >= 78 && c <= 90) || (c >= 110 && c <= 122)) {
bytes[i] = c - 13
}
}
... | Give a code snippet in #Wren
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least t... | #BaCon | BaCon | ' Nth (sans apostrophes)
FUNCTION nth$(NUMBER n) TYPE STRING
LOCAL suffix
IF n < 0 THEN RETURN STR$(n)
IF MOD(n, 100) >= 11 AND MOD(n, 100) <= 13 THEN
suffix = "th"
ELSE
suffix = MID$("thstndrdthththththth", MOD(n, 10) * 2 + 1, 2)
ENDIF
RETURN CONCAT$(STR$(n), suffix)
END FUNCTIO... | Give a code snippet in #BaCon
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #ReScript | ReScript | Js.log("Hello world!") | Give a code snippet in #ReScript
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard erro... | christopher/rosetta-code | |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #XBasic | XBasic | PROGRAM "100doors"
VERSION "0.0001"
IMPORT "xma"
IMPORT "xst"
DECLARE FUNCTION Entry()
FUNCTION Entry()
maxpuertas = 100
cont = 0
DIM puertas[100]
FOR p = 1 TO maxpuertas
IF INT(SQRT(p)) = SQRT(p) THEN puertas[p] = 1
NEXT p
PRINT "The doors are open: ";
FOR p = 1 TO maxpuertas
IF puertas... | Give a code snippet in #XBasic
There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, .... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pen... | #Lasso | Lasso | define cointcoins(
target::integer,
operands::array
) => {
local(
targetlength = #target + 1,
operandlength = #operands -> size,
output = staticarray_join(#targetlength,0),
outerloopcount
)
#output -> get(1) = 1
loop(#operandlength) => {
#outerloopcount = loop_count
loop(#targetlength) => {
... | Give a code snippet in #Lasso
There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5... | christopher/rosetta-code | |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Groovy | Groovy | doors = [false] * 100
(0..99).each {
it.step(100, it + 1) {
doors[it] ^= true
}
}
(0..99).each {
println("Door #${it + 1} is ${doors[it] ? 'open' : 'closed'}.")
} | Give a code snippet in #Groovy
There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, .... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Juggler_sequence | Juggler sequence | Background of the juggler sequence:
Juggler sequences were publicized by an American mathematician and author Clifford A. Pickover. The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences, much like balls in the hands of a juggler.
Descrip... | #Wren | Wren | import "/fmt" for Fmt
import "/big" for BigInt
var one = BigInt.one
var juggler = Fn.new { |n|
if (n < 1) Fiber.abort("Starting value must be a positive integer.")
var a = BigInt.new(n)
var count = 0
var maxCount = 0
var max = a.copy()
while (a != one) {
if (a.isEven) {
... | Give a code snippet in #Wren
Background of the juggler sequence:
Juggler sequences were publicized by an American mathematician and author Clifford A. Pickover. The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences, much like balls in the ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Named_parameters | Named parameters | Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being able to use the names give... | #J | J | NB. Strand notation
myFunc['c:\file.txt' 906 'blue' fs]
NB. Commas, like other langs
myFunc['c:\file.txt', 906, 'blue' fs]
NB. Unspecified args are defaulted ("optional")
myFunc['c:\file.txt' fs]
NB. Can use named arguments, like eg VB
myFunc[color='blue' fs]
NB. Often values needn't be quoted
myFunc[co... | Give a code snippet in #J
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.
Note:
Named parameters relies on being... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #Raku | Raku | use v6;
sub power-path ($n ) {
state @unused_nodes = (2,);
state @power-tree = (False,0,1);
until @power-tree[$n].defined {
my $node = @unused_nodes.shift;
for $node X+ power-path($node).pick(*) {
next if @power-tree[$_].defined;
@unused_nodes.push($_);
... | Give a code snippet in #Raku
(Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact value... | christopher/rosetta-code | |
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... | #M4 | M4 | define(`even', `ifelse(eval(`$1'%2),0,True,False)')
define(`odd', `ifelse(eval(`$1'%2),0,False,True)')
even(13)
even(8)
odd(5)
odd(0) | Give a code snippet in #M4
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #ALGOL_68 | ALGOL 68 | BEGIN
BOOL at eof := FALSE;
# set the EOF handler for stand in to a procedure that sets "at eof" to true #
# and returns true so processing can continue #
on logical file end( stand in, ( REF FILE f )BOOL: at eof := TRUE );
# copy stand i... | Give a code snippet in #ALGOL_68
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Yin_and_yang | Yin and yang | One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| #Julia | Julia | function yinyang(n::Int=3)
radii = (i * n for i in (1, 3, 6))
ranges = collect(collect(-r:r) for r in radii)
squares = collect(collect((x, y) for x in rnge, y in rnge) for rnge in ranges)
circles = collect(collect((x, y) for (x,y) in sqrpoints if hypot(x, y) ≤ radius)
for (sqrpo... | Give a code snippet in #Julia
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.
Task
Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.
Generate and display the symbol for two different (small) sizes.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Boolean_values | Boolean values | Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| #Elm | Elm |
--True and False directly represent Boolean values in Elm
--For eg to show yes for true and no for false
if True then "yes" else "no"
--Same expression differently
if False then "no" else "yes"
--This you can run as a program
--Elm allows you to take anything you want for representation
--In the program we take T... | Give a code snippet in #Elm
Task
Show how to represent the boolean states "true" and "false" in a language.
If other objects represent "true" or "false" in conditionals, note it.
Related tasks
Logical operations
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, base... | #Python | Python | #!/usr/bin/python3
'''\
Simple database for: http://rosettacode.org/wiki/Simple_database
'''
import argparse
from argparse import Namespace
import datetime
import shlex
def parse_args():
'Set up, parse, and return arguments'
parser = argparse.ArgumentParser(epilog=globals()['__doc__'])
parser.... | Give a code snippet in #Python
Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could b... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Align_columns | Align columns | Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, o... | #Racket | Racket |
#lang racket
(define (display-aligned text #:justify [justify 'left])
(define lines
(for/list ([line (regexp-split #rx"\n" text)])
(regexp-split #rx"\\$" line)))
(define width
(add1 (for*/fold ([m 0]) ([line lines] [word line])
(max m (string-length word)))))
(define spaces (make-str... | Give a code snippet in #Racket
Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either le... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Window_creation | Window creation | Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"WINLIB2"
dlg% = FN_newdialog("GUI Window", 0, 0, 200, 150, 8, 1000)
PROC_showdialog(dlg%) | Give a code snippet in #BBC_BASIC
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Pentagram | Pentagram |
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and backg... | #Scala | Scala | import java.awt._
import java.awt.geom.Path2D
import javax.swing._
object Pentagram extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Pentagram") {
class Pentagram extends JPanel {
setPreferredSize(new Dimension(640, 640))
setBackground(Color.white)
final private val... | Give a code snippet in #Scala
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.
Task
Draw (or print) a regular pentagram, in any orientation. Use a different color (or token)... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at uni... | #Lua | Lua | string.tacnoc = function(str) -- 'inverse' of table.concat
local arr={}
for ch in str:gmatch(".") do arr[#arr+1]=ch end
return arr
end
local function deranged(s1, s2)
if s1==s2 then return false end
local t1, t2 = s1:tacnoc(), s2:tacnoc()
for i,v in ipairs(t1) do if t2[i]==v then return false end end
re... | Give a code snippet in #Lua
Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[e... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strong_and_weak_primes | Strong and weak primes |
Definitions (as per number theory)
The prime(p) is the pth prime.
prime(1) is 2
prime(4) is 7
A strong prime is when prime(p) is > [prime(p-1) + prime(p+1)] ÷ 2
A weak prime is when prime(p) is < [prime(p-1) + prime(p+1)] ÷ 2
Note that the defin... | #Raku | Raku | sub comma { $^i.flip.comb(3).join(',').flip }
use Math::Primesieve;
my $sieve = Math::Primesieve.new;
my @primes = $sieve.primes(10_000_019);
my (@weak, @balanced, @strong);
for 1 ..^ @primes - 1 -> $p {
given (@primes[$p - 1] + @primes[$p + 1]) / 2 {
when * > @primes[$p] { @weak.push: @primes... | Give a code snippet in #Raku
Definitions (as per number theory)
The prime(p) is the pth prime.
prime(1) is 2
prime(4) is 7
A strong prime is when prime(p) is > [prime(p-1) + prime(p+1)] ÷ 2
A weak prime is when prime(p) is < [prime(p-1) + prime(p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 ... | #Action.21 | Action! | DEFINE MAX_SIZE="10"
DEFINE MAX_MATRIX_SIZE="100"
INT FUNC Index(BYTE size,x,y)
RETURN (x+y*size)
PROC PrintMatrix(BYTE ARRAY a BYTE size)
BYTE i,j,v
FOR j=0 TO size-1
DO
FOR i=0 TO size-1
DO
v=a(Index(size,i,j))
IF v<10 THEN
Print(" ")
ELSE
Print(" ")
FI
... | Give a code snippet in #Action.21
Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or co... | #Haskell | Haskell | import Data.Decimal
import Data.Ratio
import Data.Complex | Give a code snippet in #Haskell
Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[ed... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Erlang | Erlang | %% Implemented by Arjun Sunel
-module(nested_loops).
-export([main/0, inner_loop/0]).
main() ->
outer_loop(1).
inner_loop()->
inner_loop(1).
inner_loop(N) when N rem 5 =:= 0 ->
io:format("* ");
inner_loop(N) ->
io:fwrite("* "),
inner_loop(N+1).
outer_loop(N) when N rem 5 =:= 0 ->
io:format("*");
outer... | Give a code snippet in #Erlang
“For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract struct... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #BASIC | BASIC | 10 PRINT "Hello world!" | Give a code snippet in #BASIC
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Lasso | Lasso | local(a = 6, b = 4)
#a + #b // 10
#a - #b // 2
#a * #b // 24
#a / #b // 1
#a % #b // 2
math_pow(#a,#b) // 1296
math_pow(#b,#a) // 4096 | Give a code snippet in #Lasso
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p.... | #AWK | AWK |
# A comment starts with a "#" and are ignored by the machine. They can be on a
# line by themselves or at the end of an executable line.
#
# A program consists of multiple lines or statements. This program tests
# positive integers starting at 1 and terminates when one is found whose square
# ends in 269696.
#
# Th... | Give a code snippet in #AWK
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Comput... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bit... | #FreeBASIC | FreeBASIC | ' version 25-06-2015
' compile with: fbc -s console
Sub calc_entropy(source As String, base_ As Integer)
Dim As Integer i, sourcelen = Len(source), totalchar(255)
Dim As Double prop, entropy
For i = 0 To sourcelen -1
totalchar(source[i]) += 1
Next
Print "Char count"
For i = 0 ... | Give a code snippet in #FreeBASIC
Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binar... | christopher/rosetta-code | |
http://rosettacode.org/wiki/15_puzzle_solver | 15 puzzle solver | Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.
For this task you will be using the following puzzle:
15 14 1 6
9 11 4 12
0 10 7 3
13 8 5 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
The output must show the moves' dir... | #Nim | Nim |
# 15 puzzle.
import strformat
import times
const
Nr = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
Nc = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]
type
Solver = object
n: int
np: int
n0: array[100, int]
n2: array[100, uint64]
n3: array[100, char]
n4: array[100, int]
... | Give a code snippet in #Nim
Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.
For this task you will be using the following puzzle:
15 14 1 6
9 11 4 12
0 10 7 3
13 8 5 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
The ou... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_common_subsequence | Longest common subsequence | Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ... | #SETL | SETL | op .longest(a, b);
return if #a > #b then a else b end;
end .longest;
procedure lcs(a, b);
if exists empty in {a, b} | #empty = 0 then
return empty;
elseif a(1) = b(1) then
return a(1) + lcs(a(2..), b(2..));
else
return lcs(a(2..), b) .longest lcs(a, b(2..))... | Give a code snippet in #SETL
Introduction
Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string.
The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings.
Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be string... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Ada | Ada | with Ada.Containers.Ordered_Sets, Ada.Text_IO;
use Ada.Text_IO;
procedure Duplicate is
package Int_Sets is new Ada.Containers.Ordered_Sets (Integer);
Nums : constant array (Natural range <>) of Integer := (1,2,3,4,5,5,6,7,1);
Unique : Int_Sets.Set;
begin
for n of Nums loop
Unique.Include (n);
end loop;
for e... | Give a code snippet in #Ada
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.