task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/Matrix-exponentiation_operator
Matrix-exponentiation operator
Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
#Chapel
Chapel
proc **(a, e) { // create result matrix of same dimensions var r:[a.domain] a.eltType; // and initialize to identity matrix forall ij in r.domain do r(ij) = if ij(1) == ij(2) then 1 else 0;   for 1..e do r *= a;   return r; }
Give a code snippet in #Chapel Most programming languages have a built-in implementation of exponentiation for integers and reals only. Task Demonstrate how to implement matrix exponentiation as an operator.
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Ursala
Ursala
a = `x
Give a code snippet in #Ursala Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters ...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#COBOL
COBOL
>>SOURCE FORMAT FREE *> This code is dedicated to the public domain *> This is GNUCobol 2.0 identification division. program-id. twentyfoursolve. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select count-file assign to count-fil...
Give a code snippet in #COBOL task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#6502_Assembly
6502 Assembly
ArithmeticMean: PHA TYA PHA ;push accumulator and Y register onto stack     LDA #0 STA Temp STA Temp+1 ;temporary 16-bit storage for total   LDY NumberInts BEQ Done ;if NumberInts = 0 then return an average of zero   DEY ;start with NumberInts-1 AddLoop: LDA (ArrayPtr),Y CLC ADC Temp ...
Give a code snippet in #6502_Assembly Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#Lambdatalk
Lambdatalk
  {def xor {lambda {:a :b} {or {and :a {not :b}} {and :b {not :a}}}}} -> xor   {def halfAdder {lambda {:a :b} {cons {and :a :b} {xor :a :b}}}} -> halfAdder   {def fullAdder {lambda {:a :b :c} {let { {:b :b} {:ha1 {halfAdder :c :a}} } {let { {:ha1 :ha1} {:ha2 {halfAdder {cdr :ha1} :b}}...
Give a code snippet in #Lambdatalk Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#Nanoquery
Nanoquery
def analyze(s) s = str(s) println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"   if len(s) < 2 println "\tAll characters in the string are unique." return end   seen = list() for i in range(0, len(s) - 2) ...
Give a code snippet in #Nanoquery Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Ruby
Ruby
txt = "WELLDONEISBETTERTHANWELLSAID" @left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ".chars @right = "PTLNBQDEOYSFAVZKGJRIHWXUMC".chars   def encrypt(char) coded_char = @left[@right.index(char)]   @left.rotate!(@left.index(coded_char)) part = @left.slice!(1,13).rotate @left.insert(1, *part)   @right.rotate!(@right.in...
Give a code snippet in #Ruby Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there ...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#Perl
Perl
#!/usr/bin/perl   use strict; use warnings;   my $gap = qr/.{3}/s;   find( <<terminator ); -AB- CDEF -GH- terminator   sub find { my $p = shift; $p =~ /(\d)$gap.{0,2}(\d)(??{abs $1 - $2 <= 1 ? '' : '(*F)'})/ || $p =~ /^.*\n.*(\d)(\d)(??{abs $1 - $2 <= 1 ? '' : '(*F)'})/ and return; if( $p =~ /[A-H]/ ) {...
Give a code snippet in #Perl You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ ...
christopher/rosetta-code
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#PicoLisp
PicoLisp
- Global variables start with an asterisk '*' - Global constants may be written all-uppercase - Functions and other global symbols start with a lower case letter - Locally bound symbols start with an upper case letter - Local functions start with an underscore '_' - Classes start with a plus-sign '+', where the first l...
Give a code snippet in #PicoLisp Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefix...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#11l
11l
F hailstone(=n) V seq = [n] L n > 1 n = I n % 2 != 0 {3 * n + 1} E n I/ 2 seq.append(n) R seq   V h = hailstone(27) assert(h.len == 112 & h[0.<4] == [27, 82, 41, 124] & h[(len)-4 ..] == [8, 4, 2, 1])   V m = max((1..99999).map(i -> (hailstone(i).len, i))) print(‘Maximum length #. was found for hail...
Give a code snippet in #11l The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#Elixir
Elixir
defmodule RC do use Bitwise @bit_size 4   def four_bit_adder(a, b) do # returns pair {sum, carry} a_bits = binary_string_to_bits(a) b_bits = binary_string_to_bits(b) Enum.zip(a_bits, b_bits) |> List.foldr({[], 0}, fn {a_bit, b_bit}, {acc, carry} -> {s, c} = full_adder(a_bit, b_b...
Give a code snippet in #Elixir Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#Factor
Factor
USING: combinators formatting io kernel math math.combinatorics prettyprint sequences ; IN: rosetta-code.derangements   : !n ( n -- m ) { { 0 [ 1 ] } { 1 [ 0 ] } [ [ 1 - !n ] [ 2 - !n + ] [ 1 - * ] tri ] } case ;   : derangements ( n -- seq ) <iota> dup [ [ = ] 2map [ f = ] all? ] wi...
Give a code snippet in #Factor A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of...
christopher/rosetta-code
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Juggler_sequence use warnings; use Math::BigInt lib => 'GMP';   print " n l(n) i(n) h(n) or d(n)\n"; print " ------- ---- ---- ------------\n"; for my $i ( 20 .. 39, 113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909, 226491...
Give a code snippet in #Perl Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class PerfectShuffle { static void Main() { foreach (int input in new [] {8, 24, 52, 100, 1020, 1024, 10000}) { int[] numbers = Enumerable.Range(1, input).ToArray(); Console.WriteLine($"{input} car...
Give a code snippet in #C.23 A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.2B.2B
C++
#include <iostream> #include <string>   int main( ) { std::string greeting( "Hello" ) ; greeting.append( " , world!" ) ; std::cout << greeting << std::endl ; return 0 ; }
Give a code snippet in #C.2B.2B Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#BQN
BQN
ExClass ← { 𝕊 value: # Constructor portion priv ← value priv2 ⇐ 0 ChangePriv ⇐ { priv ↩ 𝕩 } DispPriv ⇐ {𝕊: •Show priv‿priv2 }   }   obj ← ExClass 5 obj.DispPriv@ obj.ChangePriv 6 obj.DispPriv@
Give a code snippet in #BQN In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#PicoLisp
PicoLisp
(maxi '((L) (apply + L)) (mapcon '((L) (maplist reverse (reverse L))) (-1 -2 3 5 6 -2 -1 4 -4 2 -1) ) )
Give a code snippet in #PicoLisp Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements a...
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#Maple
Maple
isStrong := proc(n::posint) local holder; holder := false; if isprime(n) and 1/2*prevprime(n) + 1/2*nextprime(n) < n then holder := true; end if; return holder; end proc:   isWeak := proc(n::posint) local holder; holder := false; if isprime(n) and n < 1/2*prevprime(n) + 1/2*nextprime(n) then holder := tr...
Give a code snippet in #Maple Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Delphi
Delphi
  program JsonTest;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, Json;   type TJsonObjectHelper = class helper for TJsonObject public class function Deserialize(data: string): TJsonObject; static; function Serialize: string; end;   { TJsonObjectHelper }   class function TJsonObjectHelper....
Give a code snippet in #Delphi Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace ConvertSecondsToCompoundDuration { class Program { static void Main( string[] args ) { foreach ( string arg in args ) { int duration ; bool isValid = int.TryParse( arg , out duration ) ;   if (...
Give a code snippet in #C.23 Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Ada
Ada
with Gtk.Window; use Gtk.Window; with Gtk.Enums; with Gtk.Handlers; with Gtk.Main; with Gdk; with Gdk.Event; with Glib; use Glib; with Cairo; use Cairo; with Gdk.Cairo; pragma Elaborate_All (Gtk.Handlers);   procedure Greyscale is   Win  : Gtk_Window; Width  : constant := 640; Height : const...
Give a code snippet in #Ada The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we hav...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#ALGOL_68
ALGOL 68
BEGIN PROC digit sum = (INT i) INT : BEGIN INT res := i %* 10, h := i; WHILE (h %:= 10) > 0 DO res +:= h %* 10 OD; res END; INT found := 0; FOR i WHILE found < 20 DO (i %* digit sum (i) = 0 | found +:= 1; printf (($g(0)", "$, i)) ) OD; FOR i FROM 1001 DO (i %* digit sum ...
Give a code snippet in #ALGOL_68 The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Perl
Perl
use List::Util qw(sum reduce);   sub find_loop { my($n) = @_; my($r,@seen); while () { $seen[$r] = $seen[($r = int(1+rand $n))] ? return sum @seen : 1 } }   print " N empiric theoric (error)\n"; print "=== ========= ============ =========\n";   my $MAX = 20; my $TRIALS = 1000;   for my $n...
Give a code snippet in #Perl Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number t...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#JavaScript
JavaScript
function lastSundayOfEachMonths(year) { var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var sundays = []; var date, month; if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) { lastDay[2] = 29; } for (date = new Date(), month = 0; month < 12; month += 1) { date.setFullYear(year, mont...
Give a code snippet in #JavaScript Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-2...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Java
Java
public class CompoundDuration {   public static void main(String[] args) { compound(7259); compound(86400); compound(6000_000); }   private static void compound(long seconds) { StringBuilder sb = new StringBuilder();   seconds = addUnit(sb, seconds, 604800, " wk, "); ...
Give a code snippet in #Java Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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 ...
#Scala
Scala
$ include "seed7_05.s7i";   const proc: genSort3 (in type: elemType) is func begin global   const proc: doSort3 (in var elemType: x, in var elemType: y, in var elemType: z) is func local var array elemType: sorted is 0 times elemType.value; begin writeln("BEFORE: x=[" <& x <& "]; y...
Give a code snippet in #Scala Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Factor
Factor
USING: formatting fry io kernel math math.functions math.parser math.ranges sequences ; IN: rosetta-code.van-der-corput   : vdc ( n base -- x ) [ >base string>digits <reversed> ] [ nip '[ 1 + neg _ swap ^ * ] ] 2bi map-index sum ;   : vdc-demo ( -- ) 2 5 [a,b] [ dup "Base %d: " printf 10 <iota> ...
Give a code snippet in #Factor When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Kotlin
Kotlin
fun <T> modeOf(a: Array<T>) { val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size } val maxFreq = sortedByFreq.first().value.size val modes = sortedByFreq.takeWhile { it.value.size == maxFreq } if (modes.size == 1) println("The mode of the collection is ${modes.first()....
Give a code snippet in #Kotlin Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if p...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may ...
#Wren
Wren
var s = [1, 2, 2, 3, 4, 4, 5]   // There is no output as 'prev' is created anew each time // around the loop and set implicitly to null. for (i in 0...s.count) { var curr = s[i] var prev if (i > 0 && curr == prev) System.print(i) prev = curr }   // Now 'prev' is created only once and reassigned // each ...
Give a code snippet in #Wren A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection
Factorial base numbers indexing permutations of a collection
You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0....
#F.23
F#
  // Factorial base numbers indexing permutations of a collection // Nigel Galloway: December 7th., 2018 let lN2p (c:int[]) (Ω:'Ω[])= let Ω=Array.copy Ω let rec fN i g e l=match l-i with 0->Ω.[i]<-e |_->Ω.[l]<-Ω.[l-1]; fN i g e (l-1)// rotate right [0..((Array.length Ω)-2)]|>List.iter(fun n->let i=c.[n] in if i>0...
Give a code snippet in #F.23 You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#NetRexx
NetRexx
/* NetRexx ************************************************************ * 30.08.2013 Walter Pachl translated from Java/REXX/PL/I **********************************************************************/ options replace format comments java crossref savelog symbols nobinary   doors = create_doors switchWins = 0 stayWins ...
Give a code snippet in #NetRexx Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for t...
christopher/rosetta-code
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#PureBasic
PureBasic
UseSQLiteDatabase()   Procedure CheckDatabaseUpdate(database, query$) result = DatabaseUpdate(database, query$) If result = 0 PrintN(DatabaseError()) EndIf   ProcedureReturn result EndProcedure     If OpenConsole() If OpenDatabase(0, ":memory:", "", "") ;create players table with sample data Check...
Give a code snippet in #PureBasic SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworker...
christopher/rosetta-code
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#REXX
REXX
/*REXX program demonstrates how to update a configuration file (four specific tasks).*/ parse arg iFID oFID . /*obtain optional arguments from the CL*/ if iFID=='' | iFID=="," then iFID= 'UPDATECF.TXT' /*Not given? Then use default.*/ if oFID=='' | oFID=="," then oFID='\TEMP\UPDAT...
Give a code snippet in #REXX We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non c...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#MiniScript
MiniScript
suits = ["Spades", "Clubs", "Hearts", "Diamonds"] pips = ["Ace","Two","Three","Four","Five","Six","Seven", "Eight","Nine","Ten","Jack","Queen","King"]   Card = {} Card.str = function() return self.pip + " of " + self.suit + " (value: " + self.value + ")" end function   //Build Deck deck = [] for s in suits.inde...
Give a code snippet in #MiniScript Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the curr...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#AppleScript
AppleScript
-- luhn :: String -> Bool on luhn(s) -- True if the digit string represents -- a valid Luhn credit card number.   script divMod10Sum on |λ|(a, x) a + x div 10 + x mod 10 end |λ| end script   0 = foldl(divMod10Sum, 0, ¬ zipWith(my mul, ¬ map(my int, rev...
Give a code snippet in #AppleScript The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the or...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Brat
Brat
factorial = { x | true? x == 0 1 { x * factorial(x - 1)} }
Give a code snippet in #Brat Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Uniface
Uniface
variables numeric I endvariables   I = 1024 while (I > 0) putmess I I = (I/2)[trunc] endwhile
Give a code snippet in #Uniface Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downw...
christopher/rosetta-code
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#Bracmat
Bracmat
( Baker Cooper Fletcher Miller Smith:?people & ( constraints = .  !arg  : ~(? Baker)  : ~(Cooper ?)  : ~(Fletcher ?|? Fletcher)  : ? Cooper ? Miller ?  : ~(? Smith Fletcher ?|? Fletcher Smith ?)  : ~(? Cooper Fletcher ?|? Fletcher Cooper ?) ) & ( solutio...
Give a code snippet in #Bracmat Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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 ...
#8086_Assembly
8086 Assembly
mov ax,6FFFh mov bx,3456h mov cx,0   ;We'll consider these sorted when ax <= bx <= cx.   SortRegisters proc cmp ax,bx jbe continue ;if we got here, ax > bx. We don't know the relationship between bx and cx at this time. cmp ax,cx jbe swap_ax_and_bx ;if we got here, ax > bx, and bx > cx. Therefore...
Give a code snippet in #8086_Assembly 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 | ...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function isBalanced(s As String) As Boolean If s = "" Then Return True Dim countLeft As Integer = 0 '' counts number of left brackets so far unmatched Dim c As String For i As Integer = 1 To Len(s) c = Mid(s, i, 1) If c = "[" Then countLeft += 1 ElseIf countLeft > 0 Then ...
Give a code snippet in #FreeBASIC Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which m...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#uBasic.2F4tH
uBasic/4tH
For x = 0 to 25 ' Test range 0..25 Push x : GoSub _PrintOrdinal Next x  : Print   For x = 250 to 265 ' Test range 250..265 Push x : GoSub _PrintOrdinal Next x : Print   For x = 1000 to 1025 ' Test range 1000..1025 Push x : GoSub _PrintOrdinal Next x : P...
Give a code snippet in #uBasic.2F4tH Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP var [const] one=BI(1), two=BI(2), three=BI(3);   fcn pierPonts(n){ //-->((bigInt first kind primes) (bigInt second)) pps1,pps2 := List(BI(2)), List(); count1, count2, s := 1, 0, List(BI(1)); // n==2_000, s-->266_379 elements i2,i3,k := 0, 0, 1; n2,n3,t := BI(...
Give a code snippet in #zkl A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the fi...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#11l
11l
F binomial_coeff(n, k) V result = 1 L(i) 1..k result = result * (n - i + 1) / i R result   print(binomial_coeff(5, 3))
Give a code snippet in #11l This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Phix
Phix
with javascript_semantics -- comparing a simple implementation against using the builtins: sequence stack = {} procedure push_(object what) stack = append(stack,what) end procedure function pop_() object what = stack[$] stack = stack[1..$-1] return what end function function empty_() return le...
Give a code snippet in #Phix 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 acc...
christopher/rosetta-code
http://rosettacode.org/wiki/Odd_word_problem
Odd word problem
Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one punctuation, the stream will...
#Icon_and_Unicon
Icon and Unicon
procedure main() every OddWord(!["what,is,the;meaning,of:life.", "we,are;not,in,kansas;any,more."]) end   procedure OddWord(stream) #: wrapper for demonstration write("Input stream: ",stream) writes("Output stream: ") & eWord(create !stream,'.,;:') & write() end   procedure eW...
Give a code snippet in #Icon_and_Unicon Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one a...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#COBOL
COBOL
MOVE FUNCTION FACTORIAL(num) TO result
Give a code snippet in #COBOL Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a n...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Ruby
Ruby
require 'open-uri' ordered_words = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', 'r').select do |word| word.strip! word.chars.sort.join == word end   grouped = ordered_words.group_by &:size puts grouped[grouped.keys.max]
Give a code snippet in #Ruby An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Forth
Forth
https://github.com/DouglasBHoffman/FMS2
Give a code snippet in #Forth Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lambdatalk
Lambdatalk
    1) lambdas   {lambda {:x} {* :x :x}} -> _LAMB_123   2) arrays   '{A.new hello world} // defining an array -> _ARRA_123 // as replaced and used before post-processing -> [hello,world] // if unused after post-processing   3) pairs   {pre '{P.new hello world} // defining a pair -> _PAIR_123 //...
Give a code snippet in #Lambdatalk Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Arc
Arc
(for n 1 100 (prn:if (multiple n 15) 'FizzBuzz (multiple n 5) 'Buzz (multiple n 3) 'Fizz n))
Give a code snippet in #Arc Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#AWK
AWK
  # syntax: GAWK -f PROPER_DIVISORS.AWK BEGIN { show = 0 # show divisors: 0=no, 1=yes print(" N cnt DIVISORS") for (i=1; i<=20000; i++) { divisors(i) if (i <= 10 || i == 100) { # including 100 as it was an example in task description printf("%5d  %3d  %s\n",i,Dcnt,Dstr) } ...
Give a code snippet in #AWK The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisor...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#J
J
10{.\:~(#;{.)/.~;:tolower((e.&(a.-.Alpha_j_,' '))`(,:&' '))}1!:1<jpath'~/downloads/books/LesMis.txt' ┌─────┬────┐ │41093│the │ ├─────┼────┤ │19954│of │ ├─────┼────┤ │14943│and │ ├─────┼────┤ │14558│a │ ├─────┼────┤ │13953│to │ ├─────┼────┤ │11219│in │ ├─────┼────┤ │9649 │he │ ├─────┼────┤ │8622 │was │ ├─────┼─...
Give a code snippet in #J Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Vlang
Vlang
name := 'Bob' age := 20 large_number := i64(9999999999)
Give a code snippet in #Vlang Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Clojure
Clojure
; Basic usage > (reduce * '(1 2 3 4 5)) 120 ; Using an initial value > (reduce + 100 '(1 2 3 4 5)) 115  
Give a code snippet in #Clojure Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#Liberty_BASIC
Liberty BASIC
  global outnum$ dim ones$(20),tens$(9),gr$(5),group(5) for a = 0 to 19 read a$:ones$(a)=a$ next a for a = 1 to 8 read a$:tens$(a)=a$ next a   [start] redim gr$(5) redim group(5)   input "Enter a number (nonzero positive integers only less than 1 quadrillion, no commas): ";num$   num$=trim$(num$...
Give a code snippet in #Liberty_BASIC Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other t...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#BBC_BASIC
BBC BASIC
HIMEM = PAGE + 8000000 nItems% = 22 maxWeight% = 400   DIM Tag{ivalue%, list%(nItems%-1), lp%} DIM items{(nItems%-1)name$, weight%, ivalue%} FOR item% = 0 TO nItems%-1 READ items{(item%)}.name$, items{(item%)}.weight%, items{(item%)}.ivalue% NEXT   DATA "map", 9, ...
Give a code snippet in #BBC_BASIC A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will ...
christopher/rosetta-code
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Scala
Scala
trait Thingable { def thing: String }   class Delegator { var delegate: Thingable = _   def operation: String = if (delegate == null) "default implementation" else delegate.thing }   class Delegate extends Thingable { override def thing = "delegate implementation" }   // Example usage // Memory management ign...
Give a code snippet in #Scala A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also w...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Kotlin
Kotlin
// version 1.1   import java.util.*   fun main(args: Array<String>) { println("Keep entering text or the word 'quit' to end the program:") val sc = Scanner(System.`in`) val words = mutableListOf<String>() while (true) { val input: String = sc.next() if (input.trim().toLowerCase() == "qui...
Give a code snippet in #Kotlin Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#TypeScript
TypeScript
  // N'th function suffix(n: number): string { var nMod10: number = n % 10; var nMod100: number = n % 100; if (nMod10 == 1 && nMod100 != 11) return "st"; else if (nMod10 == 2 && nMod100 != 12) return "nd"; else if (nMod10 == 3 && nMod100 != 13) return "rd"; else return "th"; }   function pr...
Give a code snippet in #TypeScript Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Tcl
Tcl
# Can find the modal value of any vector of values proc mode {n args} { foreach n [list $n {*}$args] { dict incr counter $n } set counts [lsort -stride 2 -index 1 -decreasing $counter] set best {} foreach {n count} $counts { if {[lindex $counts 1] == $count} { lappend bes...
Give a code snippet in #Tcl Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if poss...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#JavaScript
JavaScript
const check = s => { const arr = [...s]; const at = arr.findIndex( (v, i) => i === 0 ? false : v !== arr[i - 1] ) const l = arr.length; const ok = at === -1; const p = ok ? "" : at + 1; const v = ok ? "" : arr[at]; const vs = v === "" ? v : `"${v}"` const h = ok ? "" : `0x${v.codePointAt(0).toSt...
Give a code snippet in #JavaScript Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#DCL
DCL
$ rnd = f$extract( 21, 2, f$time() ) $ count = 0 $ loop: $ inquire guess "guess what number between 0 and 99 inclusive I am thinking of" $ guess = f$integer( guess ) $ if guess .lt. 0 .or. guess .gt. 99 $ then $ write sys$output "out of range" $ goto loop $ endif $ count = count + 1 $ if guess .lt. rnd then $ write s...
Give a code snippet in #DCL Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: high...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Prolog
Prolog
leftfact(N):- leftfact(N, 0, 0, 1).   leftfact(N, N, _, _):- !. leftfact(N, M, L, F):- ((M =< 10 ; (M =< 110, 0 is M mod 10)) -> writef("!%w = %w\n", [M, L]) ; (0 is M mod 1000 -> number_string(L, S), string_length(S, Len), writef("length of !%w is...
Give a code snippet in #Prolog Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[UniqueCharacters] UniqueCharacters[s_String] := Module[{c, len, good = True}, c = Characters[s]; len = Length[c]; Print[s, " with length ", len]; Do[ If[c[[i]] == c[[j]], Print["Character ", c[[i]], " is repeated at positions ", i, " and ", j]; good = False ] , {i, len - 1}, ...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#PureBasic
PureBasic
#N=9 Define.i i,j   If OpenConsole("Magic squares") PrintN("The square order is: "+Str(#N)) For i=1 To #N For j=1 To #N Print(RSet(Str((i*2-j+#N-1) % #N*#N + (i*2+j-2) % #N+1),5)) Next PrintN("") Next PrintN("The magic number is: "+Str(#N*(#N*#N+1)/2)) EndIf Input()
Give a code snippet in #PureBasic A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The num...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Quackery
Quackery
0 [ 1+ dup echo cr dup 6 mod 0 = until ] drop
Give a code snippet in #Quackery Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#REXX
REXX
/* REXX Use Cramer's rule to compute solutions of given linear equations */ Numeric Digits 20 names='w x y z' M=' 2 -1 5 1', ' 3 2 2 -6', ' 1 3 3 -1', ' 5 -2 -3 3' v=' -3', '-32', '-47', ' 49' Call mk_mat(m) /* M -> a.i.j */ Do j=1 To dim ...
Give a code snippet in #REXX linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_...
christopher/rosetta-code
http://rosettacode.org/wiki/Legendre_prime_counting_function
Legendre prime counting function
The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number. then π(n) ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[Phi,pi] $RecursionLimit = 10^6; Phi[x_, 0] := x Phi[x_, a_] := Phi[x, a] = Phi[x, a - 1] - Phi[Floor[x/Prime[a]], a - 1] pi[n_] := Module[{a}, If[n < 2, 0, a = pi[Floor[Sqrt[n]]]; Phi[n, a] + a - 1]] Scan[Print[pi[10^#]] &, Range[0,9]]
Give a code snippet in #Mathematica.2FWolfram_Language The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/p...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Transd
Transd
  #lang transd   MainModule: { countDivs: (λ n Int() ret_ Int() (= ret_ 2) (for i in Range(2 (to-Int (/ (to-Double n) 2) 1)) do (if (not (mod n i)) (+= ret_ 1))) (ret ret_) ),   _start: (λ max 0 tmp 0 N 1 i 2 (textout 1 " ") (while (< N 20) (=...
Give a code snippet in #Transd The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#AutoHotkey
AutoHotkey
EnvGet, OutputVar, Path MsgBox, %OutputVar%
Give a code snippet in #AutoHotkey Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Par...
#C
C
#include <stdio.h> #include <math.h>   int main() { const int N = 2; int base = 10; int c1 = 0; int c2 = 0; int k;   for (k = 1; k < pow(base, N); k++) { c1++; if (k % (base - 1) == (k * k) % (base - 1)) { c2++; printf("%d ", k); } }   prin...
Give a code snippet in #C Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others y...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Logo
Logo
while [not eof?] [print readline]
Give a code snippet in #Logo Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Arturo
Arturo
text: { Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left...
Give a code snippet in #Arturo Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either le...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Gosu
Gosu
  uses java.lang.Integer uses java.lang.Double uses java.lang.System uses java.util.ArrayList uses java.util.LinkedList uses java.util.List uses java.util.Scanner uses java.util.Stack   function permutations<T>( lst : List<T> ) : List<List<T>> { if( lst.size() == 0 ) return {} if( lst.size() == 1 ) return { lst...
Give a code snippet in #Gosu task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.Collections.Generic   Module Module1 Sub Main(ByVal args As String()) Dim a As List(Of Integer) = New List(Of Integer)() From { 0 }, used As HashSet(Of Integer) = New HashSet(Of Integer)() From { 0 }, used1000 As HashSet(Of Integer) = used.ToHashSet(), ...
Give a code snippet in #Visual_Basic_.NET The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Mirah
Mirah
def factorial_iterative(n:int) 2.upto(n-1) do |i| n *= i end n end   puts factorial_iterative 10
Give a code snippet in #Mirah Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a n...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#C
C
int i; for(i = 1; i < 10; i += 2) printf("%d\n", i);
Give a code snippet in #C Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increme...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#C.23
C#
using System; using System.Linq;   namespace PentominoTiling { class Program { static readonly char[] symbols = "FILNPTUVWXYZ-".ToCharArray();   static readonly int nRows = 8; static readonly int nCols = 8; static readonly int target = 12; static readonly int blank = 12; ...
Give a code snippet in #C.23 A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Delphi
Delphi
program HostIntrospection ;   {$APPTYPE CONSOLE}   uses SysUtils;   begin Writeln('word size: ', SizeOf(Integer)); Writeln('endianness: little endian'); // Windows is always little endian end.
Give a code snippet in #Delphi Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#Simula
Simula
! MATRIX ARITHMETIC ; BEGIN   INTEGER PROCEDURE LENGTH(A); ARRAY A; LENGTH := UPPERBOUND(A, 1) - LOWERBOUND(A, 1) + 1;    ! Set MAT to the first minor of A dropping row X and column Y ; PROCEDURE MINOR(A, X, Y, MAT); ARRAY A, MAT; INTEGER X, Y; BEGIN INTEGER I, J, rowA, M; M := LENGTH(A) ...
Give a code snippet in #Simula For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#OCaml
OCaml
let counting_sort_array arr lo hi = let count = Array.make (hi-lo+1) 0 in Array.iter (fun i -> count.(i-lo) <- count.(i-lo) + 1) arr; Array.concat (Array.to_list (Array.mapi (fun i x -> Array.make x (lo+i)) count))
Give a code snippet in #OCaml Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#Raku
Raku
use Math::Primesieve; my $sieve = Math::Primesieve.new;   my %prime-base;   my $chars = 4; # for demonstration purposes. Change to 5 for the whole shmegegge.   my $threshold = ('1' ~ 'Z' x $chars).parse-base(36);   my @primes = $sieve.primes($threshold);   %prime-base.push: $_ for (2..36).map: -> $base { $threshold...
Give a code snippet in #Raku Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Fortran
Fortran
program test_substring   character (*), parameter :: string = 'The quick brown fox jumps over the lazy dog.' character (*), parameter :: substring = 'brown' character , parameter :: c = 'q' integer , parameter :: n = 5 integer , parameter :: m = 15 integer :: i   ! Display the ...
Give a code snippet in #Fortran Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#PL.2FM
PL/M
/* IF-THEN-ELSE - THE ELSE STATEMENT; PART IS OPTIONAL */ IF COND THEN STATEMENT1; ELSE STATEMENT2;   /* CAN BE CHAINED - THE ELSE STATEMENTX; PART IS STILL OPTIONAL */ IF COND1 THEN STATEMENT1; ELSE IF CONB2 THEN STATEMENT2; ELSE IF CONB3 THEN STATEMENT3; ELSE STATEMENTX;
Give a code snippet in #PL.2FM Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#MathCortex
MathCortex
I = eye(10)
Give a code snippet in #MathCortex Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#XPL0
XPL0
code Text=12; \built-in routine to display a string of characters string 0; \use zero-terminated strings (not MSb terminated)   func StrLen(S); \Return number of characters in an ASCIIZ string char S; int I; for I:= 0, -1>>1-1 do \(limit = 2,147,483,646 if 32 bit, or 32766 if 16 bit) ...
Give a code snippet in #XPL0 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#Nim
Nim
type Digit = range[0..9]   iterator digits(n: int64): Digit = var n = n while true: yield n mod 10 n = n div 10 if n == 0: break   func isLynchBell(num: int64): bool = var hSet: set[Digit] for d in num.digits: if d == 0 or num mod d != 0 or d in hSet: return false hSet.incl(d) return...
Give a code snippet in #Nim Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n...
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#FreePascal
FreePascal
{$mode objfpc} uses windows,math;{ windows only } var Interval:Double = 1.0594630943592953; i:integer; begin for i:= 0 to 11 do beep(Round(440.0*interval**i),500); end.
Give a code snippet in #FreePascal Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, R...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
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 ...
#PicoLisp
PicoLisp
(de orderDisjoint (M N) (for S N (and (memq S M) (set @ NIL)) ) (mapcar '((S) (or S (pop 'N))) M ) )
Give a code snippet in #PicoLisp Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Nanoquery
Nanoquery
def caesar_encode(plaintext, shift) uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lowercase = "abcdefghijklmnopqrstuvwxyz"   cipher = "" for char in plaintext if char in uppercase cipher += uppercase[uppercase[char] - (26 - shift)] else if char in lowercase cipher += lowercase[lowercase[char] - (26 - shift)] ...
Give a code snippet in #Nanoquery Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface Hofstadter : NSObject + (int)M: (int)n; + (int)F: (int)n; @end   @implementation Hofstadter + (int)M: (int)n { if ( n == 0 ) return 0; return n - [self F: [self M: (n-1)]]; } + (int)F: (int)n { if ( n == 0 ) return 1; return n - [self M: [self F: (n-1)]]; } @end   ...
Give a code snippet in #Objective-C Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Quackery
Quackery
[ temp put 0 [ over while swap temp share /mod rot + again ] nip temp release ] is digitsum ( n n --> n )   1 10 digitsum echo sp 1234 10 digitsum echo sp hex FE 16 digitsum echo sp hex F0E 16 digitsum echo
Give a code snippet in #Quackery Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#Sidef
Sidef
func ordered(a, b) { (a <=> b) < 0 }   for p in [ Pair([1,2,4], [1,2,4]), Pair([1,2,4], [1,2] ), Pair([1,2], [1,2,4]), ] { var a = p.first var b = p.second var before = ordered(a, b) say "#{a} comes before #{b} : #{before}" }
Give a code snippet in #Sidef sorting 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 | ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Rust
Rust
  use itertools::Itertools;   const PRIMES: [u64; 15] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]; const MAX_DIVISOR: usize = 64;   struct DivisorSeq { max_number_of_divisors: u64, index: u64, }   impl DivisorSeq { fn new(max_number_of_divisors: u64) -> DivisorSeq { DivisorSeq { ...
Give a code snippet in #Rust Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Seq...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Maxima
Maxima
weekday(year, month, day) := block([m: month, y: year, k], if m < 3 then (m: m + 12, y: y - 1), k: 1 + remainder(day + quotient((m + 1)*26, 10) + y + quotient(y, 4) + 6*quotient(y, 100) + quotient(y, 400) + 5, 7), ['monday, 'tuesday, 'wednesday, 'thurdsday, 'friday, 'saturday, 'sunday][k] )$   sublist(...
Give a code snippet in #Maxima A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between...
christopher/rosetta-code
http://rosettacode.org/wiki/Rendezvous
Rendezvous
Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
#D
D
import std.stdio, std.array, std.datetime, std.exception, std.concurrency, core.thread, core.atomic;   final class OutOfInk: Exception { this() pure nothrow { super("Out of ink."); } }   struct Printer { string id; size_t ink;   void printIt(in string line) { enforce(ink != 0,...
Give a code snippet in #D Demonstrate the “rendezvous” communications technique by implementing a printer monitor.
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Raku
Raku
foo # as list operator foo() # as function foo.() # as function, explicit postfix form $ref() # as object invocation $ref.() # as object invocation, explicit postfix &foo() # as object invocation &foo.() # as object invocation, explicit post...
Give a code snippet in #Raku Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a var...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Oz
Oz
functor export New Get Set Transform define fun {New Width Height Init} C = {Array.new 1 Height unit} in for Row in 1..Height do C.Row := {Array.new 1 Width Init} end   array2d(width:Width height:Height contents:C) end   fun {Get array2d(contents:C ...) X ...
Give a code snippet in #Oz Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#Raku
Raku
(2..2**19).hyper.map: -> $candidate { my $sum = 1 / $candidate; for 2 .. ceiling(sqrt($candidate)) -> $factor { if $candidate %% $factor { $sum += 1 / $factor + 1 / ($candidate / $factor); } } if $sum.nude[1] == 1 { say "Sum of reciprocal factors of $candidate = $sum ...
Give a code snippet in #Raku Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (a...
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#Scala
Scala
import scala.annotation.tailrec   object DammAlgorithm extends App {   private val numbers = Seq(5724, 5727, 112946, 112949)   @tailrec private def damm(s: String, interim: Int): String = { def table = Vector( Vector(0, 3, 1, 7, 5, 9, 8, 6, 4, 2), Vector(7, 0, 9, 2, 1, 5, 4, 8, 6, 3), ...
Give a code snippet in #Scala The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code