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/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...
#C.23
C#
using System; using System.Collections.Generic;   namespace StableMarriage { class Person { private int _candidateIndex; public string Name { get; set; } public List<Person> Prefs { get; set; } public Person Fiance { get; set; }   public Person(string name) { ...
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...
#Phix
Phix
constant tests = {1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, 123, 00123.0, 1.23e2, 0b1111011, 0o173, 0x7B, 861/7} for i=1 to length(tests) do puts(1,ordinal(tests[i])&'\n') end 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.
#Nim
Nim
var count = 0 var n, c, c3 = 1   while count < 30: var sq = n * n while c3 < sq: inc c c3 = c * c * c if c3 == sq: echo sq, " is square and cube" else: echo sq inc count inc n
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.
#OCaml
OCaml
let rec fN n g phi = if phi < 31 then match compare (n*n) (g*g*g) with | -1 -> Printf.printf "%d\n" (n*n); fN (n+1) g (phi+1) | 0 -> Printf.printf "%d cube and square\n" (n*n); fN (n+1) (g+1) phi | 1 -> fN n (g+1) phi | _ -> assert false ;;   fN 1 1 1
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#VBA
VBA
Option Base 1 Private Function mean(s() As Variant) As Double mean = WorksheetFunction.Average(s) End Function Private Function standard_deviation(s() As Variant) As Double standard_deviation = WorksheetFunction.StDev(s) End Function Public Sub basic_statistics() Dim s() As Variant For e = 2 To 4 ...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Vlang
Vlang
import rand import math   fn main() { sample(100) sample(1000) sample(10000) }   fn sample(n int) { // generate data mut d := []f64{len: n} for i in 0.. d.len { d[i] = rand.f64() } // show mean, standard deviation mut sum, mut ssq := f64(0), f64(0) for s in d { s...
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...
#Lambdatalk
Lambdatalk
  {def mysplit {def mysplit.r {lambda {:w :i} {if {> :i {W.length :w}} then else {if {not {W.equal? {W.get :i :w} {W.get {+ :i 1} :w}}} then ____ else} {W.get {+ :i 1} :w}{mysplit.r :w {+ :i 1}}}}} {lambda {:w} {S.replace ____ by in {mysplit.r #:w 0}}}} -> mysplit   {mysplit 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...
#Lua
Lua
function charSplit (inStr) local outStr, nextChar = inStr:sub(1, 1) for pos = 2, #inStr do nextChar = inStr:sub(pos, pos) if nextChar ~= outStr:sub(#outStr, #outStr) then outStr = outStr .. ", " end outStr = outStr .. nextChar end return outStr end   print(cha...
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...
#Sidef
Sidef
# Declare a function to generate the Stern-Brocot sequence func stern_brocot { var list = [1, 1] { list.append(list[0]+list[1], list[1]) list.shift } }   # Show the first fifteen members of the sequence. say 15.of(stern_brocot()).join(' ')   # Show the (1-based) index of where the numbers 1-...
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...
#REXX
REXX
/*REXX program displays a "spinning rod" (AKA: trobbers or progress indicators). */   if 4=='f4'x then bs= "16"x /*EBCDIC? Then use this backspace chr.*/ else bs= "08"x /* ASCII? " " " " " */   signal on halt ...
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...
#Ring
Ring
load "stdlib.ring" rod = ["|", "/", "-", "\"] for n = 1 to len(rod) see rod[n] + nl sleep(0.25) system("cls") next
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...
#Crystal
Crystal
stack = [] of Int32 (1..10).each do |x| stack.push x end   10.times do puts stack.pop 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 ...
#Ada
Ada
-- Spiral Square with Ada.Text_Io; use Ada.Text_Io; with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;   procedure Spiral_Square is type Array_Type is array(Positive range <>, Positive range <>) of Natural;   function Spiral (N : Posit...
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.
#Clojure
Clojure
  (apply str (interpose " " (sort (filter #(.startsWith % "*") (map str (keys (ns-publics 'clojure.core)))))))  
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.
#Common_Lisp
Common Lisp
(defun special-variables () (flet ((special-var-p (s) (and (char= (aref s 0) #\*) (find-if-not (lambda (x) (char= x #\*)) s) (char= (aref s (1- (length s))) #\*)))) (let ((lst '())) (do-symbols (s (find-package 'cl)) (when (special-var-p (symbol-name s)) ...
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...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <string> #include <vector> using namespace std;   const char *men_data[][11] = { { "abe", "abi","eve","cath","ivy","jan","dee","fay","bea","hope","gay" }, { "bob", "cath","hope","abi","dee","eve","fay","bea","jan","ivy","gay" },...
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...
#Prolog
Prolog
test_ordinal(Number):- number_name(Number, ordinal, Name), writef('%w: %w\n', [Number, Name]).   main:- test_ordinal(1), test_ordinal(2), test_ordinal(3), test_ordinal(4), test_ordinal(5), test_ordinal(11), test_ordinal(15), test_ordinal(21), test_ordinal(42), test_ordina...
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.
#Pascal
Pascal
program SquareButNotCube; var sqN, sqDelta, SqNum,   cbN, cbDelta1, cbDelta2, CbNum,   CountSqNotCb, CountSqAndCb : NativeUint;   begin CountSqNotCb := 0; CountSqAndCb := 0; SqNum := 0; CbNum := 0; cbN := 0; sqN := 0; sqDelta := 1; cbDelta1 := 0; cbDelta2 := 1; repeat ...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Wren
Wren
import "random" for Random import "/math" for Nums   var r = Random.new() for (i in [100, 1000, 10000]) { var a = List.filled(i, 0) for (j in 0...i) a[j] = r.float() System.print("For %(i) random numbers:") System.print(" mean = %(Nums.mean(a))") System.print(" std/dev = %(Nums.popStdDev(a))") ...
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...
#Ksh
Ksh
  #!/bin/ksh   # Split a character string based on change of character   # # Variables: # str='gHHH5YY++///\' delim=', '   # # Functions: # # # Function _splitonchg(str, delim) - return str split by delim at char change # function _splitonchg { typeset _str ; _str="$1" typeset _delim ; _delim="$2" typeset _i _splits...
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...
#M2000_Interpreter
M2000 Interpreter
  Module PrintParts(splitthis$) { Def string m$, p$ Def long c Stack New { if len(splitthis$)=0 then exit For i=1 to len(splitthis$) p$=mid$(splitthis$,i,1) if m$<>p$ then { if c>0 then data string$(m$, c) ...
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...
#Snobol
Snobol
* GCD function DEFINE('GCD(A,B)')  :(GCD_END) GCD GCD = A EQ(B,0)  :S(RETURN) A = B B = REMDR(GCD,B)  :(GCD) GCD_END   * Find first occurrence of element in array DEFINE('IDX(ARR,ELM)') ...
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...
#Ruby
Ruby
def spinning_rod begin printf("\033[?25l") # Hide cursor %w[| / - \\].cycle do |rod| print rod sleep 0.25 print "\b" end ensure printf("\033[?25h") # Restore cursor end end   puts "Ctrl-c to stop." spinning_rod  
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...
#Rust
Rust
fn main() { let characters = ['|', '/', '-', '\\']; let mut current = 0;   println!("{}[2J", 27 as char); // Clear screen.   loop { println!("{}[;H{}", 27 as char, characters[current]); // Move cursor to 1,1 and output the next character. current += 1; // Advance current character. ...
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...
#D
D
import std.array;   class Stack(T) { private T[] items;   @property bool empty() { return items.empty(); }   void push(T top) { items ~= top; }   T pop() { if (this.empty) throw new Exception("Empty Stack."); auto top = items.back; items.popBack(); return top;...
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 ...
#ALGOL_68
ALGOL 68
INT empty=0;   PROC spiral = (INT n)[,]INT: ( INT dx:=1, dy:=0; # Starting increments # INT x:=0, y:=0; # Starting location # [0:n-1,0:n-1]INT my array; FOR y FROM LWB my array TO UPB my array DO FOR x FROM LWB my array TO UPB my array DO my array[x,y]:=empty ...
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.
#D
D
func Integer.Double() { this + this } print(8.Double())
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.
#DWScript
DWScript
func Integer.Double() { this + this } print(8.Double())
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...
#Ceylon
Ceylon
abstract class Single(name) of Gal | Guy {   shared String name; shared late Single[] preferences;   shared variable Single? fiance = null; shared Boolean free => fiance is Null;   shared variable Integer currentProposalIndex = 0;   "Does this single prefer this other single over their fiance?" ...
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...
#Python
Python
irregularOrdinals = { "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth", "nine": "ninth", "twelve": "twelfth", }   def num2ordinal(n): conversion = int(float(n)) num = spell_integer(conversion) hyphen = num.rsplit("-", 1) num = num.rsplit(" ", 1) ...
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.
#Perl
Perl
while ($cnt < 30) { $n++; $h{$n**2}++; $h{$n**3}--; $cnt++ if $h{$n**2} > 0; }   print "First 30 positive integers that are a square but not a cube:\n"; print "$_ " for sort { $a <=> $b } grep { $h{$_} == 1 } keys %h;   print "\n\nFirst 3 positive integers that are both a square and a cube:\n"; print "$...
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#zkl
zkl
fcn mean(ns) { ns.sum(0.0)/ns.len() } fcn stdDev(ns){ m:=mean(ns); (ns.reduce('wrap(p,n){ x:=(n-m); p+x*x },0.0)/ns.len()).sqrt() }
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...
#Maple
Maple
splitChange := proc(str::string) local start,i,len; start := 1; len := StringTools:-Length(str); for i from 2 to len do if str[i] <> str[start] then printf("%s, ", str[start..i-1]); start := i: end if; end do; printf("%s", str[start..len]); end proc; splitChange("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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringJoin@@Riffle[StringCases["gHHH5YY++///\\", p : (x_) .. -> p], ", "]
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...
#Swift
Swift
struct SternBrocot: Sequence, IteratorProtocol { private var seq = [1, 1]   mutating func next() -> Int? { seq += [seq[0] + seq[1], seq[1]]   return seq.removeFirst() } }   func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T { guard a != 0 else { return b }   return a < b ? gcd(b % a, a) : gcd(a % b...
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...
#Scala
Scala
object SpinningRod extends App { val start = System.currentTimeMillis   def a = "|/-\\"   print("\033[2J") // hide the cursor   while (System.currentTimeMillis - start < 20000) { for (i <- 0 until 4) { print("\033[2J\033[0;0H") // clear terminal, place cursor at top left corner for (j <- 0 until...
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...
#Delphi
Delphi
program Stack;   {$APPTYPE CONSOLE}   uses Generics.Collections;   var lStack: TStack<Integer>; begin lStack := TStack<Integer>.Create; try lStack.Push(1); lStack.Push(2); lStack.Push(3); Assert(lStack.Peek = 3); // 3 should be at the top of the stack   Writeln(lStack.Pop); // 3 Writeln(lS...
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 ...
#AppleScript
AppleScript
---------------------- SPIRAL MATRIX ---------------------   -- spiral :: Int -> [[Int]] on spiral(n) script go on |λ|(rows, cols, start) if 0 < rows then {enumFromTo(start, start + pred(cols))} & ¬ map(my |reverse|, ¬ transpose(|λ|(col...
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.
#Dyalect
Dyalect
func Integer.Double() { this + this } print(8.Double())
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
set setglobal local get getlocal return recurse drop dup swap rot over [] {} pop-from push-to push-through has get-from set-to raise reraise call for pass
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...
#11l
11l
with Ada.Text_IO; use Ada.Text_IO;   procedure Test is begin Put ("Quote """ & ''' & """" & Character'Val (10)); end Test;
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...
#APL
APL
sparkln←{'▁▂▃▄▅▆▇█'[⌊0.5+7×⍵÷⌈/⍵]}
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 ...
#11l
11l
F merge_list(&a, &b) [Int] out L !a.empty & !b.empty I a[0] < b[0] out.append(a.pop(0)) E out.append(b.pop(0)) out [+]= a out [+]= b R out   F strand(&a) V i = 0 V s = [a.pop(0)] L i < a.len I a[i] > s.last s.append(a.pop(i)) E i++ R...
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...
#CoffeeScript
CoffeeScript
class Person constructor: (@name, @preferences) -> @mate = null @best_mate_rank = 0 @rank = {} for preference, i in @preferences @rank[preference] = i   preferred_mate_name: => @preferences[@best_mate_rank]   reject: => @best_mate_rank += 1   set_mate: (mate) => @mate = mate   ...
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...
#Raku
Raku
use Lingua::EN::Numbers;   # The task +$_ ?? printf( "Type: \%-14s %16s : %s\n", .^name, $_, .&ordinal ) !! say "\n$_:" for   # Testing 'Required tests', 1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,   'Optional tests - different forms of 123', 'Numerics', 123, 00123.0, 1.23e2, 123+0i,   'Allomorphs', ...
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.
#Phix
Phix
integer square = 1, squared = 1*1, cube = 1, cubed = 1*1*1, count = 0 while count<30 do squared = square*square while squared>cubed do cube += 1; cubed = cube*cube*cube end while if squared=cubed then printf(1,"%d: %d == %d^3\n",{square,squared,cube}) else count += ...
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...
#MiniScript
MiniScript
s = "gHHH5YY++///\" output = [] lastLetter = s[0] for letter in s if letter != lastLetter then output.push ", " output.push letter lastLetter = letter end for print output.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...
#Modula-2
Modula-2
MODULE CharacterChange; FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;   PROCEDURE Split(str : ARRAY OF CHAR); VAR i : CARDINAL; c : CHAR; BEGIN FOR i:=0 TO HIGH(str) DO IF i=0 THEN c := str[i] ELSIF str[i]#c THEN c := str[i]; WriteLn; EN...
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...
#Tcl
Tcl
  #!/usr/bin/env tclsh #   package require generator ;# from tcllib   namespace eval stern-brocot { proc generate {{count 100}} { set seq {1 1} set n 0 while {[llength $seq] < $count} { lassign [lrange $seq $n $n+1] a b lappend seq [expr {$a + $b}] $b in...
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...
#ScratchScript
ScratchScript
print "|" delay 0.25 clear print "/" delay 0.25 clear print "-" delay 0.25 clear print "\" delay 0.25
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...
#SimpleCode
SimpleCode
dtxt | wait 0.25 ctxt reset dtxt / wait 0.25 ctxt reset dtxt - wait 0.25 ctxt reset dtxt \ wait 0.25
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...
#DWScript
DWScript
  var stack: array of Integer;   stack.Push(1); stack.Push(2); stack.Push(3);   PrintLn(stack.Pop); // 3 PrintLn(stack.Pop); // 2 PrintLn(stack.Pop); // 1   Assert(stack.Length = 0); // assert empty  
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 ...
#Arturo
Arturo
spiralMatrix: function [n][ m: new array.of: @[n,n] null   [dx, dy, x, y]: [1, 0, 0, 0]   loop 0..dec n^2 'i [ m\[y]\[x]: i   [nx,ny]: @[x+dx, y+dy]   if? and? [and? [in? nx 0..n-1][in? ny 0..n-1]][ null? m\[ny]\[nx] ][ [x,y]: @[nx, ny] ] ...
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.
#Erlang
Erlang
  -module( special_variables ).   -export( [task/0] ).   task() -> ok.  
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.
#Forth
Forth
Name Type Description --------------------------------------------- TIB integer Terminal Input Buffer address U0 integer current user area address >IN integer holds offset into TIB, used for parsing BASE integer holds number conversion radix STATE integer holds compil...
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...
#360_Assembly
360 Assembly
with Ada.Text_IO; use Ada.Text_IO;   procedure Test is begin Put ("Quote """ & ''' & """" & Character'Val (10)); end Test;
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...
#6502_Assembly
6502 Assembly
with Ada.Text_IO; use Ada.Text_IO;   procedure Test is begin Put ("Quote """ & ''' & """" & Character'Val (10)); end Test;
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...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions   on run unlines(map(¬ compose(compose(unlines, sparkLine), readFloats), ¬ {"0, 1, 19, 20", "0, 999, 4000, 4999, 7000, 7999", ¬ "0, 1000, 4000, 5000, 7000, 8000", ¬ "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1...
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 ...
#AutoHotkey
AutoHotkey
string = ( -2 0 -2 5 5 3 -1 -3 5 5 0 2 -4 4 2 ) string2 := string Loop { loop, parse, string, %A_space% { list := 1 = A_index ? A_loopfield : list StringSplit, k, list, %A_space%   if ( k%k0% <= A_loopfield ) && ( l != "" ) && ( A_index != 1 ) list := list . " " . A_loopfield   if ( k%k0% > A_loopfield ) ...
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...
#ColdFusion
ColdFusion
  PERSON.CFC   component displayName="Person" accessors="true" { property name="Name" type="string"; property name="MrOrMrsGoodEnough" type="Person"; property name="UnrealisticExpectations" type="array"; property name="PersonalHistory" type="array";   public Person function init( required String nam...
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...
#REXX
REXX
/*REXX programs spells out ordinal numbers (in English, using the American system). */ numeric digits 3000 /*just in case the user uses gihugic #s*/ parse arg n /*obtain optional arguments from the CL*/   if n='' | n="," then n= 1 2 3 4 5 11 6...
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.
#PILOT
PILOT
C :sqr=1 C :cbr=1 C :sq=1 C :cb=1 C :n=0   *square U (sq>cb):*cube C (sq<cb):n=n+1 T (sq<cb):#sq C :sqr=sqr+1 C :sq=sqr*#sqr J (n<30):*square E :   *cube C :cbr=cbr+1 C :cb=(cbr*#cbr)*#cbr J (sq>cb):*cube E :
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.
#PL.2FI
PL/I
squareNotCube: procedure options(main);   square: procedure(n) returns(fixed); declare n fixed; return(n * n); end square;   cube: procedure(n) returns(fixed); declare n fixed; return(n * n * n); end cube;   declare (ci, si, seen) fixed;   ci = 1; do si = 1 re...
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...
#Nim
Nim
proc splitOnDiff(str: string): string = result = ""   if str.len < 1: return result   var prevChar: char = str[0]   for idx in 0 ..< str.len: if str[idx] != prevChar: result &= ", " prevChar = str[idx]   result &= str[idx]   assert splitOnDiff("""X""") == """X""" assert splitOnDiff("""XX""")...
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...
#ooRexx
ooRexx
Parse Arg str . /*obtain optional arguments from the CL*/ If str=='' Then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/ i=1 ol='' Do Forever j=verify(str,substr(str,i,1),'N',i,99) /* find first character that's different */ If j=0 Then Do ...
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...
#VBScript
VBScript
sb = Array(1,1) i = 1 'considered j = 2 'precedent n = 0 'loop counter Do ReDim Preserve sb(UBound(sb) + 1) sb(UBound(sb)) = sb(UBound(sb) - i) + sb(UBound(sb) - j) ReDim Preserve sb(UBound(sb) + 1) sb(UBound(sb)) = sb(UBound(sb) - j) i = i + 1 j = j + 1 n = n + 1 Loop Until n = 2000   WScript.Echo "First 15: " ...
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...
#Wee_Basic
Wee Basic
let loop=1 sub delay: for i=1 to 10000 next cls 1 return while loop=1 print 1 "l" gosub delay: print 1 "/" gosub delay: print 1 "-" gosub delay: print 1 "\" gosub delay: wend end
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...
#Wren
Wren
import "io" for Stdout import "timer" for Timer   var ESC = "\u001b"   var a = "|/-\\" System.write("%(ESC)[?25l") // hide the cursor var start = System.clock var asleep = 0 while (true) { for (i in 0..3) { System.write("%(ESC)[2J") // clear terminal System.write("%(ESC)[0;0H") // place...
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...
#Dyalect
Dyalect
type Stack() { var xs = [] }   func Stack.IsEmpty() => this!xs.Length() == 0   func Stack.Peek() => this!xs[this!xs.Length() - 1]   func Stack.Pop() { var e = this!xs[this!xs.Length() - 1] this!xs.RemoveAt(this!xs.Length() - 1) return e }   func Stack.Push(item) => this!xs.Add(item)   var stack = Stack(...
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 ...
#AutoHotkey
AutoHotkey
n := 5, dx := x := y := v := 1, dy := 0   Loop % n*n { a_%x%_%y% := v++ nx := x+dx, ny := y+dy If (1 > nx || nx > n || 1 > ny || ny > n || a_%nx%_%ny%) t := dx, dx := -dy, dy := t x := x+dx, y := y+dy }   Loop %n% { ; generate printout y := A_Index ; for each ro...
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.
#Fortran
Fortran
INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST, !Here we go. Does the file exist? 1 ERR = 666,IOSTAT = IOSTAT) !Hopefully, named in good style, etc. IF (EXIST) THEN !So, does the named file already exist? ...etc.
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.
#Go
Go
  # &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...
#ActionScript
ActionScript
with Ada.Text_IO; use Ada.Text_IO;   procedure Test is begin Put ("Quote """ & ''' & """" & Character'Val (10)); end Test;
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...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test is begin Put ("Quote """ & ''' & """" & Character'Val (10)); end Test;
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...
#Arturo
Arturo
bar: "▁▂▃▄▅▆▇█" barcount: to :floating dec size bar   while ø [ line: input "Numbers separated by spaces: " numbers: to [:floating] split.words line mn: min numbers mx: max numbers extent: mx-mn sparkLine: new "" loop numbers 'n [ i: to :integer barcount*(n-mn)//extent 'spark...
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...
#AutoHotkey
AutoHotkey
SetFormat, FloatFast, 0.1 strings := ["1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" , "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"]   Loop, % strings.MaxIndex() { SL := Sparklines(strings[A_Index]) MsgBox, % "Min: " SL["Min"] ", Max: " SL["Max"] ", Range: " SL["Rng"] "`n" SL["Chars"] }   Sparklines(s) { s := RegexRepl...
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 ...
#C
C
#include <stdio.h>   typedef struct node_t *node, node_t; struct node_t { int v; node next; }; typedef struct { node head, tail; } slist;   void push(slist *l, node e) { if (!l->head) l->head = e; if (l->tail) l->tail->next = e; l->tail = e; }   node removehead(slist *l) { node e = l->head; if (e) { l->head = e...
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...
#D
D
import std.stdio, std.array, std.algorithm, std.string;     string[string] matchmaker(string[][string] guyPrefers, string[][string] girlPrefers) /*@safe*/ { string[string] engagedTo; string[] freeGuys = guyPrefers.keys;   while (freeGuys.length) { const string thisGuy = fre...
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...
#Rust
Rust
struct NumberNames { cardinal: &'static str, ordinal: &'static str, }   impl NumberNames { fn get_name(&self, ordinal: bool) -> &'static str { if ordinal { return self.ordinal; } self.cardinal } }   const SMALL_NAMES: [NumberNames; 20] = [ NumberNames { ca...
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...
#Sidef
Sidef
var lingua_en = frequire('Lingua::EN::Numbers') var tests = [1,2,3,4,5,11,65,100,101,272,23456,8007006005004003]   tests.each {|n| printf("%16s : %s\n", n, lingua_en.num2en_ordinal(n)) }
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.
#PL.2FM
PL/M
100H: /* CP/M OUTPUT */ BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;   PRINT$NUMBER: PROCEDURE (N); DECLARE S (7) BYTE INITIAL ('..... $'); DECLARE (N, P) ADDRESS, C BASED P BYTE; P = .S(5); DIGIT: P = P-1; C = N MOD 10 + '0'; N = N/10; IF N > 0 THEN GO...
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.
#PureBasic
PureBasic
OpenConsole() lv=1 Repeat s+1 : s2=s*s : Flg=#True For i=lv To s If s2=i*i*i tx3$+Space(Len(tx2$)-Len(tx3$))+Str(s2) tx2$+Space(Len(Str(s2))+1) Flg=#False : lv=i : c-1 : Break EndIf Next If Flg : tx2$+Str(s2)+" " : EndIf c+1 Until c>=30 PrintN("s²  : "+tx2$) : PrintN("s²&s³: ...
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...
#Pascal
Pascal
program SplitChars; {$IFDEF FPC} {$MODE DELPHI}{$COPERATORS ON} {$ENDIF} const TestString = 'gHHH5YY++///\';   function SplitAtChars(const S: String):String; var i : integer; lastChar:Char; begin result := ''; IF length(s) > 0 then begin LastChar := s[1]; result := LastChar; For i := 2 to len...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.Collections.Generic Imports System.Linq   Module Module1 Dim l As List(Of Integer) = {1, 1}.ToList()   Function gcd(ByVal a As Integer, ByVal b As Integer) As Integer Return If(a > 0, If(a < b, gcd(b Mod a, a), gcd(a Mod b, b)), b) End Function   Sub Main(ByVal args...
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...
#XPL0
XPL0
char I, Rod; [Rod:= "|/-\ "; loop for I:= 0 to 3 do [ChOut(0, Rod(I)); DelayUS(250_000); ChOut(0, $08\BS\); if KeyHit then quit; ]; ]
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...
#zkl
zkl
foreach n,rod in ((1).MAX, T("|", "/", "-", "\\")){ print("  %s\r".fmt(rod));   Atomic.sleep(0.25); }
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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :stack [] #lists used to be stacks in DV   push-to stack 1 push-to stack 2 push-to stack 3   !. pop-from stack #prints 3 !. pop-from stack #prints 2 !. pop-from stack #prints 1   if stack: #empty lists are falsy error #this stack should be empty now!
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 ...
#AWK
AWK
  # syntax: GAWK -f SPIRAL_MATRIX.AWK [-v offset={0|1}] [size] # converted from BBC BASIC BEGIN { # offset: "0" prints 0 to size^2-1 while "1" prints 1 to size^2 offset = (offset == "") ? 0 : offset size = (ARGV[1] == "") ? 5 : ARGV[1] if (offset !~ /^[01]$/) { exit(1) } if (size !~ /^[0-9]+$/) { exit(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.
#Haskell
Haskell
  # &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...
#ALGOL_68
ALGOL 68
printf(($"flip:"g"!"l$,flip)); printf(($"flop:"g"!"l$,flop)); printf(($"blank:"g"!"l$,blank)); printf(($"error char:"g"!"l$,error char)); printf(($"null character:"g"!"l$,null character))
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...
#ALGOL_W
ALGOL W
? 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
C
  #include<string.h> #include<stdlib.h> #include<locale.h> #include<stdio.h> #include<wchar.h> #include<math.h>   int main(int argC,char* argV[]) { double* arr,min,max; char* str; int i,len; if(argC == 1) printf("Usage : %s <data points separated by spaces or commas>",argV[0]); else{ arr = (double*)malloc((arg...
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 ...
#C.2B.2B
C++
#include <list>   template <typename T> std::list<T> strandSort(std::list<T> lst) { if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.e...
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 ...
#Clojure
Clojure
(ns rosettacode.strand-sort)   (defn merge-join "Produces a globally sorted seq from two sorted seqables" [[a & la :as all] [b & lb :as bll]] (cond (nil? a) bll (nil? b) all (< a b) (cons a (lazy-seq (merge-join la bll))) true (cons b (lazy-seq (merge-join all lb)))))   (defn unbraid ...
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...
#EchoLisp
EchoLisp
  (lib 'hash) ;; input data (define M-RANKS '(( 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 gay) ( fred bea abi dee gay e...
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...
#Swift
Swift
fileprivate class NumberNames { let cardinal: String let ordinal: String   init(cardinal: String, ordinal: String) { self.cardinal = cardinal self.ordinal = ordinal }   func getName(_ ordinal: Bool) -> String { return ordinal ? self.ordinal : self.cardinal }   class f...
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...
#VBA
VBA
Private Function ordinal(s As String) As String Dim irregs As New Collection irregs.Add "first", "one" irregs.Add "second", "two" irregs.Add "third", "three" irregs.Add "fifth", "five" irregs.Add "eighth", "eight" irregs.Add "ninth", "nine" irregs.Add "twelfth", "twelve" Dim i As Int...
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.
#Python
Python
# nonCubeSquares :: Int -> [(Int, Bool)] def nonCubeSquares(n): upto = enumFromTo(1) ns = upto(n) setCubes = set(x ** 3 for x in ns) ms = upto(n + len(set(x * x for x in ns).intersection( setCubes ))) return list(tuple([x * x, x in setCubes]) for x in ms)     # squareListing :: [(Int, Bo...
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...
#Perl
Perl
use strict; use warnings; use feature 'say'; use utf8; binmode(STDOUT, ':utf8');   for my $string (q[gHHH5YY++///\\], q[fffn⃗n⃗n⃗»»» ℵℵ☄☄☃☃̂☃🤔🇺🇸🤦♂️👨‍👩‍👧‍👦]) { my @S; my $last = ''; while ($string =~ /(\X)/g) { if ($last eq $1) { $S[-1] .= $1 } else { push @S, $1 } $last = $1; } ...
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...
#Phix
Phix
function split_on_change(string s) string res = "" if length(s) then integer prev = s[1] for i=1 to length(s) do integer ch = s[i] if ch!=prev then res &= ", " prev = ch end if res &= ch end for end if ...