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/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.
| #Ada | Ada | with Ada.Text_IO;
procedure Flushtest is
use Text_IO;
begin
Put_Line ("Type anything for 2 s");
delay 2.0;
Flush_Input:
declare
Ch : Character;
More : Boolean;
begin
loop
Get_Immediate (Ch, More);
exit when not More;
end loop;
end Flush_Input;
New_Line;
... | Give a code snippet in #Ada
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/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
| #SNOBOL4 | SNOBOL4 | OUTPUT = "Hello world!"
END | Give a code snippet in #SNOBOL4
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/Substring | Substring |
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 |... | #Liberty_BASIC | Liberty BASIC | 'These tasks can be completed with various combinations of Liberty Basic's
'built in Mid$()/ Instr()/ Left$()/ Right$()/ and Len() functions, but these
'examples only use the Mid$()/ Instr()/ and Len() functions.
baseString$ = "Thequickbrownfoxjumpsoverthelazydog."
n = 12
m = 5
'starting from n characters in and of... | Give a code snippet in #Liberty_BASIC
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 Ope... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Raku | Raku | class Thing {
method regular-example() { say 'I haz a method' }
multi method multi-example() { say 'No arguments given' }
multi method multi-example(Str $foo) { say 'String given' }
multi method multi-example(Int $foo) { say 'Integer given' }
};
# 'new' is actually a method, not a special keyword:
my $thin... | Give a code snippet in #Raku
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
Stri... | #BCPL | BCPL | get "libhdr"
let ordinal(n) =
n=1 -> "first", n=2 -> "second", n=3 -> "third",
n=4 -> "fourth", n=5 -> "fifth", n=6 -> "sixth",
n=7 -> "seventh", n=8 -> "eighth", n=9 -> "ninth",
n=10 -> "tenth", n=11 -> "eleventh", n=12 -> "twelfth",
valof finish
let gift(n) =
n=1 -> ... | Give a code snippet in #BCPL
Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displa... | #HicEst | HicEst | REAL :: a(1000)
a = 1 / $^2
WRITE(ClipBoard, Format='F17.15') SUM(a) | Give a code snippet in #HicEst
Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort | Sorting algorithms/Quicksort |
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
... | #Factor | Factor | : qsort ( seq -- seq )
dup empty? [
unclip [ [ < ] curry partition [ qsort ] bi@ ] keep
prefix append
] unless ; | Give a code snippet in #Factor
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 s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Longest_string_challenge | Longest string challenge | Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th... | #PureBasic | PureBasic |
Procedure.i ConsoleWrite(t.s) ; compile using /CONSOLE option
OpenConsole()
PrintN (t.s)
CloseConsole()
ProcedureReturn 1
EndProcedure
Procedure.i StdOut(t.s) ; compile using /CONSOLE option
OpenConsole()
Print(t.s)
CloseConsole()
ProcedureReturn 1... | Give a code snippet in #PureBasic
Background
This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the cha... | 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 ... | #JavaScript | JavaScript | (function(){print("("+arguments.callee.toString().replace(/\s/g,'')+")()");})() | Give a code snippet in #JavaScript
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 progr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #PL.2FI | PL/I | declare (c1, c2) character (1);
declare run_length fixed binary;
declare input file;
open file (input) title ('/RLE.DAT,type(text),recsize(20000)');
on endfile (input) go to epilog;
get file (input) edit (c1) (a(1));
run_length = 1;
do forever;
get file (input) edit (c2) (a(1));
if c1 = c2 then
run_leng... | Give a code snippet in #PL.2FI
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a fun... | christopher/rosetta-code | |
http://rosettacode.org/wiki/HTTPS | HTTPS | Task
Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console.
Checking the host certificate for validity is recommended.
Do not authenticate. That is the subject of other tasks.
Readers may wish to contrast with the HTTP Request task, and also the task on HTT... | #JavaScript | JavaScript | fetch("https://sourceforge.net").then(function (response) {
return response.text();
}).then(function (body) {
return body;
}); | Give a code snippet in #JavaScript
Task
Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console.
Checking the host certificate for validity is recommended.
Do not authenticate. That is the subject of other tasks.
Readers may wish to contrast with the HTTP Re... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Monads/Maybe_monad | Monads/Maybe monad | Demonstrate in your programming language the following:
Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
Make two functions, each which take a number and return a monadic number, e.g. Int ... | #JavaScript | JavaScript | (function () {
'use strict';
// START WITH SOME SIMPLE (UNSAFE) PARTIAL FUNCTIONS:
// Returns Infinity if n === 0
function reciprocal(n) {
return 1 / n;
}
// Returns NaN if n < 0
function root(n) {
return Math.sqrt(n);
}
// Returns -Infinity if n === 0
// ... | Give a code snippet in #JavaScript
Demonstrate in your programming language the following:
Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
Make two functions, each which take a number an... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Go | Go | package main
import (
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "localhost:256")
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
_, err = conn.Write([]byte("hello socket world"))
if err != nil {
fmt.Println(err)
}
} | Give a code snippet in #Go
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Ulam_spiral_(for_primes) | Ulam spiral (for primes) | An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is shown with sequential integers, ... | #Phix | Phix | with javascript_semantics
function spiral(integer w, h, x, y)
return iff(y?w+spiral(h-1,w,y-1,w-x-1):x)
end function
integer w = 9, h = 9
for i=h-1 to 0 by -1 do
for j=w-1 to 0 by -1 do
integer p = w*h-spiral(w,h,j,i)
puts(1,"o "[2-is_prime(p)])
end for
puts(1,'\n')
end for
| Give a code snippet in #Phix
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1), constructed on a square grid, starting at the "center".
An Ulam spiral is also known as a prime spiral.
The first grid (green) is show... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PHP | PHP | function move($n,$from,$to,$via) {
if ($n === 1) {
print("Move disk from pole $from to pole $to");
} else {
move($n-1,$from,$via,$to);
move(1,$from,$to,$via);
move($n-1,$via,$to,$from);
}
} | Give a code snippet in #PHP
Task
Solve the Towers of Hanoi problem with recursion.
| 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.
| #jq | jq |
def svg:
"<svg width='100%' height='100%' version='1.1'
xmlns='http://www.w3.org/2000/svg'
xmlns:xlink='http://www.w3.org/1999/xlink'>" ;
def draw_yinyang(x; scale):
"<use xlink:href='#y' transform='translate(\(x),\(x)) scale(\(scale))'/>";
def define_yinyang:
"<defs>
<g id='y'>
<circle... | Give a code snippet in #jq
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/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #11l | 11l | L(i) 1..
print(i) | Give a code snippet in #11l
Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #EchoLisp | EchoLisp |
;; CSV -> LISTS
(define (csv->row line) (map (lambda(x) (or (string->number x) x)) (string-split line ",")))
(define (csv->table csv) (map csv->row (string-split csv "\n")))
;; LISTS -> CSV
(define (row->csv row) (string-join row ","))
(define (table->csv header rows)
(string-join (cons (row->csv header) (fo... | Give a code snippet in #EchoLisp
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Wireworld | Wireworld | Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell transitions happen simultaneous... | #Forth | Forth | 16 constant w
8 constant h
: rows w * 2* ;
1 rows constant row
h rows constant size
create world size allot
world value old
old w + value new
: init world size erase ;
: age new old to new to old ;
: foreachrow ( xt -- )
size 0 do I over execute row +loop drop ;
0 constant EMPTY
1 constant ... | Give a code snippet in #Forth
Wireworld
Conway's Game of Life
It is capable of doing sophisticated computations with appropriate programs
(it is actually Turing complete),
and is much simpler to program for.
A Wireworld arena consists of a Cartesian grid of cells,
each of which can be in one of four states.
All cell ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime | Add a variable to a class instance at runtime | Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re... | #PHP | PHP | class E {};
$e=new E();
$e->foo=1;
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable | Give a code snippet in #PHP
Demonstrate how to dynamically add variables to an object (a class instance) at runtime.
This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprog... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime,... | #APL | APL |
⍝ Determine whether given list of integers has GCD = 1
primitive←∧/1=2∨/⊢
⍝ Filter list given as right operand by applying predicate given as left operand
filter←{⍵⌿⍨⍺⍺ ⍵}
⍝ Function pytriples finds all triples given a maximum perimeter
∇res←pytriples maxperimeter;sos;sqrt;cartprod;ascending;ab_max;c_max;a_b_pairs;... | Give a code snippet in #APL
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
... | #AutoHotkey | AutoHotkey | Loop, %A_WinDir%\*.ini
out .= A_LoopFileName "`n"
MsgBox,% out | Give a code snippet in #AutoHotkey
Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single direct... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
... | #Julia | Julia | A' | Give a code snippet in #Julia
Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Xtend | Xtend |
package com.rosetta.example
import java.io.File
import java.io.PrintStream
class ReadFile {
def static main( String ... args ) {
val content = new String(Files.readAllBytes(Paths.get("file.txt")))
}
}
| Give a code snippet in #Xtend
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incre... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ranking_methods | Ranking methods |
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
... | #Julia | Julia |
function ties{T<:Real}(a::Array{T,1})
unique(a[2:end][a[2:end] .== a[1:end-1]])
end
| Give a code snippet in #Julia
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 so... | 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
... | #Maple | Maple | > L := [ 1, 2, 1, 2, 3, 3, 2, 1, "a", "b", "b", "a", "c", "b" ];
L := [1, 2, 1, 2, 3, 3, 2, 1, "a", "b", "b", "a", "c", "b"]
> [op]({op}(L));
[1, 2, 3, "a", "b", "c"] | Give a code snippet in #Maple
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 so... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #Java | Java | public class LynchBell {
static String s = "";
public static void main(String args[]) {
//Highest number with unique digits (no 0 or 5)
int i = 98764321;
boolean isUnique = true;
boolean canBeDivided = true;
while (i>0) {
s = String.valueOf(i);
... | Give a code snippet in #Java
Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Langton%27s_ant | Langton's ant | Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the following rules:
If the ce... | #AWK | AWK |
# usage: awk -v debug=0 -f langton.awk
# Simulates the cellular automaton "Langton's ant",
# see http://en.wikipedia.org/wiki/Langton%27s_ant
function turnRight() {
dir++
if( dir>4 ) { dir=1 }
}
function turnLeft() {
dir--
if( dir<1 ) { dir=4 }
}
function move() {
if (dir==1) { y--; z="^" }
if (dir==3) { ... | Give a code snippet in #AWK
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.
Each cell can either be black or white.
The ant moves according to the color of the cell it is currently sitting in, with the f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_prepend | String prepend |
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 |... | #Nim | Nim | # Direct way.
var str1, str2 = "12345678"
str1 = "0" & str1
echo str1
# Using "insert".
str2.insert("0")
echo str2
| Give a code snippet in #Nim
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
Co... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_the_missing_permutation | Find the missing permutation | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
... | #Wren | Wren | import "./set" for Set
import "./perm" for Perm
var missingPerms = Fn.new { |input, perms|
var s1 = Set.new()
s1.addAll(perms)
var perms2 = Perm.list(input).map { |p| p.join() }
var s2 = Set.new()
s2.addAll(perms2)
return s2.except(s1).toList
}
var input = ["A", "B", "C", "D"]
var perms = [
... | Give a code snippet in #Wren
ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #Fortran | Fortran |
!Implemented by Anant Dixit (October 2014)
program flipping_bits
implicit none
character(len=*), parameter :: cfmt = "(A3)", ifmt = "(I3)"
integer :: N, i, j, io, seed(8), moves, input
logical, allocatable :: Brd(:,:), Trgt(:,:)
logical :: solved
double precision :: r
do
write(*,*) 'Enter the number of squares (b... | Give a code snippet in #Fortran
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one m... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #JavaScript | JavaScript | const assert = require('assert');
describe('palindrome', () => {
const pali = require('../lib/palindrome');
describe('.check()', () => {
it('should return true on encountering a palindrome', () => {
assert.ok(pali.check('racecar'));
assert.ok(pali.check('abcba'));
assert.ok(pali.check('aa'... | Give a code snippet in #JavaScript
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Perfect_shuffle | Perfect shuffle | A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠
When you ... | #Tcl | Tcl | namespace eval shuffle {
proc perfect {deck} {
if {[llength $deck]%2} {
return -code error "Deck must be of even length!"
}
set split [expr {[llength $deck]/2}]
set top [lrange $deck 0 $split-1]
set btm [lrange $deck $split end]
foreach a $top b $btm {
... | Give a code snippet in #Tcl
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:
7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠ 8♠ 9♠
J♠ Q♠ K♠→... | christopher/rosetta-code | |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Go | Go | package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
} | Give a code snippet in #Go
User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| 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... | #Lua | Lua | local build_freqtable = function (data)
local freq = { }
for i = 1, #data do
local cur = string.sub (data, i, i)
local count = freq [cur] or 0
freq [cur] = count + 1
end
local nodes = { }
for w, f in next, freq do
nodes [#nodes + 1] = { word = w, freq = f }
end
table.sort (nodes, fun... | Give a code snippet in #Lua
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 cou... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications | Abundant, deficient and perfect number classifications | These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient (OEIS A005100).
if P(n)... | #Wren | Wren | import "/math" for Int, Nums
var d = 0
var a = 0
var p = 0
for (i in 1..20000) {
var j = Nums.sum(Int.properDivisors(i))
if (j < i) {
d = d + 1
} else if (j == i) {
p = p + 1
} else {
a = a + 1
}
}
System.print("There are %(d) deficient numbers between 1 and 20000")
System.... | Give a code snippet in #Wren
These define three classifications of positive integers based on their proper divisors.
Let P(n) be the sum of the proper divisors of n where the proper divisors are all positive divisors of n other than n itself.
if P(n) < n then n is classed as deficient ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #JavaScript | JavaScript |
function selfReferential(n) {
n = n.toString();
let res = [n];
const makeNext = (n) => {
let matchs = {
'9':0,'8':0,'7':0,'6':0,'5':0,'4':0,'3':0,'2':0,'1':0,'0':0}, res = [];
for(let index=0;index<n.length;index++)
matchs[n[index].toString()]++;
for(let ind... | Give a code snippet in #JavaScript
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/MD5 | MD5 | Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the algorithm than the Wikipedia article.
Warning:... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | USER>set hash=$System.Encryption.MD5Hash("The quick brown fox jumped over the lazy dog's back")
USER>zzdump hash
0000: E3 8C A1 D9 20 C4 B8 B8 D3 94 6B 2C 72 F0 16 80 | Give a code snippet in #Cach.C3.A9_ObjectScript
Task
Encode a string using an MD5 algorithm. The algorithm can be found on Wikipedia.
Optionally, validate your implementation by running all of the test values in IETF RFC (1321) for MD5.
Additionally, RFC 1321 provides more precise information on the a... | 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... | #Mercury | Mercury |
% file: beer.m
% author:
% Fergus Henderson <fjh@cs.mu.oz.au> Thursday 9th November 1995
% Re-written with new syntax standard library calls:
% Paul Bone <paul@mercurylang.org> 2015-11-20
%
% This beer song is more idiomatic Mercury than the original, I feel bad
% saying that since Fergus is a founder of the lang... | Give a code snippet in #Mercury
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
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rhonda_numbers | Rhonda numbers | A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is ... | #Wren | Wren | import "./math" for Math, Int, Nums
import "./fmt" for Fmt, Conv
for (b in 2..36) {
if (Int.isPrime(b)) continue
var count = 0
var rhonda = []
var n = 1
while (count < 15) {
var digits = Int.digits(n, b)
if (!digits.contains(0)) {
if (b != 10 || (digits.contains(5) && d... | Give a code snippet in #Wren
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers w... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hostname | Hostname | Task
Find the name of the host on which the routine is running.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "socket.s7i";
const proc: main is func
begin
writeln(getHostname);
end func; | Give a code snippet in #Seed7
Task
Find the name of the host on which the routine is running.
| 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... | #LabVIEW | LabVIEW | '%4o '__number_format set
0 do dup 1 compress . "\n" . 1 + loop | Give a code snippet in #LabVIEW
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.... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Positional_read | Terminal control/Positional read | Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, r... | #Kotlin | Kotlin | // Kotlin Native version 0.3
import kotlinx.cinterop.*
import win32.*
fun main(args: Array<String>) {
for (i in 0 until (80 * 25)) print("A") // fill 80 x 25 console with 'A's
println()
memScoped {
val conOut = GetStdHandle(-11)
val info = alloc<CONSOLE_SCREEN_BUFFER_INFO>()
... | Give a code snippet in #Kotlin
Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Generator/Exponential | Generator/Exponential | A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that the internal state of the objec... | #Scheme | Scheme | (define (power-seq n)
(let ((i 0))
(lambda ()
(set! i (+ 1 i))
(expt i n))))
(define (filter-seq m n)
(let* ((s1 (power-seq m)) (s2 (power-seq n))
(a 0) (b 0))
(lambda ()
(set! a (s1))
(let loop ()
(if (>= a b) (begin
(cond ((> a b) (set! b (s2)))
((= a b) ... | Give a code snippet in #Scheme
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
Generators are often built on top of coroutines or objects so that... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Polyspiral | Polyspiral | A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b... | #Nim | Nim | # Pendulum simulation.
import math, random
import gintro/[gobject, gdk, gtk, gio, glib, cairo]
const
Width = 500
Height = 500
DrawIters = 72
Red = [float 1, 0, 0]
Green = [float 0, 1, 0]
Blue = [float 0, 0, 1]
Black = [float 0, 0, 0]
White = [float 255, 255, 255]
Gold = [float 255, 215, 0]
Col... | Give a code snippet in #Nim
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the ang... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
... | #JavaScript | JavaScript | function root_mean_square(ary) {
var sum_of_squares = ary.reduce(function(s,x) {return (s + x*x)}, 0);
return Math.sqrt(sum_of_squares / ary.length);
}
print( root_mean_square([1,2,3,4,5,6,7,8,9,10]) ); // ==> 6.2048368229954285 | Give a code snippet in #JavaScript
Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Factor | Factor | : supremum ( seq -- elt ) [ ] [ max ] map-reduce ; | Give a code snippet in #Factor
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #Fortran | Fortran | DO WHILE(F*F <= LST) !But, F*F might overflow the integer limit so instead,
DO WHILE(F <= LST/F) !Except, LST might also overflow the integer limit, so
DO WHILE(F <= (IST + 2*(SBITS - 1))/F) !Which becomes...
DO WHILE(F <= IST/F + (MOD(IST,F) + 2*(SBITS - 1))/F) ... | Give a code snippet in #Fortran
Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or pr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #Maple | Maple | a := [bear, giraffe, dog, rabbit, koala, lion, fox, deer, pony]:
randomNum := rand(1 ..numelems(a)):
a[randomNum()]; | Give a code snippet in #Maple
Demonstrate how to pick a random element from a list.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #OCaml | OCaml | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " ... | Give a code snippet in #OCaml
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numb... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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)
Task
Create a simple demonstrative example of Currying in a specific la... | #jq | jq |
def plus(x): . + x;
def plus5: plus(5);
| Give a code snippet in #jq
This page uses content from Wikipedia. The original article was at Currying. 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)
Task
Create a simple demonstrative example ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #Yabasic | Yabasic | data "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030", "AB", "B00A03", ""
do
read d$
if d$ = "" break
print sedol$(d$)
loop
sub sedol$(d$)
LOCAL a, i, s, weights$(1)
a = len(d$)
if a < 6 or a > 6 return d$ + ": Error in length"
... | Give a code snippet in #Yabasic
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
58528... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #Nim | Nim | import strformat
const MAX = 12
var super: seq[char] = @[]
var pos: int
var cnt: array[MAX, int]
proc factSum(n: int): int =
var s, x = 0
var f = 1
while x < n:
inc x
f *= x
inc s, f
s
proc r(n: int): bool =
if n == 0:
return false
var c = super[pos - n]
dec cnt[n]
if cnt[n] == ... | Give a code snippet in #Nim
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #PicoLisp | PicoLisp | (in '(rec -q -c1 -tu16 - trim 0 2) # Record 2 seconds
(make
(while (rd 2)
(link @) ) ) ) | Give a code snippet in #PicoLisp
Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample ra... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #TI-83_Hex_Assembly | TI-83 Hex Assembly | PROGRAM:EMPTY
:AsmPrgmC9 | Give a code snippet in #TI-83_Hex_Assembly
Task
Create the simplest possible program that is still considered "correct."
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #Perl | Perl |
#!/usr/bin/perl
my @even_numbers;
for (1..7)
{
if ( $_ % 2 == 0)
{
push @even_numbers, $_;
}
}
print "Police\tFire\tSanitation\n";
foreach my $police_number (@even_numbers)
{
for my $fire_number (1..7)
{
for my $sanitation_number (1..7)
{
if ( $police_number + $fire_number + $sanit... | Give a code snippet in #Perl
There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (dif... | 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... | #Action.21 | Action! | PROC ReverseDigits(CHAR ARRAY n,rev)
BYTE i,j
i=n(0)
WHILE i>0 AND n(i)='0
DO
i==-1
OD
j=1
WHILE i>0
DO
rev(j)=n(i)
j==+1 i==-1
OD
rev(0)=j-1
RETURN
BYTE FUNC SumOddDigits(CHAR ARRAY n)
BYTE sum,i
sum=0
FOR i=1 TO n(0) STEP 2
DO
sum==+ValB(n(i))
OD
RETURN(sum)
BYT... | Give a code snippet in #Action.21
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 orde... | 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
| #Scala | Scala | repeat with each item of [True, False, Yes, No, On, Off, ""]
put it & " is " & (it is true)
end repeat
| Give a code snippet in #Scala
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/Find_the_intersection_of_a_line_with_a_plane | Find the intersection of a line with a plane | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes ... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE REALPTR="CARD"
TYPE VectorR=[REALPTR x,y,z]
PROC PrintVector(VectorR POINTER v)
Print("(") PrintR(v.x)
Print(",") PrintR(v.y)
Print(",") PrintR(v.z)
Print(")")
RETURN
PROC Vector(REAL POINTER vx,vy,vz VectorR POINTER v)
v.x=vx v.y=vy v.z=vz
RETURN
... | Give a code snippet in #Action.21
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
Task
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation | Bioinformatics/Sequence mutation | Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o... | #Common_Lisp | Common Lisp |
(defun random_base ()
(random 4))
(defun basechar (base)
(char "ACTG" base))
(defun generate_genome (genome_length)
(let (genome '())
(loop for i below genome_length do
(push (random_base) genome))
(return-from generate_genome genome)))
(defun map_genome (genome)
(let... | Give a code snippet in #Common_Lisp
Task
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
Choosing a random base position in the sequence.
Mutate the sequence by doing one of either:
Swap the base at that position by changing it to one of... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #Bracmat | Bracmat | ( (plus=a b.!arg:(?a.?b)&!a+!b)
& ( print
= text a b func
. !arg:(?a.?b.(=?func).?text)
& out$(str$(!text "(" !a "," !b ")=" func$(!a.!b)))
)
& print$(3.7.'$plus.add)
& print
$ ( 3
. 7
. (=a b.!arg:(?a.?b)&!a*!b)
. multiply
)
); | Give a code snippet in #Bracmat
Task
Pass a function as an argument to another function.
Related task
First-class functions
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. 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)
Thiele's interpolation formula is an interpolation ... | #Common_Lisp | Common Lisp | ;; 256 is heavy overkill, but hey, we memoized
(defparameter *thiele-length* 256)
(defparameter *rho-cache* (make-hash-table :test #'equal))
(defmacro make-thele-func (f name xx0 xx1)
(let ((xv (gensym)) (yv (gensym))
(x0 (gensym)) (x1 (gensym)))
`(let* ((,xv (make-array (1+ *thiele-length*)))
(,yv (make-... | Give a code snippet in #Common_Lisp
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. 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)
Thiele's inter... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Order | Order | #include <order/interpreter.h>
#define ORDER_PP_DEF_8gcd ORDER_PP_FN( \
8fn(8U, 8V, \
8if(8isnt_0(8V), 8gcd(8V, 8remainder(8U, 8V)), 8U)))
#define ORDER_PP_DEF_8lcm ORDER_PP_FN( \
8fn(8X, 8Y, \
8if(8or(8is_0(8X), 8is_0(8Y)), \
0, ... | Give a code snippet in #Order
Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #VTL-2 | VTL-2 | 10 P=2
20 S=1
30 F=1
40 #=0<((P=S)+(P=F)+(S=F)+(P+S+F=12=0))*110
50 ?=P
60 $=32
70 ?=S
80 $=32
90 ?=F
100 ?=""
110 F=F+1
120 #=F<8*40
130 S=S+1
140 #=S<8*30
150 P=P+2
160 #=P<8*20 | Give a code snippet in #VTL-2
There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (di... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Combinations_with_repetitions | Combinations with repetitions | The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of those sets is chosen from
S... | #Erlang | Erlang |
-module(comb).
-compile(export_all).
comb_rep(0,_) ->
[[]];
comb_rep(_,[]) ->
[];
comb_rep(N,[H|T]=S) ->
[[H|L] || L <- comb_rep(N-1,S)]++comb_rep(N,T).
| Give a code snippet in #Erlang
The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #SAS | SAS |
The macro "palindro" has two parameters: string and ignorewhitespace.
string is the expression to be checked.
ignorewhitespace, (Y/N), determines whether or not to ignore blanks and punctuation.
This macro was written in SAS 9.2. If you use a version before SAS 9.1.3,
the compress function options will not work... | Give a code snippet in #SAS
A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits | Largest number divisible by its digits | Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and n is divisible by each of it... | #XPL0 | XPL0 | int Digits; \bit array
func AllDiv(N); \Return 'true' if N is divisible by its digits
int N, D;
[for D:= 9 downto 2 do
if 1<<D & Digits then
if rem(N/D) # 0 then return false;
return true;
];
func Unique(N); \Return 'true' if N contains unique digits
int N;
[Digits:= 1; \disallow 0
while N do
... | Give a code snippet in #XPL0
Task
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as Lynch-Bell numbers, numbers n such that the
(base ten) digits are all different (and do not include zero) and ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Factor | Factor | "docs" "/docs" [ delete-tree ] bi@
"input.txt" "/input.txt" [ delete-file ] bi@ | Give a code snippet in #Factor
Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(... | #Wren | Wren | import "./sql" for Sql, Connection
import "./crypto" for Md5
var addUser = Fn.new { |db, name, pw|
var sql = "INSERT OR IGNORE INTO users (username,pass_salt,pass_md5) VALUES(?, ?, ?)"
var stmt = db.prepare(sql)
var salt = Sql.randomness(16)
var md5s = Md5.digest(salt + pw)
stmt.bindText(1, name)
... | Give a code snippet in #Wren
This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_IN... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-... | #JavaScript | JavaScript | //makes outputting a table possible in environments
//that don't support console.table()
function console_table(xs) {
function pad(n,s) {
var res = s;
for (var i = s.length; i < n; i++)
res += " ";
return res;
}
if (xs.length === 0)
console.log("No data");
... | Give a code snippet in #JavaScript
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤... | #Jsish | Jsish | /* A+B in Jsish */
var line = console.input();
var nums = line.match(/^\s*([+-]?[0-9]+)\s+([+-]?[0-9]+)\s*/);
if (nums) {
var A = Number(nums[1]);
var B = Number(nums[2]);
if (A <= 1000 && A >= -1000 && B <= 1000 && B >= -1000) {
printf("%d\n", A + B);
} else {
puts("error: A and B both ... | Give a code snippet in #Jsish
A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separate... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
STRUCT (REAL x, y, heading, BOOL pen down) turtle;
PROC turtle init = VOID: (
draw erase (window);
turtle := (0.5, 0.5, 0, TRUE);
draw move (window, x OF turtle, y OF turtle);
draw colour name(window, "white")
);
PROC turtle left = (REAL left turn)VOID:
heading OF turtle +:= le... | Give a code snippet in #ALGOL_68
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
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.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
S... | #Brlcad | Brlcad | c lamp base stem bulb shade chord plug
| Give a code snippet in #Brlcad
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.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are n... | #JavaScript | JavaScript | function isEsthetic(inp, base = 10) {
let arr = inp.toString(base).split('');
if (arr.length == 1) return false;
for (let i = 0; i < arr.length; i++)
arr[i] = parseInt(arr[i], base);
for (i = 0; i < arr.length-1; i++)
if (Math.abs(arr[i]-arr[i+1]) !== 1) return false;
return true;
}
function collect... | Give a code snippet in #JavaScript
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Kotlin | Kotlin | // Version 1.3.21
fun chowla(n: Int): Int {
if (n < 1) throw RuntimeException("argument must be a positive integer")
var sum = 0
var i = 2
while (i * i <= n) {
if (n % i == 0) {
val j = n / i
sum += if (i == j) i else i + j
}
i++
}
return sum
}
... | Give a code snippet in #Kotlin
Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file | Append a record to the end of a text file | Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most useful in the case of log files,... | #Groovy | Groovy | class PasswdRecord {
String account, password, directory, shell
int uid, gid
SourceRecord source
private static final fs = ':'
private static final fieldNames = ['account', 'password', 'uid', 'gid', 'source', 'directory', 'shell']
private static final stringFields = ['account', 'password', 'di... | Give a code snippet in #Groovy
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.
This feature is most ... | 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... | #Factor | Factor | USING: fry io kernel math math.functions math.order sequences
splitting strings ;
IN: rosetta.column-aligner
CONSTANT: example-text "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$e... | Give a code snippet in #Factor
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/Latin_Squares_in_reduced_form | Latin Squares in reduced form | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S... | #Wren | Wren | import "/sort" for Sort
import "/math" for Int
import "/fmt" for Fmt
// generate derangements of first n numbers, with 'start' in first place.
var dList = Fn.new { |n, start|
var r = []
start = start - 1 // use 0 basing
var a = [0] * n
for (i in 1...n) a[i] = i
a[start] = a[0]
a[0] = start
... | Give a code snippet in #Wren
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element wit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Play_recorded_sounds | Play recorded sounds | Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performing other actions when marked times... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
audiofile="test.wav"
ERROR/STOP OPEN (audiofile,READ,-std-)
BROWSE $audiofile
| Give a code snippet in #TUSCRIPT
Load at least two prerecorded sounds, and demonstrate as many of these features as you can:
playing them individually and simultaneously
stopping before the end of the sound
looping (preferably glitch-free)
setting the volume of each sound
stereo or 3D positional mixing
performi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Truncate_a_file | Truncate a file | Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced... | #Delphi | Delphi | procedure TruncateFile(FileName : string; NewSize : integer);
var
aFile: file of byte;
begin
Assign(aFile, FileName);
Reset(aFile);
try
Seek(afile, NewSize);
Truncate(aFile);
finally
Close(afile);
end;
end; | Give a code snippet in #Delphi
Task
Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).
Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creati... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compound_data_type | Compound data type |
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.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
Related task
Enumeration
S... | #zonnon | zonnon |
{ref,public} (* class *)
Point = object(ord,abs: integer)
var
(* instance variables *)
{public,immutable} x,y: integer;
(* method *)
procedure {public} Ord():integer;
begin
return y
end Ord;
(* method *)
procedure {public} Abs():integer;
begin
return x
end Abs;
(* constructor *)
begin
self... | Give a code snippet in #zonnon
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.
Task
Create a compound data type:
Point(x,y)
A compound data type is one that holds multiple independent values.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Modified_random_distribution | Modified random distribution | Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand... | #Julia | Julia | using UnicodePlots
modifier(x) = (y = 2x - 1; y < 0 ? -y : y)
modrands(rands1, rands2) = [x for (i, x) in enumerate(rands1) if rands2[i] < modifier(x)]
histogram(modrands(rand(50000), rand(50000)), nbins = 20)
| Give a code snippet in #Julia
Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the followin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #E | E | def move(out, n, fromPeg, toPeg, viaPeg) {
if (n.aboveZero()) {
move(out, n.previous(), fromPeg, viaPeg, toPeg)
out.println(`Move disk $n from $fromPeg to $toPeg.`)
move(out, n.previous(), viaPeg, toPeg, fromPeg)
}
}
move(stdout, 4, def left {}, def right {}, def middle {}) | Give a code snippet in #E
Task
Solve the Towers of Hanoi problem with recursion.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
W... | #VBA | VBA | Sub copystring()
a = "Hello World!"
b = a
a = "I'm gone"
Debug.Print b
Debug.Print a
End Sub | Give a code snippet in #VBA
This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty str... | christopher/rosetta-code | |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Elixir | Elixir | defmodule LZW do
@encode_map Enum.into(0..255, Map.new, &{[&1],&1})
@decode_map Enum.into(0..255, Map.new, &{&1,[&1]})
def encode(str), do: encode(to_char_list(str), @encode_map, 256, [])
defp encode([h], d, _, out), do: Enum.reverse([d[[h]] | out])
defp encode([h|t], d, free, out) do
val = d[[h]]
... | Give a code snippet in #Elixir
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) ... | #PicoLisp | PicoLisp | (load "@lib/simul.l") # For 'shuffle'
(de generateBrackets (N)
(shuffle (make (do N (link "[" "]")))) )
(de checkBrackets (S)
(let N 0
(for C S
(if (= C "[")
(inc 'N)
(if2 (= C "]") (=0 N)
(off N)
(dec 'N) ) ) )
(=0 N) ) )
(for N 10... | Give a code snippet in #PicoLisp
Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Haskell | Haskell | (++) :: [a] -> [a] -> [a] | Give a code snippet in #Haskell
Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Haskell | Haskell | import System.IO
main = hPutStrLn stderr "Goodbye, World!" | Give a code snippet in #Haskell
Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard ou... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of ... | #FutureBasic | FutureBasic |
include "NSLog.incl"
local fn SumOfProperDivisors( n as NSUInteger ) as NSUinteger
NSUinteger sum = 1
cln for (unsigned i = 3, j; i < sqrt(n)+1; i += 2) if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
end fn = sum
NSUinteger n, c
cln for (n = 1, c = 0; c < 25; n += 2 ) if ( n < SumOfProperDivisors( n ) )... | Give a code snippet in #FutureBasic
An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or... | 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 ... | #BCPL | BCPL | get "libhdr"
let start() be
$( let x = table
13,10,32,32,32,32,108,101,116,32,110,32,61,32,48,
13,10,32,32,32,32,119,114,105,116,101,115,40,34,103,
101,116,32,42,34,108,105,98,104,100,114,42,34,42,78,
42,78,108,101,116,32,115,116,97,114,116,40,41,32,98,
101,42,78,36,40,32,32,108,101,116,32,120,32... | Give a code snippet in #BCPL
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/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always ... | #Java | Java | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Hidato {
private static int[][] board;
private static int[] given, start;
public static void main(String[] args) {
String[] input = {"_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"... | Give a code snippet in #Java
The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connect... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Atomic_updates | Atomic updates |
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t... | #Clojure | Clojure | (defn xfer [m from to amt]
(let [{f-bal from t-bal to} m
f-bal (- f-bal amt)
t-bal (+ t-bal amt)]
(if (or (neg? f-bal) (neg? t-bal))
(throw (IllegalArgumentException. "Call results in negative balance."))
(assoc m from f-bal to t-bal)))) | Give a code snippet in #Clojure
Task
Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:
get the current value of any bucket
remove a specified amount from one specified bucket and add it to another, preserving the total of all ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Standard_error | Hello world/Standard error | Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".
The error messages print to ... | #Raku | Raku | note "Goodbye, World!"; | Give a code snippet in #Raku
Hello world/Standard error is part of Short Circuit's Console Program Basics selection.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called "standard output" or "standard out".... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ethiopian_multiplication | Ethiopian multiplication | Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ... | #Action.21 | Action! | INT FUNC EthopianMult(INT a,b)
INT res
PrintF("Ethopian multiplication %I by %I:%E",a,b)
res=0
WHILE a>=1
DO
IF a MOD 2=0 THEN
PrintF("%I %I strike%E",a,b)
ELSE
PrintF("%I %I keep%E",a,b)
res==+b
FI
a==/2
b==*2
OD
RETURN (res)
PROC Main()
INT res
res=EthopianM... | Give a code snippet in #Action.21
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
Take two numbers to be multiplied and write them down at the top of two columns.
In the left-hand column repeatedly halve the last number, discarding any remainders, a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/List_comprehensions | List comprehensions | A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and the use of map and filter functio... | #Scala | Scala | def pythagoranTriangles(n: Int) = for {
x <- 1 to 21
y <- x to 21
z <- y to 21
if x * x + y * y == z * z
} yield (x, y, z) | Give a code snippet in #Scala
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name.
Some attributes of a list comprehension are:
They should be distinct from (nested) for loops and th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p... | #Chapel | Chapel | proc binsearch(A:[], value) {
var low = A.domain.dim(1).low;
var high = A.domain.dim(1).high;
while (low <= high) {
var mid = (low + high) / 2;
if A(mid) > value then
high = mid - 1;
else if A(mid) < value then
... | Give a code snippet in #Chapel
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet | Generate lower case ASCII alphabet | Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task use a reliable style of coding, a sty... | #Standard_ML | Standard ML | val lowercase_letters = List.tabulate (26, fn x => chr (x + ord #"a")); | Give a code snippet in #Standard_ML
Task
Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.
For this basic task ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Needs["DatabaseLink`"];
connectDb[dbUser_, dbPass_, dbUrl_] :=
OpenSQLConnection[JDBC["mysql", dbUrl], "Username" -> dbUser,
"Password" -> dbPass];
createUser::nameTaken = "The username '`1`' is already taken.";
createUser[dbUser_, dbPass_, dbUrl_, user_, pass_] :=
Module[{db = connectDb[dbUser, dbPass, dbUrl... | Give a code snippet in #Mathematica.2FWolfram_Language
This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
user... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Logtalk | Logtalk |
:- object(foo).
:- public(try/0).
try :-
catch(bar::message, Error, handler(Error)).
handler(error(existence_error(predicate_declaration,message/0),_)) :-
% handle the unknown message
...
:- end_object.
| Give a code snippet in #Logtalk
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the poin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #Lua | Lua |
--returns the powerset of s, out of order.
function powerset(s, start)
start = start or 1
if(start > #s) then return {{}} end
local ret = powerset(s, start + 1)
for i = 1, #ret do
ret[#ret + 1] = {s[start], unpack(ret[i])}
end
return ret
end
--non-recurse implementation
function powerset(s)
local... | Give a code snippet in #Lua
A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.