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/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#Sidef
Sidef
define ( RECORD_FIELDS = %w(account password UID GID GECOS directory shell), GECOS_FIELDS = %w(fullname office extension homephone email), RECORD_SEP = ':', GECOS_SEP = ',', PASSWD_FILE = 'passwd.txt', )   # here's our three records var records_to_write = [ Hash( account => 'j...
Give a code snippet in #Sidef Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most u...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#CoffeeScript
CoffeeScript
binarySearch = (xs, x) -> do recurse = (low = 0, high = xs.length - 1) -> mid = Math.floor (low + high) / 2 switch when high < low then NaN when xs[mid] > x then recurse low, mid - 1 when xs[mid] < x then recurse mid + 1, high else mid
Give a code snippet in #CoffeeScript A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Raku
Raku
my %pairs = hello => 13, world => 31, '!' => 71;   for %pairs.kv -> $k, $v { say "(k,v) = ($k, $v)"; }   # Stable order for %pairs.sort(*.value)>>.kv -> ($k, $v) { say "(k,v) = ($k, $v)"; }   { say "$^a => $^b" } for %pairs.kv;   say "key = $_" for %pairs.keys;   say "value = $_" for %pairs.values;
Give a code snippet in #Raku Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Action.21
Action!
DEFINE TOP="0" DEFINE RIGHT="1" DEFINE BOTTOM="2" DEFINE LEFT="3" DEFINE WIDTH="160" DEFINE HEIGHT="96"   DEFINE STACK_SIZE="5000" BYTE ARRAY stack(STACK_SIZE) INT stackSize   PROC InitStack() stackSize=0 RETURN   BYTE FUNC IsEmpty() IF stackSize=0 THEN RETURN (1) FI RETURN (0)   BYTE FUNC IsFull() IF stack...
Give a code snippet in #Action.21 Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#jq
jq
def is_pangram: explode | map( if 65 <= . and . <= 90 then . + 32 # uppercase elif 97 <= . and . <= 122 then . # lowercase else empty end ) | unique | length == 26;   # Example: "The quick brown fox jumps over the lazy dog" | is_pangram
Give a code snippet in #jq Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#C
C
#include <stdio.h> #include <string.h> #include <stdlib.h>   const char *ca = "/*", *cb = "*/"; int al = 2, bl = 2;   char *loadfile(const char *fn) { FILE *f = fopen(fn, "rb"); int l; char *s;   if (f != NULL) { fseek(f, 0, SEEK_END); l = ftell(f); s = malloc(l+1); rewind(f); if (s) fread(s, ...
Give a code snippet in #C A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at ...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#Wren
Wren
import "/fmt" for Conv, Fmt   var reverse = Fn.new { |s| var e = 0 while (s > 0) { e = e * 10 + (s % 10) s = (s/10).floor } return e }   var MAX = 100000 var data = [ [1, 20, 7], [86, 100, 8], [991, 1000, 10], [9995, 10000, 12], [99996, 100000, 14] ] var results = {} for (d in data) { ...
Give a code snippet in #Wren Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful num...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Preserve_screen
Terminal control/Preserve screen
Task Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved.   If the implement...
#Go
Go
package main   import ( "fmt" "time" )   func main() { fmt.Print("\033[?1049h\033[H") fmt.Println("Alternate screen buffer\n") s := "s" for i := 5; i > 0; i-- { if i == 1 { s = "" } fmt.Printf("\rgoing back in %d second%s...", i, s) time.Sleep(time.Sec...
Give a code snippet in #Go Task Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be p...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#Scala
Scala
import java.awt.print.PrinterException import scala.swing.TextArea   object LinePrinter extends App { val (show, context) = (false, "Hello, World!") try // Default Helvetica, 12p new TextArea(context) { append(" in printing.") peer.print(null, null, show, null, null, show) } catch { case e...
Give a code snippet in #Scala Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#C
C
/* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC, § 22 */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 4 #define M 4 enum Move{UP,DOWN,LEFT,RIGHT};int hR;int hC;int cc[N][M];const int nS=100;int update(enum Move m){const int dx[]={0,0,-1,1};const int...
Give a code snippet in #C Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Cut_a_rectangle
Cut a rectangle
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE} -- Initialization   make -- Finds solution for cut a rectangle up to 10 x 10. local i, j, n: Integer r: GRID do n := 10 from i := 1 until i > n loop from j := 1 until j > i loop if i.bit_and (1) /= 1 or j.b...
Give a code snippet in #Eiffel A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such path...
christopher/rosetta-code
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#C
C
#include <math.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h>   struct Pair { uint64_t v1, v2; };   struct Pair makePair(uint64_t a, uint64_t b) { struct Pair r; r.v1 = a; r.v2 = b; return r; }   struct Pair solvePell(int n) { int x = (int) sqrt(n);   if (x * x == n) { ...
Give a code snippet in #C Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive inte...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Burlesque
Burlesque
  blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1 1 12 66 220 495 792 924 792 495 220 66 12 1 1 13 78 286 715...
Give a code snippet in #Burlesque Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is ei...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#ALGOL_68
ALGOL 68
BEGIN # cache factorials from 0 to 11 # [ 0 : 11 ]INT fact; fact[0] := 1; FOR n TO 11 DO fact[n] := fact[n-1] * n OD; FOR b FROM 9 TO 12 DO print( ( "The factorions for base ", whole( b, 0 ), " are:", newline ) ); FOR i TO 1500000 - 1 DO INT sum := 0; ...
Give a code snippet in #ALGOL_68 Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;   public class HumbleNumbers {   public static void main(String[] args) { System.out.println("First 50 humble numbers:"); ...
Give a code snippet in #Java Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above ...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#TI-83_BASIC
TI-83 BASIC
:ClrHome ­:1→X :Input ">",Str1 :Str1→Str2 :Repeat L≤1 :Disp Str1 :length(Str1→L :L→dim(L₁ :seq(expr(sub(Str1,A,1)),A,1,L)→L₁ :sum(L₁→N :{0,.5,1→L₂ :NL₂→L₃ :Med-Med L₂,L₃,Y₁ :Equ►String(Y₁,Str1 :sub(Str1,1,length(Str1)-3→Str1 :X+1→X :End :Pause :ClrHome :Disp Str2,"DIGITAL ROOT",expr(Str1),"ADDITIVE","PERSISTENCE",X...
Give a code snippet in #TI-83_BASIC The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle ...
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...
#PureBasic
PureBasic
OpenConsole()   Repeat ; Ask for limits, with sanity check Print("Enter low limit : "): low =Val(Input()) Print("Enter high limit: "): High =Val(Input()) Until High>low   TheNumber=Random(High-low)+low Debug TheNumber Repeat Print("Guess what number I have: "): Guess=Val(Input()) If Guess=TheNumber Pri...
Give a code snippet in #PureBasic 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:...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#RLaB
RLaB
>> s = "myusername" myusername >> $$.[s] = 10; >> myusername 10
Give a code snippet in #RLaB Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Smalltalk
Smalltalk
String extend [ lookAndSay [ |anElement nextElement counter coll newColl| coll := (self asOrderedCollection). newColl := OrderedCollection new. counter := 0. anElement := (coll first). [ coll size > 0 ] whileTrue: [ nextElement := coll removeFirst. ( anElement == nextElement ) i...
Give a code snippet in #Smalltalk The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Elixir
Elixir
defmodule RC do def comb_rep(0, _), do: [[]] def comb_rep(_, []), do: [] def comb_rep(n, [h|t]=s) do (for l <- comb_rep(n-1, s), do: [h|l]) ++ comb_rep(n, t) end end   s = [:iced, :jam, :plain] Enum.each(RC.comb_rep(2, s), fn x -> IO.inspect x end)   IO.puts "\nExtra credit: #{length(RC.comb_rep(3, Enum.to...
Give a code snippet in #Elixir The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Jack
Jack
class Main { function void main () { do Output.printString("Goodbye, World!");und return; } }
Give a code snippet in #Jack Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Ada
Ada
with Ada.Text_IO; with Ada.Numerics.Generic_Elementary_Functions;   procedure Almost_Integers is   type Real is new Long_Long_Float;   package Real_IO is new Ada.Text_IO.Float_IO (Real); package Integer_IO is new Ada.Text_IO.Integer_IO (Integer);   function Faculty (N : in Long_Long_Integer) ret...
Give a code snippet in #Ada The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#AWK
AWK
  function step_up() { while (!step()) { step_up() } }  
Give a code snippet in #AWK From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detec...
christopher/rosetta-code
http://rosettacode.org/wiki/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Temp_File is Temp : File_Type; Contents : String(1..80); Length : Natural; begin -- Create a temporary file Create(File => Temp); Put_Line(File => Temp, Item => "Hello World"); Reset(File => Temp, Mode => In_File); Get_Line(File => Temp, Item => Con...
Give a code snippet in #Ada Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" ...
christopher/rosetta-code
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#Python
Python
>>> s = "Hello" >>> s[0] = "h"   Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> s[0] = "h" TypeError: 'str' object does not support item assignment
Give a code snippet in #Python Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Sidef
Sidef
func cwr (n, l, a = []) { n>0 ? (^l -> map {|k| __FUNC__(n-1, l.slice(k), [a..., l[k]]) }) : a }   cwr(2, %w(iced jam plain)).each {|a| say a.map{ .join(' ') }.join("\n") }
Give a code snippet in #Sidef The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the la...
#Perl
Perl
  #!/usr/bin/perl use strict; use warnings; use Storable; use Data::Dumper;   my $src = { foo => 0, bar => [0, 1] }; $src->{baz} = $src; my $dst = Storable::dclone($src); print Dumper($src); print Dumper($dst);  
Give a code snippet in #Perl Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this fac...
christopher/rosetta-code
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#REXX
REXX
/*REXX program uses a Shoelace formula to calculate the area of an N─sided polygon.*/ parse arg $; if $='' then $= "(3,4),(5,11),(12,8),(9,5),(5,6)" /*Use the default?*/ A= 0; @= space($, 0) /*init A; elide blanks from pts.*/ do #=1 until @==''; parse var @...
Give a code snippet in #REXX Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#AutoHotkey
AutoHotkey
Item = map,compass,water,sandwich,glucose,tin,banana,apple,cheese,beer,suntan cream ,camera,tshirt,trousers,umbrella,waterproof trousers,waterproof overclothes,notecase ,sunglasses,towel,socks,book Weight= 9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30 Value = 150,35,200,60,60,45,60,40,30,1...
Give a code snippet in #AutoHotkey 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 some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 k...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#Java_2
Java
  import java.util.LinkedList;   public class RPN{ public static void main(String[] args) { evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +"); }   private static void evalRPN(String expr){ LinkedList<Double> stack = new LinkedList<Double>(); System.out.println("Input\tOperation\tStack after"); for (String token : expr.sp...
Give a code snippet in #Java_2 Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the R...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#Raku
Raku
multi bind (@list, &code) { @list.map: &code };   multi bind ($item, &code) { $item.&code };   sub divisors (Int $int) { gather for 1 .. $int { .take if $int %% $_ } }   put (^10).&bind(* + 3).&bind(&divisors)».&bind(*.base: 2).join: "\n";
Give a code snippet in #Raku A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically kn...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Raku
Raku
my $a = 1 + i; my $b = pi + 1.25i;   .say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj; .say for $a.abs, $a.sqrt, $a.re, $a.im;
Give a code snippet in #Raku A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Go
Go
  package main import ( "fmt" "os" )   func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is %s\n", i, x) } }  
Give a code snippet in #Go Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Euphoria
Euphoria
constant table = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " function random_generation(integer len) sequence s s = rand(repeat(length(table),len)) for i = 1 to len do s[i] = table[s[i]] end for return s end function   function mutate(sequence s, integer n) for i = 1 to length(s) do if rand(n)...
Give a code snippet in #Euphoria Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance/Alignment
Levenshtein distance/Alignment
The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used t...
#Julia
Julia
function levenshteinalign(a::AbstractString, b::AbstractString) a = lowercase(a) b = lowercase(b) len_a = length(a) len_b = length(b)   costs = Matrix{Int}(len_a + 1, len_b + 1) costs[1, :] .= 0:len_b @inbounds for i in 2:(len_a + 1) costs[i, 1] = i for j in 2:(len_b + 1) ...
Give a code snippet in #Julia The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Raku
Raku
say 30.base(2); # "11110" say 30.base(8); # "36" say 30.base(10); # "30" say 30.base(16); # "1E" say 30.base(30); # "10"
Give a code snippet in #Raku Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard rout...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#Raku
Raku
< Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge ...
Give a code snippet in #Raku This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlic...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#Standard_ML
Standard ML
fun merge cmp ([], ys) = ys | merge cmp (xs, []) = xs | merge cmp (xs as x::xs', ys as y::ys') = case cmp (x, y) of GREATER => y :: merge cmp (xs, ys') | _ => x :: merge cmp (xs', ys) ; fun merge_sort cmp [] = [] | merge_sort cmp [x] = [x] | merge_sort cmp xs = let val y...
Give a code snippet in #Standard_ML 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 | Qu...
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...
#AppleScript
AppleScript
-- LAST SUNDAYS OF YEAR ------------------------------------------------------   -- lastSundaysOfYear :: Int -> [Date] on lastSundaysOfYear(y)   -- lastWeekDaysOfYear :: Int -> Int -> [Date] script lastWeekDaysOfYear on |λ|(intYear, iWeekday)   -- lastWeekDay :: Int -> Int -> Date ...
Give a code snippet in #AppleScript 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-...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#Scala
Scala
scala> val x = 2.0 x: Double = 2.0   scala> val xi = 0.5 xi: Double = 0.5   scala> val y = 4.0 y: Double = 4.0   scala> val yi = 0.25 yi: Double = 0.25   scala> val z = x + y z: Double = 6.0   scala> val zi = 1.0 / ( x + y ) zi: Double = 0.16666666666666666   scala> val numbers = List(x, y, z) numbers: List[Double] = L...
Give a code snippet in #Scala In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to crea...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#OCaml
OCaml
# 0.0 ** 0.0;; - : float = 1. # Complex.pow Complex.zero Complex.zero;; - : Complex.t = {Complex.re = nan; Complex.im = nan} # #load "nums.cma";; # open Num;; # Int 0 **/ Int 0;; - : Num.num = Int 1
Give a code snippet in #OCaml Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Wren
Wren
var n = 15 var t = List.filled(n+2, 0) t[1] = 1 for (i in 1..n) { if (i > 1) for (j in i..2) t[j] = t[j] + t[j-1] t[i+1] = t[i] if (i > 0) for (j in i+1..2) t[j] = t[j] + t[j-1] System.write("%(t[i+1]-t[i]) ") } System.print()
Give a code snippet in #Wren Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that gener...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#MATLAB
MATLAB
function rms = quadraticMean(list) rms = sqrt(mean(list.^2)); end
Give a code snippet in #MATLAB Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 ...
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...
#Ada
Ada
package My_Package is type My_Type is tagged private; procedure Some_Procedure(Item : out My_Type); function Set(Value : in Integer) return My_Type; private type My_Type is tagged record Variable : Integer := -12; end record; end My_Package;
Give a code snippet in #Ada 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/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 ...
#Liberty_BASIC
Liberty BASIC
  a$ =" 1 $23.19 2 elbow 3 2 Bork 4 3 elbow 2 $23.19 " print "Original set of elements = ["; a$; "]"   b$ =removeDuplicates$( a$) print "With duplicates removed = ["; b$; "]"   end   function removeDuplicates$( in$) o$ =" " i =1 do term$ =word$( in$, i, " ") if instr( o$, " "; term$; " ...
Give a code snippet in #Liberty_BASIC 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/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Common_Lisp
Common Lisp
(loop for i in list do (print i))
Give a code snippet in #Common_Lisp Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#Objeck
Objeck
  bundle Default { class Insert { function : Main(args : String[]) ~ Nil { values := [9, 7, 10, 2, 9, 7, 4, 3, 10, 2, 7, 10]; InsertionSort(values); each(i : values) { values[i]->PrintLine(); }; }   function : InsertionSort (a : Int[]) ~ Nil { each(i : a) { va...
Give a code snippet in #Objeck Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { ITERATIONS = 1000000 delete symbMap delete probMap delete counts initData();   for (i = 0; i < ITERATIONS; i++) { distribute(rand()) } showDistributions()   exit }   function distribute(rnd, cnt, symNum, sym, symPrb) { cnt = length(symbMap) ...
Give a code snippet in #AWK Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because float...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#OCaml
OCaml
let lst = [1;2;3;4;5;6] let even_lst = List.filter (fun x -> x mod 2 = 0) lst
Give a code snippet in #OCaml Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program game24Solvex64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstant...
Give a code snippet in #AArch64_Assembly 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/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#Icon_and_Unicon
Icon and Unicon
procedure main(a) n := integer(!a) | 20 every (nr|nw|nb) := ?n-1 sIn := repl("r",nw)||repl("w",nb)||repl("b",nr) write(sRand := bestShuffle(sIn)) write(sOut := map(csort(map(sRand,"rwb","123")),"123","rwb")) if sIn ~== sOut then write("Eh? Not in correct order!") end   procedure bestShuffle(s) ...
Give a code snippet in #Icon_and_Unicon The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order...
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#Fortran
Fortran
LOGICAL FUNCTION ISPRIME(N) !Ad-hoc, since N is not going to be big... INTEGER N !Despite this intimidating allowance of 32 bits... INTEGER F !A possible factor. ISPRIME = .FALSE. !Most numbers aren't prime. DO F = 2,SQRT(DFLOAT(N)) !Wince... IF (MOD(N,F).EQ.0) RETURN ...
Give a code snippet in #Fortran A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to inv...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#SenseTalk
SenseTalk
  # Hashtag is a comment -- Dash dash is another comment // Slash slash is yet another comment — Alt/Option + Underscore creates an m-dash comment (* Parentheses and star is used for commenting blocks of code (* and can be nested *) *) set foo to true // all comments can append to statements  
Give a code snippet in #SenseTalk Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#TXR
TXR
$ txr -p '(exptmod 2988348162058574136915891421498819466320163312926952423791023078876139 2351399303373464486466122544523690094744975233415544072992656881240319 (expt 10 40)))' 1527229998585248450016808958343740453059
Give a code snippet in #TXR Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#XSLT
XSLT
  <xsl:template name="ackermann"> <xsl:param name="m"/> <xsl:param name="n"/>   <xsl:choose> <xsl:when test="$m = 0"> <xsl:value-of select="$n+1"/> </xsl:when> <xsl:when test="$n = 0"> <xsl:call-template name="ackermann"> <xsl:with-param name="m" select="$m - 1"...
Give a code snippet in #XSLT The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
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 ...
#Erlang
Erlang
  -module( four_bit_adder ).   -export( [add_bits/3, create/1, task/0] ).   add_bits( Adder, A_bits, B_bits ) -> Adder ! {erlang:self(), lists:reverse(A_bits), lists:reverse(B_bits)}, receive {Adder, Sum, Carry} -> {Sum, Carry} end.   create( How_many_bits ) -> Full_adders = connect_full_adders( [full_adder_create...
Give a code snippet in #Erlang 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/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#C
C
  #include <string.h> #include <memory.h>     static unsigned int _parseDecimal ( const char** pchCursor ) { unsigned int nVal = 0; char chNow; while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' ) { //shift digit in nVal *= 10; nVal += chNow - '0';   ++*pchCursor; ...
Give a code snippet in #C The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Prolog
Prolog
  :- use_module(library(clpfd)).   % main predicate my_sum(Min, Max, Top, LL):- L = [A,B,C,D,E,F,G], L ins Min..Max, ( Top == 0 -> all_distinct(L) ; true), R #= A+B, R #= B+C+D, R #= D+E+F, R #= F+G, setof(L, labeling([ff], L), LL).     my_sum_1(Min, Max) :- my_sum(Min,...
Give a code snippet in #Prolog 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of th...
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...
#REXX
REXX
/*REXX program finds and displays the smallest number with exactly N divisors.*/ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N= 15 /*Not specified? Then use the default.*/ say '──divisors── ──smallest number with N div...
Give a code snippet in #REXX 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/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Lua
Lua
a = function() return 1 end b = function(r) print( r() ) end b(a)
Give a code snippet in #Lua Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#BQN
BQN
GenFizzBuzz ← {factors‿words ← <˘⍉>𝕨 ⋄ (∾´∾⟜words/˜·(¬∨´)⊸∾0=factors|⊢)¨1+↕𝕩}
Give a code snippet in #BQN Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: a (in boolean: aBool) is func result var boolean: result is FALSE; begin writeln("a"); result := aBool; end func;   const func boolean: b (in boolean: aBool) is func result var boolean: result is FALSE; begin writeln("b"); result := aBool...
Give a code snippet in #Seed7 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable res...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Raku
Raku
use SVG;   role Lindenmayer { has %.rules; method succ { self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules) } }   my $hilbert = 'A' but Lindenmayer( { A => '-BF+AFA+FB-', B => '+AF-BFB-FA+' } );   $hilbert++ xx 7; my @points = (647, 13);   for $hilbert.comb { state ($x, $y) = ...
Give a code snippet in #Raku Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 READ n 20 DIM d$(n,5) 30 FOR i=1 TO n 40 READ d$(i) 50 NEXT i 60 DATA 3,"iced","jam","plain" 70 FOR i=1 TO n 80 FOR j=i TO n 90 PRINT d$(i);" ";d$(j) 100 NEXT j 110 NEXT i
Give a code snippet in #ZX_Spectrum_Basic The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where eac...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Pascal
Pascal
program MultRoot; {$IFDEF FPC} {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16} {$ENDIF} {$IFDEF WINDOWS} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils; type tMul3Dgt = array[0..999] of Uint32; tMulRoot = record mrNum, mrMul, mrPers : Uint64; end; ...
Give a code snippet in #Pascal The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Cobra
Cobra
  class Rosetta def gcd(u as number, v as number) as number u, v = u.abs, v.abs while v > 0 u, v = v, u % v return u   def main print "gcd of [12] and [8] is [.gcd(12, 8)]" print "gcd of [12] and [-8] is [.gcd(12, -8)]" print "gcd of [96] and [27] is [.gcd(27, 96)]" print "gcd of [51] and [34] is [.g...
Give a code snippet in #Cobra Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a...
#Java
Java
  import java.math.BigInteger;   public class SuperDNumbers {   public static void main(String[] args) { for ( int i = 2 ; i <= 9 ; i++ ) { superD(i, 10); } }   private static final void superD(int d, int max) { long start = System.currentTimeMillis(); String test...
Give a code snippet in #Java A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   o...
christopher/rosetta-code
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   ...
#Python
Python
# coding=UTF-8 from __future__ import print_function, division from math import sqrt   def cell(n, x, y, start=1): d, y, x = 0, y - n//2, x - (n - 1)//2 l = 2*max(abs(x), abs(y)) d = (l*3 + x + y) if y >= x else (l - x - y) return (l - 1)**2 + d + start - 1   def show_spiral(n, symbol='# ', start=1, spa...
Give a code snippet in #Python An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
Sorting algorithms/Strand sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#jq
jq
# merge input array with array x by comparing the heads of the arrays # in turn; # if both arrays are sorted, the result will be sorted: def merge(x): length as $length | (x|length) as $xl | if $length == 0 then x elif $xl == 0 then . else . as $in | reduce range(0; $xl + $length) as $z ...
Give a code snippet in #jq Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Erlang
Erlang
  -module( write_float_arrays ).   -export( [task/0, to_a_text_file/3, to_a_text_file/4] ).   task() -> File = "afile", Xs = [1.0, 2.0, 3.0, 1.0e11], Ys = [1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791], Options = [{xprecision, 3}, {yprecision, 5}], to_a_text_file( File, Xs, Ys, Options ), {ok, ...
Give a code snippet in #Erlang Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2,...
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.
#PicoLisp
PicoLisp
(for P (collect 'jerseyNum '+Players 99) (put!> P 'name "Smith, Steve") (put!> P 'score 42) (put!> P 'active T) )
Give a code snippet in #PicoLisp 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Randomize Dim n As Integer = Int(Rnd * 10) + 1 Dim guess As Integer Print "Guess which number I've chosen in the range 1 to 10" Print Do Input " Your guess : "; guess If n = guess Then Print "Well guessed!" End End If Loop
Give a code snippet in #FreeBASIC Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue...
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.
#Nim
Nim
  from algorithm import reverse   const Table = [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2], [7, 0, 9, 2, 1, 5, 4, 8, 6, 3], [4, 2, 0, 6, 8, 7, 1, 3, 5, 9], [1, 7, 5, 0, 9, 8, 3, 4, 2, 6], [6, 1, 2, 3, 0, 4, 5, 9, 7, 8], [3, 6, 7, 4, 2, 0, 9, 5, 8, 1], ...
Give a code snippet in #Nim 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
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Clojure
Clojure
(def arabic->roman (partial clojure.pprint/cl-format nil "~@R"))   (arabic->roman 147) ;"CXXIII" (arabic->roman 99) ;"XCIX"
Give a code snippet in #Clojure Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a v...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#BQN
BQN
SumSqDgt ← +´2⋆˜ •Fmt-'0'˙ Happy ← ⟨⟩{𝕨((⊑∊˜ )◶⟨∾𝕊(SumSqDgt⊢),1=⊢⟩)𝕩}⊢ 8↑Happy¨⊸/↕50
Give a code snippet in #BQN From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Action.21
Action!
DEFINE MAX_COUNT="100" INT ARRAY stack(MAX_COUNT) INT stackSize   PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC InitStack() stackSize=0 RETURN   BYTE FUNC IsEmpty() IF stackSize=0 THEN RETURN (1)...
Give a code snippet in #Action.21 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#R
R
sieve <- function(n) { if (n < 2) integer(0) else { primes <- rep(T, n) primes[[1]] <- F for(i in seq(sqrt(n))) { if(primes[[i]]) { primes[seq(i * i, n, i)] <- F } } which(primes) } }   sieve(1000)
Give a code snippet in #R This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algor...
christopher/rosetta-code
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Nim
Nim
import strutils   iterator tokenize(text: string; sep: openArray[string]): tuple[token: string, isSep: bool] = var i, lastMatch = 0 while i < text.len: for j, s in sep: if text[i..text.high].startsWith s: if i > lastMatch: yield (text[lastMatch ..< i], false) yield (s, true) lastMa...
Give a code snippet in #Nim It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Ada
Ada
with Ada.Text_IO;   procedure Letter_Frequency is Counters: array (Character) of Natural := (others => 0); -- initialize all Counters to 0 C: Character; File: Ada.Text_IO.File_Type;   begin Ada.Text_IO.Open(File, Mode => Ada.Text_IO.In_File, Name => "letter_frequency.adb"); while not Ada.Text_...
Give a code snippet in #Ada Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assig...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Sidef
Sidef
func roman2arabic(roman) {   var arabic = 0 var last_digit = 1000   static m = Hash( I => 1, V => 5, X => 10, L => 50, C => 100, D => 500, M => 1000, )   roman.uc.chars.map{m{_} \\ 0}.each { |digit| if (last_digit < digit) {...
Give a code snippet in #Sidef Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, st...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#SkookumScript
SkookumScript
print("Hello world!")
Give a code snippet in #SkookumScript Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard...
christopher/rosetta-code
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares
Numbers which are not the sum of distinct squares
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... ) Most positive integers can be generated as the sum of 1 or more distinct integer squares. 1 == 1 5 == 4 + 1 25 == 16 + 9 77 == 36 + 25 + 16 103 == 49 + 25 + 16 + 9 + 4 Ma...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program {   // recursively permutates the list of squares to seek a matching sum static bool soms(int n, IEnumerable<int> f) { if (n <= 0) return false; if (f.Contains(n)) return true; switch(n.CompareTo(f.Sum())) { case 1:...
Give a code snippet in #C.23 Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... ) Most positive integers can be generated as the sum of 1 or more distinct integer squares. 1 == 1 5 == 4 + 1 25 == 16 + 9 77 == 36 + 25 + 16 1...
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...
#TOML
TOML
str = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF."
Give a code snippet in #TOML 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/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.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace CastingOutNines { public static class Helper { public static string AsString<T>(this IEnumerable<T> e) { var it = e.GetEnumerator();   StringBuilder builder = new StringBuilder(); ...
Give a code snippet in #C.23 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 other...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#M2000_Interpreter
M2000 Interpreter
  Module Non_continuous_subsequences (item$(), display){ Function positions(n) { function onebit { =lambda b=false (&c)-> { =b :if c then b~:c=not b } } dim k(n)=onebit(), p(n) m=true flush for i=1 to 2^n { for j=0 to n-1 :p(j)= k(j)(&m) :next m1=p(0) m2=0 for j=1 to n-1 if m2 t...
Give a code snippet in #M2000_Interpreter Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between ...
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...
#Tcl
Tcl
lassign $argv head while { [gets stdin line] >= 0 } { foreach word [regexp -all -inline {[A-Za-z]+} $line] { dict incr wordcount [string tolower $word] } }   set sorted [lsort -stride 2 -index 1 -int -decr $wordcount] foreach {word count} [lrange $sorted 0 [expr {$head * 2 - 1}]] { puts "$count\t$wo...
Give a code snippet in #Tcl 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Maxima
Maxima
/* goto */ block(..., label, ..., go(label), ...);   /* throw, which is like trapping errors, and can do non-local jumps to return a value */ catch(..., throw(value), ...);   /* error trapping */ errcatch(..., error("Bad luck!"), ...);
Give a code snippet in #Maxima Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have m...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
in-pair: if = :nil dup: false drop else: @in-pair &> swap &< dup   get-last lst: get-from lst -- len lst   lis-sub pile i di: for j range 0 -- len pile: local :pj get-from pile j if > &< get-last pj di: push-to pj & di if j get-last get-from pile -- j :nil return push-to pile [ & di get-last get-last...
Give a code snippet in #D.C3.A9j.C3.A0_Vu Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#SQL
SQL
SELECT ' SSS\ ' AS s, ' QQQ\ ' AS q, 'L\ ' AS l FROM dual UNION ALL SELECT 'S \|', 'Q Q\ ', 'L | ' FROM dual UNION ALL SELECT '\SSS ', 'Q Q |', 'L | ' FROM dual UNION ALL SELECT ' \ S\', 'Q Q Q |', 'L | ' from dual union all select ' SSS |', ...
Give a code snippet in #SQL Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program simpleWin64.s link with X11 library */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "...
Give a code snippet in #AArch64_Assembly Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { a=Stack Stack a { Data 100,200, 300 } Stack a { While not empty { Read N Print N } } } Checkit  
Give a code snippet in #M2000_Interpreter 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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Ruby
Ruby
puts ['apple', 'orange'].length # or .size
Give a code snippet in #Ruby Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter freque...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS
HTTPS
Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request task, and also the task on HTT...
#Scala
Scala
import scala.io.Source   object HttpsTest extends App { System.setProperty("http.agent", "*")   Source.fromURL("https://sourceforge.net").getLines.foreach(println) }
Give a code snippet in #Scala Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Arturo
Arturo
menu: function [items][ selection: neg 1 while [not? in? selection 1..size items][ loop.with:'i items 'item -> print ~"|i+1|. |item|" inp: input "Enter a number: " if numeric? inp -> selection: to :integer inp ] print items\[selection-1] ]   menu ["fee fie" "huff and puf...
Give a code snippet in #Arturo Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the str...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Swift
Swift
let dog = "Benjamin" let Dog = "Samba" let DOG = "Bernie" println("The three dogs are named \(dog), \(Dog), and \(DOG).")
Give a code snippet in #Swift Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Sa...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#D.C3.A9j.C3.A0_Vu
Déjà Vu
try: bogus catch name-error:  !print "There is *no* :bogus in the current context" return !print "You won't see this."
Give a code snippet in #D.C3.A9j.C3.A0_Vu
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Tcl
Tcl
package require ripemd160   puts [ripemd::ripemd160 -hex "Rosetta Code"]
Give a code snippet in #Tcl RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCI...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#V
V
[1 2 3 4] [dup *] map
Give a code snippet in #V Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code