task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its prece... | #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
var sbs = [1, 1]
var sternBrocot = Fn.new { |n, fromStart|
if (n < 4 || (n % 2 != 0)) Fiber.abort("n must be >= 4 and even.")
var consider = fromStart ? 1 : (n/2).floor - 1
while (true) {
var sum = sbs[consider] + sbs[consider - 1]
sbs.add(sum... |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET A$="|/-\"
20 FOR C=1 TO 4
30 PRINT AT 0,0;A$(C)
40 PAUSE 4
50 NEXT C
60 GOTO 20
|
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... | #E | E | ? def l := [].diverge()
# value: [].diverge()
? l.push(1)
? l.push(2)
? l
# value: [1, 2].diverge()
? l.pop()
# value: 2
? l.size().aboveZero()
# value: true
? l.last()
# value: 1
? l.pop()
# value: 1
? l.size().aboveZero()
# value: false |
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 ... | #BBC_BASIC | BBC BASIC | N%=5
@%=LENSTR$(N%*N%-1)+1
BotCol%=0 : TopCol%=N%-1
BotRow%=0 : TopRow%=N%-1
DIM Matrix%(TopCol%,TopRow%)
Dir%=0 : Col%=0 : Row%=0
FOR I%=0 TO N%*N%-1
Matrix%(Col%,Row%)=I%
PRINT TAB(Col%*@%,Row%) I%
CASE Dir% OF
WHEN 0: IF Col% < TopCol% THE... |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Icon_and_Unicon | Icon and Unicon |
# &keyword # type returned(indicators) - brief description
# indicators:
# * - generates multiple values
# = - modifiable
# ? - may fail (e.g. status inquiry)
# U - Unicon
# G - Icon or Unicon with Graphics
#
&allocated # integer(*) - report memory allocated in total and by storage regions
&ascii ... |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #Arturo | Arturo | ? A unary or dyadic operator giving 8 bit indirection.
! A unary or dyadic operator giving 32 bit indirection.
# As a prefix indicates a file channel number.
As a suffix indicates a 64-bit numeric variable or constant.
$ As a prefix indicates a 'fixed string' (string indirection).
As a su... |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #AutoHotkey | AutoHotkey | ? A unary or dyadic operator giving 8 bit indirection.
! A unary or dyadic operator giving 32 bit indirection.
# As a prefix indicates a file channel number.
As a suffix indicates a 64-bit numeric variable or constant.
$ As a prefix indicates a 'fixed string' (string indirection).
As a su... |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #AWK | AWK | ? A unary or dyadic operator giving 8 bit indirection.
! A unary or dyadic operator giving 32 bit indirection.
# As a prefix indicates a file channel number.
As a suffix indicates a 64-bit numeric variable or constant.
$ As a prefix indicates a 'fixed string' (string indirection).
As a su... |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a s... | #C.2B.2B | C++ |
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <locale>
class Sparkline {
public:
Sparkline(std::wstring &cs) : charset( cs ){
}
virtual ~Sparkline(){
}
void print(std::string spark){
const char *delim... |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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
... | #CMake | CMake | # strand_sort(<output variable> [<value>...]) sorts a list of integers.
function(strand_sort var)
# Strand sort moves elements from _ARGN_ to _answer_.
set(answer) # answer: a sorted list
while(DEFINED ARGN)
# Split _ARGN_ into two lists, _accept_ and _reject_.
set(accept) ... |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is o... | #F.23 | F# | let menPrefs =
Map.ofList
["abe", ["abi";"eve";"cath";"ivy";"jan";"dee";"fay";"bea";"hope";"gay"];
"bob", ["cath";"hope";"abi";"dee";"eve";"fay";"bea";"jan";"ivy";"gay"];
"col", ["hope";"eve";"abi";"dee";"bea";"fay";"ivy";"gay";"cath";"jan"];
"dan", ["ivy";"fay";... |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6t... | #Vlang | Vlang | fn main() {
for n in [i64(1), 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
] {
println(say_ordinal(n))
}
}
fn say_ordinal(n i64) string {
mut s := say(n)
mut i := s.last_index('-') or {s.last_index(' ') or {-1}}
i++
// Now s[:i] is everything upto and including the ... |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6t... | #Wren | Wren | var small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
v... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Quackery | Quackery | [ swap - -1 1 clamp 1+ ] is <=> ( n n --> n )
[ dup * ] is squared ( n --> n )
[ dup squared * ] is cubed ( n --> n )
0 0 []
[ unrot
over squared
over cubed <=>
[ table
1+
[ 1+ dip 1+ ]
[ dip
[ tuck squared
... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Racket | Racket | #lang racket
(require racket/generator)
;; generates values:
;; next square
;; cube-root if cube, #f otherwise
(define (make-^2-but-not-^3-generator)
(generator
()
(let loop ((s 1) (c 1))
(let ((s^2 (sqr s)) (c^3 (* c c c)))
(yield s^2 (and (= s^2 c^3) c))
(loop (add1 s) (+ c (if (>= s^2 ... |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #PicoLisp | PicoLisp | (de splitme (Str)
(let (Str (chop Str) Fin)
(glue
", "
(make
(for X Str
(if (= X (car Fin))
(conc Fin (cons X))
(link (setq Fin (cons X))) ) ) ) ) ) )
(prinl (splitme "gHHH5YY++///\\")) |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #Pike | Pike |
string input = "gHHH5YY++///\\"; // \ needs escaping
string last_char;
foreach(input/1, string char) {
if(last_char && char != last_char)
write(", ");
write(char);
last_char = char;
}
|
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its prece... | #zkl | zkl | fcn SB // Stern-Brocot sequence factory --> Walker
{ Walker(fcn(sb,n){ a,b:=sb; sb.append(a+b,b); sb.del(0); a }.fp(L(1,1))) }
SB().walk(15).println();
[1..10].zipWith('wrap(n){ [1..].zip(SB())
.filter(1,fcn(n,sb){ n==sb[1] }.fp(n)) })
.walk().println();
[1..].zip(SB()).filter1(fcn(sb){ 100==sb[1] }).prin... |
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... | #EchoLisp | EchoLisp |
; build stack [0 1 ... 9 (top)] from a list
(list->stack (iota 10) 'my-stack)
(stack-top 'my-stack) → 9
(pop 'my-stack) → 9
(stack-top 'my-stack) → 8
(push 'my-stack '🐸) ; any kind of lisp object in the stack
(stack-empty? 'my-stack) → #f
(stack->list 'my-stack) ; convert stack to list
→ (0 1 2 3 4 5 6 7 8 🐸)
... |
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 ... | #C | C | #include <stdio.h>
#include <stdlib.h>
#define valid(i, j) 0 <= i && i < m && 0 <= j && j < n && !s[i][j]
int main(int c, char **v)
{
int i, j, m = 0, n = 0;
/* default size: 5 */
if (c >= 2) m = atoi(v[1]);
if (c >= 3) n = atoi(v[2]);
if (m <= 0) m = 5;
if (n <= 0) n = m;
int **s = calloc(1, sizeof(int *)... |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #IS-BASIC | IS-BASIC | BLACK - The code of colour black.
BLUE - The code of colour blue.
CYAN - The code of colour cyan.
DATE$ - The current date in the standard format.
EXLINE - The number of the last statement that caused an exception.
EXTYPE - The error code of the last exception.
FREE - The amount of memory free and avaibl... |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #J | J | y: right argument
x: (optional) left argument
u: left argument to an adverb or conjunction
v: right argument to a conjunction
m: left noun argument to an adverb or conjunction (value error if verb provided)
n: right noun argument to a conjunction (value error if verb provided)
|
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Java | Java | import java.util.Arrays;
public class SpecialVariables {
public static void main(String[] args) {
//String-Array args contains the command line parameters passed to the program
//Note that the "Arrays.toString()"-call is just used for pretty-printing
System.out.println(Arrays.toString(... |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #BASIC | BASIC | ? A unary or dyadic operator giving 8 bit indirection.
! A unary or dyadic operator giving 32 bit indirection.
# As a prefix indicates a file channel number.
As a suffix indicates a 64-bit numeric variable or constant.
$ As a prefix indicates a 'fixed string' (string indirection).
As a su... |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #Batch_File | Batch File | ? A unary or dyadic operator giving 8 bit indirection.
! A unary or dyadic operator giving 32 bit indirection.
# As a prefix indicates a file channel number.
As a suffix indicates a 64-bit numeric variable or constant.
$ As a prefix indicates a 'fixed string' (string indirection).
As a su... |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a s... | #Clojure | Clojure | (defn sparkline [nums]
(let [sparks "▁▂▃▄▅▆▇█"
high (apply max nums)
low (apply min nums)
spread (- high low)
quantize #(Math/round (* 7.0 (/ (- % low) spread)))]
(apply str (map #(nth sparks (quantize %)) nums))))
(defn spark [line]
(if line
(let [nums (re... |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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
... | #Common_Lisp | Common Lisp | (defun strand-sort (l cmp)
(if l
(let* ((l (reverse l))
(o (list (car l))) n)
(loop for i in (cdr l) do
(push i (if (funcall cmp (car o) i) n o)))
(merge 'list o (strand-sort n cmp) #'<))))
(let ((r (loop repeat 15 collect (random 10))))
(print r)
(print (strand-sort r #'<))) |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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
... | #D | D | import std.stdio, std.container;
DList!T strandSort(T)(DList!T list) {
static DList!T merge(DList!T left, DList!T right) {
DList!T result;
while (!left.empty && !right.empty) {
if (left.front <= right.front) {
result.insertBack(left.front);
left.removeFr... |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is o... | #Go | Go | package main
import "fmt"
// Asymetry in the algorithm suggests different data structures for the
// map value types of the proposers and the recipients. Proposers go down
// their list of preferences in order, and do not need random access.
// Recipients on the other hand must compare their preferences to arbitra... |
http://rosettacode.org/wiki/Spelling_of_ordinal_numbers | Spelling of ordinal numbers | Ordinal numbers (as used in this Rosetta Code task), are numbers that describe the position of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6t... | #zkl | zkl | fcn nth(n,th=True){
var [const]
nmsth=T("","first","second","third","fourth","fifth","sixth","seventh","eighth","ninth"),
nms1=T("","one","two","three","four","five","six","seven","eight","nine"),
nms10=T("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","ninetee... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Raku | Raku | my @square-and-cube = map { .⁶ }, 1..Inf;
my @square-but-not-cube = (1..Inf).map({ .² }).grep({ $_ ∉ @square-and-cube[^@square-and-cube.first: * > $_, :k]});
put "First 30 positive integers that are a square but not a cube: \n", @square-but-not-cube[^30];
put "\nFirst 15 positive integers that are both a square ... |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #Plain_English | Plain English | Put "abcdef" into a string.
Slap a rider on the string. |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #PowerShell | PowerShell |
function Split-String ([string]$String)
{
[string]$c = $String.Substring(0,1)
[string]$splitString = $c
for ($i = 1; $i -lt $String.Length; $i++)
{
[string]$d = $String.Substring($i,1)
if ($d -ne $c)
{
$splitString += ", "
$c = $d
}
... |
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... | #Eiffel | Eiffel |
class
STACK_ON_ARRAY
create
make
feature -- Implementation
empty: BOOLEAN
do
Result := stack.is_empty
ensure
empty: Result = (stack.count = 0)
end
push (item: ANY)
do
stack.force (item, stack.count)
ensure
pushed: stack [stack.upper] = item
growth: stack.count = old stack.count + ... |
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 ... | #C.23 | C# | public int[,] Spiral(int n) {
int[,] result = new int[n, n];
int pos = 0;
int count = n;
int value = -n;
int sum = -1;
do {
value = -1 * value / n;
for (int i = 0; i < count; i++) {
sum += value;
result[sum / n, sum % n] = pos++;
}
valu... |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #JavaScript | JavaScript | var obj = {
foo: 1,
bar: function () { return this.foo; }
};
obj.bar(); // returns 1 |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #jq | jq | $ jq -n -M --arg x 1 '$x|type' # (*)
"string" |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #BBC_BASIC | BBC BASIC | ? A unary or dyadic operator giving 8 bit indirection.
! A unary or dyadic operator giving 32 bit indirection.
# As a prefix indicates a file channel number.
As a suffix indicates a 64-bit numeric variable or constant.
$ As a prefix indicates a 'fixed string' (string indirection).
As a su... |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #bc | bc | Trigraph Replacement letter
??( [
??) ]
??< {
??> }
??/ \
??= #
??' ^
??! |
??- ~
|
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a s... | #Common_Lisp | Common Lisp | (defun buckets (numbers)
(loop with min = (apply #'min numbers)
with max = (apply #'max numbers)
with width = (/ (- max min) 7)
for base from (- min (/ width 2)) by width
repeat 8
collect (cons base (+ base width))))
(defun bucket-for-number (number buckets)
(loop for i fro... |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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
... | #Elixir | Elixir | defmodule Sort do
def strand_sort(args), do: strand_sort(args, [])
defp strand_sort([], result), do: result
defp strand_sort(a, result) do
{_, sublist, b} = Enum.reduce(a, {hd(a),[],[]}, fn val,{v,l1,l2} ->
if v <= val, do: {val, [val | l1], l2},
el... |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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
... | #Euphoria | Euphoria | function merge(sequence left, sequence right)
sequence result
result = {}
while length(left) > 0 and length(right) > 0 do
if left[$] <= right[1] then
exit
elsif right[$] <= left[1] then
return result & right & left
elsif left[1] < right[1] then
res... |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is o... | #Groovy | Groovy | import static Man.*
import static Woman.*
Map<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {
Map<Woman,Man> engagedTo = new TreeMap()
List<Man> freeGuys = (Man.values()).clone()
while(freeGuys) {
Man thisGuy = freeGuys[0]
freeGuys... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #REXX | REXX | /*REXX pgm shows N ints>0 that are squares and not cubes, & which are squares and cubes.*/
numeric digits 20 /*ensure handling of larger numbers. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 30 ... |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #PureBasic | PureBasic | Procedure splitstring(s$)
Define *p.Character = @s$,
c_buf.c = *p\c
While *p\c
If *p\c = c_buf
Print(Chr(c_buf))
Else
Print(", ")
c_buf = *p\c
Continue
EndIf
*p + SizeOf(Character)
Wend
EndProcedure
If OpenConsole()
splitstring("gHHH5YY++///\")
Input(... |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #Python | Python | from itertools import groupby
def splitter(text):
return ', '.join(''.join(group) for key, group in groupby(text))
if __name__ == '__main__':
txt = 'gHHH5YY++///\\' # Note backslash is the Python escape char.
print(f'Input: {txt}\nSplit: {splitter(txt)}') |
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... | #Elena | Elena | public program()
{
var stack := new system'collections'Stack();
stack.push:2;
var isEmpty := stack.Length == 0;
var item := stack.peek(); // Peek without Popping.
item := stack.pop()
} |
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 ... | #C.2B.2B | C++ | #include <vector>
#include <memory> // for auto_ptr
#include <cmath> // for the ceil and log10 and floor functions
#include <iostream>
#include <iomanip> // for the setw function
using namespace std;
typedef vector< int > IntRow;
typedef vector< IntRow > IntTable;
auto_ptr< IntTable > getSpiralArray( int dimensio... |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Julia | Julia | join(sort(filter(sym -> let n=eval(sym); !(isa(n, Function) || isa(n, Type) || isa(n, Module)); end, names(Base))), ", ") |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Kotlin | Kotlin | // version 1.0.6
class President(val name: String) {
var age: Int = 0
set(value) {
if (value in 0..125) field = value // assigning to backing field here
else throw IllegalArgumentException("$name's age must be between 0 and 125")
}
}
fun main(args: Array<String>) {
... |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #Befunge | Befunge | Trigraph Replacement letter
??( [
??) ]
??< {
??> }
??/ \
??= #
??' ^
??! |
??- ~
|
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #Bracmat | Bracmat | Trigraph Replacement letter
??( [
??) ]
??< {
??> }
??/ \
??= #
??' ^
??! |
??- ~
|
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
... | #11l | 11l | F stoogesort(&l, i, j) -> N
I l[j] < l[i]
swap(&l[i], &l[j])
I j - i > 1
V t = (j - i + 1) I/ 3
stoogesort(&l, i, j - t)
stoogesort(&l, i + t, j)
stoogesort(&l, i, j - t)
F stooge(&l)
R stoogesort(&l, 0, l.len - 1)
V data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
st... |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
... | #Ada | Ada | with Ada.Text_IO;
with Ada.Command_Line; use Ada.Command_Line;
procedure SleepSort is
task type PrintTask (num : Integer);
task body PrintTask is begin
delay Duration (num) / 100.0;
Ada.Text_IO.Put(num'Img);
end PrintTask;
type TaskAcc is access PrintTask;
TaskList : array (1 .. Argument_Coun... |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
... | #11l | 11l | F shell_sort(&seq)
V inc = seq.len I/ 2
L inc != 0
L(el) seq[inc..]
V i = L.index + inc
L i >= inc & seq[i - inc] > el
seq[i] = seq[i - inc]
i -= inc
seq[i] = el
inc = I inc == 2 {1} E inc * 5 I/ 11
V data = [22, 7, 2, -5, 8, 4]
shell_sort(&data)
pr... |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a s... | #D | D | void main() {
import std.stdio, std.range, std.algorithm, std.conv,
std.string, std.regex;
"Numbers please separated by space/commas: ".write;
immutable numbers = readln
.strip
.splitter(r"[\s,]+".regex)
.array /**/
... |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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"
type link struct {
int
next *link
}
func linkInts(s []int) *link {
if len(s) == 0 {
return nil
}
return &link{s[0], linkInts(s[1:])}
}
func (l *link) String() string {
if l == nil {
return "nil"
}
r := fmt.Sprintf("[%d", l.int)
for l ... |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is o... | #Haskell | Haskell | {-# LANGUAGE TemplateHaskell #-}
import Lens.Micro
import Lens.Micro.TH
import Data.List (union, delete)
type Preferences a = (a, [a])
type Couple a = (a,a)
data State a = State { _freeGuys :: [a]
, _guys :: [Preferences a]
, _girls :: [Preferences a]}
makeLenses ''State |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Ring | Ring |
# Project : Square but not cube
limit = 30
num = 0
sq = 0
while num < limit
sq = sq + 1
sqpow = pow(sq,2)
flag = iscube(sqpow)
if flag = 0
num = num + 1
see sqpow + nl
else
see "" + sqpow + " is square and cube" + nl
ok
end
func iscube(cube)
for ... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Ruby | Ruby | #!/usr/bin/env ruby
class PowIt
:next
def initialize
@next = 1;
end
end
class SquareIt < PowIt
def next
result = @next ** 2
@next += 1
return result
end
end
class CubeIt < PowIt
def next
result = @next ** 3
@next += 1
return result
end
end
squares = []
hexponents = []
squit = SquareIt.n... |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #Quackery | Quackery | [ dup size 2 <
iff size done
behead swap
[] nested join
witheach
[ over != if
[ drop i^ 1+
conclude ] ] ] is $run ( $ --> n )
[ dup size 2 < if done
dup $run split
dup [] =
iff drop done
dip [ $ ", " join ]
recurse join ] is runs$ ( $ --> $ )
|
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #Racket | Racket | #lang racket
(define (split-strings-on-change s)
(map list->string (group-by values (string->list s) char=?)))
(displayln (string-join (split-strings-on-change #<<<
gHHH5YY++///\
<
)
", ")) |
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... | #Elisa | Elisa | component GenericStack ( Stack, Element );
type Stack;
Stack (MaxSize = integer) -> Stack;
Empty ( Stack ) -> boolean;
Full ( Stack ) -> boolean;
Push ( Stack, Element) -> nothing;
Pull ( Stack ) -> Element;
begin
Stack(MaxSize) =
Sta... |
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 ... | #Clojure | Clojure | (defn spiral [n]
(let [cyc (cycle [1 n -1 (- n)])]
(->> (range (dec n) 0 -1)
(mapcat #(repeat 2 %))
(cons n)
(mapcat #(repeat %2 %) cyc)
(reductions +)
(map vector (range 0 (* n n)))
(sort-by second)
(map first)))
(let [n 5]
(clojure.pprint/cl-for... |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Lasso | Lasso | {return #1 + ':'+#2}('a','b') // a:b |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Lingo | Lingo | put the constantNames |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #Brainf.2A.2A.2A | Brainf*** | Trigraph Replacement letter
??( [
??) ]
??< {
??> }
??/ \
??= #
??' ^
??! |
??- ~
|
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #C | C | Trigraph Replacement letter
??( [
??) ]
??< {
??> }
??/ \
??= #
??' ^
??! |
??- ~
|
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #C.2B.2B | C++ | Trigraph Replacement letter
??( [
??) ]
??< {
??> }
??/ \
??= #
??' ^
??! |
??- ~
|
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
... | #Action.21 | Action! | DEFINE MAX_COUNT="100"
INT ARRAY stack(MAX_COUNT)
INT stackSize
PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC InitStack()
stackSize=0
RETURN
BYTE FUNC IsEmpty()
IF stackSize=0 THEN
RETURN (1)... |
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
... | #Ada | Ada | with Ada.Text_IO;
procedure Stooge is
type Integer_Array is array (Positive range <>) of Integer;
procedure Swap (Left, Right : in out Integer) is
Temp : Integer := Left;
begin
Left := Right;
Right := Temp;
end Swap;
procedure Stooge_Sort (List : in out Integer_Array) is
T : Natu... |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
... | #APL | APL |
sleepsort←{{r}⎕TSYNC{r,←⊃⍵,⎕DL ⍵}&¨⍵,r←⍬}
|
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
... | #AutoHotkey | AutoHotkey | items := [1,5,4,9,3,4]
for i, v in SleepSort(items)
result .= v ", "
MsgBox, 262144, , % result := "[" Trim(result, ", ") "]"
return
SleepSort(items){
global Sorted := []
slp := 50
for i, v in items{
fn := Func("PushFn").Bind(v)
SetTimer, %fn%, % v * -slp
}
Sleep % Max(items*) ... |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
... | #360_Assembly | 360 Assembly | * Shell sort 24/06/2016
SHELLSRT CSECT
USING SHELLSRT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) " ... |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program shellSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesAR... |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a s... | #Delphi | Delphi |
program Sparkline_in_unicode;
{$APPTYPE CONSOLE}
//Translated from: https://www.arduino.cc/reference/en/language/functions/math/map/
function map(x, in_min, in_max, out_min, out_max: Double): Double;
begin
Result := ((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
end;
procedure Normalize(v... |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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
... | #Haskell | Haskell | -- Same merge as in Merge Sort
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x : xs) (y : ys)
| x <= y = x : merge xs (y : ys)
| otherwise = y : merge (x : xs) ys
strandSort :: (Ord a) => [a] -> [a]
strandSort [] = []
strandSort (x : xs) = merge strand (strandSort rest) where
(stra... |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is o... | #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
smd := IsStable(ShowEngaged(StableMatching(setup())))
IsStable(ShowEngaged(Swap(\smd,smd.women[1],smd.women[2])))
end
procedure index(L,x) #: return index of value or fail
return ( L[i := 1 to *L] === x, i)
end
procedure ShowEngaged(smd) ... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Rust | Rust | fn main() {
let mut s = 1;
let mut c = 1;
let mut cube = 1;
let mut n = 0;
while n < 30 {
let square = s * s;
while cube < square {
c += 1;
cube = c * c * c;
}
if cube == square {
println!("{} is a square and a cube.", square);
... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Scala | Scala | import spire.math.SafeLong
import spire.implicits._
def ncs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).flatMap(n => Iterator.iterate(n.pow(3).sqrt + 1)(_ + 1).map(i => i*i).takeWhile(_ < (n + 1).pow(3)))
def scs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).map(_.pow(3)).filter(n => n.sqr... |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #Raku | Raku | sub group-chars ($str) { $str.comb: / (.) $0* / }
# Testing:
for Q[gHHH5YY++///\], Q[fffn⃗n⃗n⃗»»» ℵℵ☄☄☃☃̂☃🤔🇺🇸🤦♂️👨👩👧👦] -> $string {
put 'Original: ', $string;
put ' Split: ', group-chars($string).join(', ');
} |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #REXX | REXX | /*REXX program splits a string based on change of character ───► a comma delimited list.*/
parse arg str /*obtain optional arguments from the CL*/
if str=='' then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/
p=left(str, 1) ... |
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... | #Elixir | Elixir | defmodule Stack do
def new, do: []
def empty?([]), do: true
def empty?(_), do: false
def pop([h|t]), do: {h,t}
def push(h,t), do: [h|t]
def top([h|_]), do: h
end |
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 ... | #CoffeeScript | CoffeeScript |
# Let's say you want to arrange the first N-squared natural numbers
# in a spiral, where you fill in the numbers clockwise, starting from
# the upper left corner. This code computes the values for each x/y
# coordinate of the square. (Of course, you could precompute the values
# iteratively, but what fun is that?)
... |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #LiveCode | LiveCode | put the constantNames |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Lua | Lua | for n in pairs(_G) do print(n) end |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #Clojure | Clojure | ? println(`1 + 1$\n= ${1 + 1}`)
1 + 1
= 2 |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact... | #E | E | ? println(`1 + 1$\n= ${1 + 1}`)
1 + 1
= 2 |
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
... | #ALGOL_68 | ALGOL 68 | # swaps the values of the two REF INTs #
PRIO =:= = 1;
OP =:= = ( REF INT a, b )VOID: ( INT t := a; a := b; b := t );
# returns the array of INTs sorted via the stooge sort algorithm #
PROC stooge sort = ( []INT array )[]INT:
BEGIN
PROC stooge sort segment = ( REF[]INT l, INT i, j )VOID:
... |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
... | #Bash | Bash |
function sleep_and_echo {
sleep "$1"
echo "$1"
}
for val in "$@"; do
sleep_and_echo "$val" &
done
wait
|
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"TIMERLIB"
DIM test%(9)
test%() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1
FOR i% = 0 TO DIM(test%(),1)
p% = EVAL("!^PROCtask" + STR$(i%))
tid% = FN_ontimer(100 + test%(i%), p%, 0)
NEXT
REPEAT
WAIT 0
UNTIL FALSE
DEF PROCtask0 : PRIN... |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
... | #Action.21 | Action! | PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC ShellSort(INT ARRAY a INT size)
INT stp,i,j,tmp,v
stp=size/2
WHILE stp>0
DO
FOR i=stp TO size-1
DO
tmp=a(i)
j=i
WHILE j... |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
... | #ActionScript | ActionScript | function shellSort(data:Array):Array
{
var inc:uint = data.length/2;
while(inc > 0)
{
for(var i:uint = inc; i< data.length; i++)
{
var tmp:Object = data[i];
for(var j:uint = i; j >= inc && data[j-inc] > tmp; j -=inc)
{
data[j] = data[j-inc];
}
data[j] = tmp;
}
inc = Math.round(inc/2.2);
}... |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a s... | #Elixir | Elixir | defmodule RC do
def sparkline(str) do
values = str |> String.split(~r/(,| )+/)
|> Enum.map(&elem(Float.parse(&1), 0))
{min, max} = Enum.min_max(values)
IO.puts Enum.map(values, &(round((&1 - min) / (max - min) * 7 + 0x2581)))
end
end |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a s... | #F.23 | F# | open System
open System.Globalization
open System.Text.RegularExpressions
let bars = Array.map Char.ToString ("▁▂▃▄▅▆▇█".ToCharArray())
while true do
printf "Numbers separated by anything: "
let numbers =
[for x in Regex.Matches(Console.ReadLine(), @"-?\d+(?:\.\d*)?") do yield x.Value]
|> Li... |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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
... | #J | J | strandSort=: (#~ merge $:^:(0<#)@(#~ -.)) (= >./\) |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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
... | #Java | Java | import java.util.Arrays;
import java.util.LinkedList;
public class Strand{
// note: the input list is destroyed
public static <E extends Comparable<? super E>>
LinkedList<E> strandSort(LinkedList<E> list){
if(list.size() <= 1) return list;
LinkedList<E> result = new LinkedList<E>();
while(list.size() > 0)... |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is o... | #J | J | Mraw=: ;: ;._2 noun define -. ':,'
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope,... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Sidef | Sidef | var square_and_cube = Enumerator({|f|
1..Inf -> each {|n| f(n**6) }
})
var square_but_not_cube = Enumerator({|f|
1..Inf -> lazy.map {|n| n**2 }.grep {|n| !n.is_power(3) }.each {|n| f(n) }
})
say "First 30 positive integers that are a square but not a cube:"
say square_but_not_cube.first(30).join(' ')
say ... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Swift | Swift | var s = 1, c = 1, cube = 1, n = 0
while n < 30 {
let square = s * s
while cube < square {
c += 1
cube = c * c * c
}
if cube == square {
print("\(square) is a square and a cube.")
} else {
print(square)
n += 1
}
s += 1
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.