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/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#AutoHotkey
AutoHotkey
ZeroDiv(num1, num2) { If ((num1/num2) != "") MsgBox % num1/num2 Else MsgBox, 48, Warning, The result is not valid (Divide By Zero). } ZeroDiv(0, 3) ; is ok ZeroDiv(3, 0) ; divize by zero alert
Give a code snippet in #AutoHotkey Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π ...
#Maple
Maple
agm:=proc(n) local a:=1,g:=evalf(sqrt(1/2)),s:=0,p:=4,i; for i to n do a,g:=(a+g)/2,sqrt(a*g); s+=p*(a*a-g*g); p+=p od; 4*a*a/(1-s) end:   Digits:=100000: d:=agm(16)-evalf(Pi): evalf[10](d); # 4.280696926e-89415
Give a code snippet in #Maple Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summariz...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Erlang
Erlang
9> U = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢". [120088,120107,120102,120096,120108,120097,120098] 10> erlang:length(U). 7
Give a code snippet in #Erlang Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme con...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func bigInteger: min (in bigInteger: a, in bigInteger: b, in bigInteger: c) is func result var bigInteger: min is 0_; begin if a < b then min := a; else min := b; end if; if c < min then min := c; end if; end func;...
Give a code snippet in #Seed7 Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numb...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS/Authenticated
HTTPS/Authenticated
The goal of this task is to demonstrate HTTPS requests with authentication. Implementations of this task should not use client certificates for this: that is the subject of another task.
#Python
Python
#!/usr/bin/python # -*- coding: utf-8 -*-   from mechanize import Browser   USER_AGENT = "Mozilla/5.0 (X11; U; Linux i686; tr-TR; rv:1.8.1.9) Gecko/20071102 Pardus/2007 Firefox/2.0.0.9"   br = Browser() br.addheaders = [("User-agent", USER_AGENT)]   # remove comment if you get debug output # br.set_debug_redirects(True...
Give a code snippet in #Python The goal of this task is to demonstrate HTTPS requests with authentication. Implementations of this task should not use client certificates for this: that is the subject of another task.
christopher/rosetta-code
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h>   enum { S_NONE, S_LIST, S_STRING, S_SYMBOL };   typedef struct { int type; size_t len; void *buf; } s_expr, *expr;   void whine(const char *s) { fprintf(stderr, "parse error before ==>%.10s\n", s); }   expr parse_string(const char *s, ch...
Give a code snippet in #C S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastru...
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
#R
R
  puz15<-function(scramble.length=100){ m=matrix(c(1:15,0),byrow=T,ncol=4) scramble=sample(c("w","a","s","d"),scramble.length,replace=T) for(i in 1:scramble.length){ m=move(m,scramble[i]) } win=F turn=0 while(!win){ print.puz(m) newmove=getmove() if(newmove=="w"|newmove=="a"|newmove=="s"|n...
Give a code snippet in #R 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/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Kotlin
Kotlin
// version 1.1.2   import java.awt.Color import java.awt.Graphics import javax.swing.JFrame   class FractalTree : JFrame("Fractal Tree") { init { background = Color.black setBounds(100, 100, 800, 600) isResizable = false defaultCloseOperation = EXIT_ON_CLOSE }   private fun d...
Give a code snippet in #Kotlin Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#GAP
GAP
leftOf  :=function(setA, vA, setB, vB) local i; for i in [1..4] do if ( setA[i] = vA) and (setB[i+1] = vB) then return true ;fi; od; return false; end;   nextTo  :=function(setA, vA, setB, vB) local i; for i in [1..4] do if ( setA[i] = vA) and (setB[i+1] = vB) then return true ;fi; if ( setB[i] = vB) and (...
Give a code snippet in #GAP Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five hous...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Lua
Lua
function median (numlist) if type(numlist) ~= 'table' then return numlist end table.sort(numlist) if #numlist %2 == 0 then return (numlist[#numlist/2] + numlist[#numlist/2+1]) / 2 end return numlist[math.ceil(#numlist/2)] end   print(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2})) print(median({4.1, 7.2, 1...
Give a code snippet in #Lua Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#ALGOL_68
ALGOL 68
STRINGa="STRINGa=,q=REPR34;print(a[:8]+q+a+q+a[9:])",q=REPR34;print(a[:8]+q+a+q+a[9:])
Give a code snippet in #ALGOL_68 A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Ada
Ada
with Ada.Text_IO;   procedure Damm_Algorithm is   function Damm (Input : in String) return Boolean is subtype Digit is Character range '0' .. '9';   Table : constant array (Digit, Digit) of Digit := (('0', '3', '1', '7', '5', '9', '8', '6', '4', '2'), ('7', '0', '9', '2', '1', '5', '4...
Give a code snippet in #Ada 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/Resistor_mesh
Resistor mesh
Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ResistanceMatrix[g_Graph] := With[{n = VertexCount[g], km = KirchhoffMatrix[g]}, Table[ ReplacePart[ Diagonal[ DrazinInverse[ ReplacePart[km, k -> UnitVector[n, k]]]], k -> 0], {k, n}] ]   rm = ResistanceMatrix[GridGraph[{10, 10}]];   N[rm[[12, 68]], 40]
Give a code snippet in #Mathematica.2FWolfram_Language Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Ruby
Ruby
  # run_encode("aaabbbbc") #=> [["a", 3], ["b", 4], ["c", 1]] def run_encode(string) string .chars .chunk{|i| i} .map {|kind, array| [kind, array.length]} end   # run_decode([["a", 3], ["b", 4], ["c", 1]]) #=> "aaabbbbc" def run_decode(char_counts) char_counts .map{|char, count| char * count} .j...
Give a code snippet in #Ruby Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a funct...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Yabasic
Yabasic
  cadena1$ = "qwertyuiop"   //Determinar si la primera cadena comienza con la segunda cadena cadena2$ = "qwerty" if left$(cadena1$, len(cadena2$)) = cadena2$ then print "'", cadena1$, "' comienza con '", cadena2$, "'" else print "'", cadena1$, "' no comienza con '", cadena2$, "'" end if   //Determinar si la pri...
Give a code snippet in #Yabasic Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
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 ...
#Visual_Basic_.NET
Visual Basic .NET
' Sorting algorithms/Cocktail sort with shifting bounds - VB.Net Private Sub Cocktail_Shaker_Sort() Dim A(20), tmp As Long 'or Integer Long Single Double String Dim i, beginIdx, endIdx, newBeginIdx, newEndIdx As Integer 'Generate the list For i = LBound(A) To UBound(A) A...
Give a code snippet in #Visual_Basic_.NET 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 sor...
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"
#Modula-2
Modula-2
MODULE try;   FROM Arguments IMPORT GetArgs, ArgTable, GetEnv; FROM InOut IMPORT WriteCard, WriteLn, WriteString;   VAR count, item : SHORTCARD; storage : ArgTable;   BEGIN GetArgs (count, storage); WriteString ('Count ='); WriteCard (count, 4); WriteLn; item := 0; ...
Give a code snippet in #Modula-2 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/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...
#Python
Python
import math   def solvePell(n): x = int(math.sqrt(n)) y, z, r = x, 1, x << 1 e1, e2 = 1, 0 f1, f2 = 0, 1 while True: y = r * z - y z = (n - y * y) // z r = (x + y) // z   e1, e2 = e2, e1 + e2 * r f1, f2 = f2, f1 + f2 * r   a, b = f2 * x + e2, f2 ...
Give a code snippet in #Python 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Ruby
Ruby
class Maybe def initialize(value) @value = value end   def map if @value.nil? self else Maybe.new(yield @value) end end end   Maybe.new(3).map { |n| 2*n }.map { |n| n+1 } #=> #<Maybe @value=7>   Maybe.new(nil).map { |n| 2*n }.map { |n| n+1 } #=> #<Maybe @value=nil>   Maybe.new(3).map...
Give a code snippet in #Ruby Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and retu...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#C
C
  #include<conio.h>   #define COLOURS 8   int main() { int colour=0,i,j,MAXROW,MAXCOL; struct text_info tInfo; gettextinfo(&tInfo); MAXROW = tInfo.screenheight; MAXCOL = tInfo.screenwidth; textbackground(BLACK); //8 colour constants are defined clrscr();   for(colour=0;colour<COLOURS;colour++) { getch();...
Give a code snippet in #C Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#OpenEdge.2FProgress
OpenEdge/Progress
/* using a longchar to read and write to, can also be file, memptr, stream */ DEFINE VARIABLE lcjson AS LONGCHAR NO-UNDO.   /* temp-table defines object, can also be dataset */ DEFINE TEMP-TABLE example FIELD blue AS INTEGER EXTENT 2 FIELD ocean AS CHARACTER . CREATE example. ASSIGN example.blue [1] = ...
Give a code snippet in #OpenEdge.2FProgress Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Sidef
Sidef
func evalArithmeticExp(s) {   func evalExp(s) {   func operate(s, op) { s.split(op).map{|c| Number(c) }.reduce(op) }   func add(s) { operate(s.sub(/^\+/,'').sub(/\++/,'+'), '+') }   func subtract(s) { s.gsub!(/(\+-|-\+)/,'-')   i...
Give a code snippet in #Sidef Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a si...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Python
Python
>>> import queue >>> pq = queue.PriorityQueue() >>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")): pq.put(item)     >>> while not pq.empty(): print(pq.get_nowait())     (1, 'Solve RC tasks') (2, 'Tax return') (3, 'Clear drains') (4, 'Feed cat') (5, 'Ma...
Give a code snippet in #Python A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in pri...
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
#Draco
Draco
proc nonrec main() void: writeln("Hello world!") corp
Give a code snippet in #Draco Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#PARI.2FGP
PARI/GP
newpoint(x)={ myT=x; myS=0; myN=1; [myT,myS]/myN }; addpoint(x)={ myT+=x; myN++; myS+=(myN*x-myT)^2/myN/(myN-1); [myT,myS]/myN }; addpoints(v)={ print(newpoint(v[1])); for(i=2,#v,print(addpoint(v[i]))); print("Mean: ",myT/myN); print("Standard deviation: ",sqrt(myS/myN)) }; addpoints([2,4,4,4,5,...
Give a code snippet in #PARI.2FGP Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the f...
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...
#Scala
Scala
import scala.annotation.tailrec import scala.collection.parallel.mutable import scala.compat.Platform   object GenuineEratosthenesSieve extends App { def sieveOfEratosthenes(limit: Int) = { val (primes: mutable.ParSet[Int], sqrtLimit) = (mutable.ParSet.empty ++ (2 to limit), math.sqrt(limit).toInt) @tailrec ...
Give a code snippet in #Scala 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   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#REXX
REXX
/*REXX program checks for balanced brackets [ ] ─── some fixed, others random.*/ parse arg seed . /*obtain optional argument from the CL.*/ if datatype(seed,'W') then call random ,,seed /*if specified, then use as RANDOM seed*/ @.=0; yesNo.0= right('not OK', 50) ...
Give a code snippet in #REXX Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-ne...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Ruby
Ruby
digits = ("1".."9").to_a   ar = ["+", "-", ""].repeated_permutation(digits.size).filter_map do |op_perm| str = op_perm.zip(digits).join str unless str.start_with?("+") end res = ar.group_by{|str| eval(str)}   puts res[100] , ""   sum, solutions = res.max_by{|k,v| v.size} puts "#{sum} has #{solutions.size} solutions...
Give a code snippet in #Ruby Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular ...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Emacs_Lisp
Emacs Lisp
(require 'cl-lib)   (defun even-or-odd-p (n) (if (cl-evenp n) 'even 'odd))   (defun even-or-odd-p (n) (if (zerop (% n 2)) 'even 'odd))   (message "%d is %s" 3 (even-or-oddp 3)) (message "%d is %s" 2 (even-or-oddp 2))
Give a code snippet in #Emacs_Lisp Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#Ruby
Ruby
strings = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]   strings.each do |str| pos = str.empty? ? nil : str =~ /[^#{str[0]}]/ print "#{str.inspect} (size #{str.size}): " puts pos ? "first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}." ...
Give a code snippet in #Ruby Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each s...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#REXX
REXX
/* REXX *************************************************************** * 30.08.2013 Walter Pachl derived from Java **********************************************************************/ Call time 'R' switchWins = 0; stayWins = 0 Do plays = 1 To 1000000 doors.=0 r=r3() doors.r=1 choice = r3() Do Until shown<...
Give a code snippet in #REXX Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Phix
Phix
without js -- none such in a browser, that I know of ?getenv("PATH")
Give a code snippet in #Phix Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#Ceylon
Ceylon
abstract class Cell(shared Character char) of emptyCell | head | tail | conductor {   shared Cell output({Cell*} neighbors) => switch (this) case (emptyCell) emptyCell case (head) tail case (tail) conductor case (conductor) (neighbors.count(head.equals) in...
Give a code snippet in #Ceylon Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#NewLISP
NewLISP
(let (str "rosetta") ;; strip first char (println (1 str)) ;; strip last char (println (0 -1 str)) ;; strip both first and last characters (println (1 -1 str)))
Give a code snippet in #NewLISP The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#Applesoft_BASIC
Applesoft BASIC
0ST$(0)="YOU MUST TAKE 1, 2, OR 3 TOKENS.":FORHEAP=12TO1STEP-4:PRINT"THERE ARE "HEAP" TOKENS REMAINING.":FORI=0TO1:INPUT"HOW MANY WOULD YOU LIKE TO TAKE?";T%:I=T%>0ANDT%<4:PRINTST$(I):NEXTI:PRINT"ON MY TURN I WILL TAKE "4-T%" TOKENS.":NEXTHEAP
Give a code snippet in #Applesoft_BASIC Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each pla...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#Forth
Forth
Name Type Description --------------------------------------------- TIB integer Terminal Input Buffer address U0 integer current user area address >IN integer holds offset into TIB, used for parsing BASE integer holds number conversion radix STATE integer holds compil...
Give a code snippet in #Forth Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Scope/Function_names_and_labels
Scope/Function names and labels
Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
#jq
jq
def NAME: def NAME: 2; 1, NAME; # this calls the inner function, not the outer function   NAME # => 1, 2
Give a code snippet in #jq Task Explain or demonstrate the levels of visibility of function names and labels within the language. See also Variables for levels of scope relating to visibility of program variables Scope modifiers for general scope modification facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#PureBasic
PureBasic
If OpenConsole("ls") rp=RunProgram("ls", "-l", "",#PB_Program_Open|#PB_Program_Read) While ProgramRunning(rp) If AvailableProgramOutput(rp) r$+ReadProgramString(rp)+#LF$ EndIf Wend CloseProgram(rp) PrintN(r$) Input() EndIf  
Give a code snippet in #PureBasic Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Maple
Maple
s := "12345"; s := convert(parse(s)+1, string);
Give a code snippet in #Maple Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Bracmat
Bracmat
( ( I = buffer . (new$=):?freshEmptyBuffer & ' ( buffer avg . ( avg = L S n . 0:?L:?S & whl ' ( !arg:%?n ?arg & !n+!S:?S & 1+!L:?L ) ...
Give a code snippet in #Bracmat Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average i...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#FOCAL
FOCAL
01.10 A "ORDER",O;S S=2^(O+1) 01.20 F X=0,S;S L(X)=0 01.30 S L(S/2)=1 01.40 F I=1,S/2;D 2;D 3 01.90 Q   02.10 F X=1,S-1;D 2.3 02.20 T !;R 02.30 I (L(X)),2.4,2.5 02.40 T " " 02.50 T "*"   03.10 F X=0,S;S K(X)=FABS(L(X-1)-L(X+1)) 03.20 F X=0,S;S L(X)=K(X)
Give a code snippet in #FOCAL Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Picat
Picat
  go => println("Write two integers (and CR)"), println(read_int()+read_int()).  
Give a code snippet in #Picat A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separate...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Fantom
Fantom
class Main { public static Void main () { rows := 10 cols := 10 // create and fill an array of given size with random numbers Int[][] array := [,] rows.times { row := [,] cols.times { row.add(Int.random(1..20)) } array.add (row) } // now do the search try { ...
Give a code snippet in #Fantom Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is m...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Phix
Phix
constant W = machine_word(), {RTN,PREVEBP} = iff(W=4?{8,20}:{16,40}) procedure show_stack() sequence symtab, symtabN integer rtn atom prev_ebp #ilASM{ [32] lea edi,[symtab] call :%opGetST -- [edi]=symtab (ie our local:=the real symtab) mov edi,[ebp+20] ...
Give a code snippet in #Phix Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the pla...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Scala
Scala
def mean(a:Array[Double])=a.sum / a.size def stddev(a:Array[Double])={ val sum = a.fold(0.0)((a, b) => a + math.pow(b,2)) math.sqrt((sum/a.size) - math.pow(mean(a),2)) } def hist(a:Array[Double]) = { val grouped=(SortedMap[Double, Array[Double]]() ++ (a groupBy (x => math.rint(x*10)/10))) grouped.map(v => (...
Give a code snippet in #Scala Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature
Numerical integration/Gauss-Legendre Quadrature
In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting function W ( x ) {\displaystyle ...
#J
J
NB. returns coefficents for yth-order Legendre polynomial getLegendreCoeffs=: verb define M. if. y<:1 do. 1 {.~ - y+1 return. end. (%~ <:@(,~ +:) -/@:* (0;'') ,&> [: getLegendreCoeffs&.> -&1 2) y )   getPolyRoots=: 1 {:: p. NB. returns the roots of a polynomial getGaussLegendreWeights...
Give a code snippet in #J In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting function ...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#PARI.2FGP
PARI/GP
long(a,b)={ a=eval(Vec(a)); b=eval(Vec(b)); my(c=vector(#a+#b),carry=0); for(i=1,#a, for(j=1,#b, c[i+j]+=a[i]*b[j] ) ); forstep(i=#c,1,-1, c[i] += carry; carry = c[i] \ 10; c[i] = c[i] % 10 ); for(i=1,#c, if(c[i], return(concat(apply(s->Str(s),vector(#c+1-i,j,c[i+j-1]))))) ...
Give a code snippet in #PARI.2FGP Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   26...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make -- Run application. do create input_file.make_open_read ("input.txt") create output_file.make_open_write ("output.txt")   from input_file.read_character ...
Give a code snippet in #Eiffel File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#mIRC_Scripting_Language
mIRC Scripting Language
var %value = 3 if (%value isnum) { echo -s %value is numeric. }
Give a code snippet in #mIRC_Scripting_Language Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_sentence_from_book
Random sentence from book
Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too). Keep a...
#Julia
Julia
""" weighted random pick of items in a Dict{String, Int} where keys are words, values counts """ function weightedrandompick(dict, total) n = rand(1:total) for (key, value) in dict n -= value if n <= 0 return key end end return last(keys(dict)) end   let """ Read ...
Give a code snippet in #Julia Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence ter...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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
# In case your jq does not have "until" defined: def until(cond; next): def _until: if cond then . else (next|_until) end; _until;
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/JortSort
JortSort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Java
Java
public class JortSort { public static void main(String[] args) { System.out.println(jortSort(new int[]{1, 2, 3})); }   static boolean jortSort(int[] arr) { return true; } }
Give a code snippet in #Java Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#Mathematica.2F_Wolfram_Language
Mathematica/ Wolfram Language
Import["file.ppm","PPM"]  
Give a code snippet in #Mathematica.2F_Wolfram_Language Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to conve...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits ...
#PureBasic
PureBasic
Structure fileDataBits bitsToWrite.i bitsToRead.i outputByte.i inputByte.i EndStructure #BitsPerByte = SizeOf(Byte) * 8 #BitsPerInteger = SizeOf(Integer) * 8   Global Dim fileBitMask(8) Define i, x For i = 0 To 8 fileBitMask(i) = x x = (x << 1) + 1 Next   Global NewMap fileDataBits.fileDataBits() Procedure ...
Give a code snippet in #PureBasic The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", t...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Lingo
Lingo
-- in some movie script ---------------------------------------- -- Composes 2 call-functions, returns a new call-function -- @param {symbol|instance} f -- @param {symbol|instance} g -- @return {instance} ---------------------------------------- on compose (f, g) return script("Composer").new(f, g) end
Give a code snippet in #Lingo Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g ...
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...
#Delphi
Delphi
  program Write_float_arrays_to_a_text_file;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.IoUtils;   function ToString(v: TArray<Double>): TArray<string>; var fmt: TFormatSettings; begin fmt := TFormatSettings.Create('en-US'); SetLength(Result, length(v));   for var i := 0 to High(v) do Result[i]...
Give a code snippet in #Delphi 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/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 ...
#Qi
Qi
(define insert X [] -> [X] X [Y|Ys] -> [X Y|Ys] where (<= X Y) X [Y|Ys] -> [Y|(insert X Ys)])   (define insertion-sort [] -> [] [X|Xs] -> (insert X (insertion-sort Xs)))   (insertion-sort [6 8 5 9 3 2 1 4 7])  
Give a code snippet in #Qi 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/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...
#Python
Python
def binary_search(l, value): low = 0 high = len(l)-1 while low <= high: mid = (low+high)//2 if l[mid] > value: high = mid-1 elif l[mid] < value: low = mid+1 else: return mid return -1
Give a code snippet in #Python A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret ...
christopher/rosetta-code
http://rosettacode.org/wiki/Honeycombs
Honeycombs
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position...
#ActionScript
ActionScript
  package {   import flash.display.GraphicsPathCommand; import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat;   /** * A honeycomb. */ public class Honeycomb extends Sprite {   /** * The sine of...
Give a code snippet in #ActionScript The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in column...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Nim
Nim
import strutils   proc rot13(c: char): char = case toLowerAscii(c) of 'a'..'m': chr(ord(c) + 13) of 'n'..'z': chr(ord(c) - 13) else: c   for line in stdin.lines: for c in line: stdout.write rot13(c) stdout.write "\n"
Give a code snippet in #Nim Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make do sequence (1, 27) end   sequence (lower, upper: INTEGER) -- Sequence of primes from 'lower' to 'upper'. require lower_positive: lower > 0 upper_positive: upper > 0 lower_smaller: lower < upper local i: INTEGER do io.put_string ("Seq...
Give a code snippet in #Eiffel Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#RLaB
RLaB
// specify polynomial >> n = 10; >> a = zeros(1,n+1); a[1] = 1; a[n+1] = -1; >> polyroots(a) radius roots success >> polyroots(a).roots -0.309016994 + 0.951056516i -0.809016994 + 0.587785252i -1 + 5.95570041e-23i -0.809016994 - 0.587785252i -0.309016994 - 0.951056516i ...
Give a code snippet in #RLaB The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#BASIC256
BASIC256
function min(a, b) if a < b then return a else return b end function   function d6() #simulates a marked regular hexahedron coming to rest on a plane return 1 + int(rand * 6) end function   function roll_stat() #rolls four dice, returns the sum of the three highest a = d6() : b = d6() : c = d6() : d = d6() retur...
Give a code snippet in #BASIC256 RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6...
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#PureBasic
PureBasic
EnableExplicit   Procedure.b CheckPW(pw.s) Define flag.b=#True, tmp.b=#False, c.c, s.s, i.i For c='a' To 'z' tmp=Bool(FindString(pw,Chr(c))) If tmp : Break : EndIf Next flag & tmp tmp=#False For c='A' To 'Z' tmp=Bool(FindString(pw,Chr(c))) If tmp : B...
Give a code snippet in #PureBasic Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
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 ...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( "1.3.6.1.4.1.11.2.17.19.3.4.0.10" "1.3.6.1.4.1.11.2.17.5.2.0.79" "1.3.6.1.4.1.11.2.17.19.3.4.0.4" "1.3.6.1.4.1.11150.3.4.0.1" "1.3.6.1.4.1.11.2.17.19.3.4.0.1" "1.3.6.1.4.1.11150.3.4.0" )   len for var i i get "." " " subst split len for var j j get tonum j se...
Give a code snippet in #Phixmonti 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/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#11l
11l
F sierpinski_carpet(n) V carpet = [String(‘#’)] L 1..n carpet = carpet.map(x -> x‘’x‘’x) [+] carpet.map(x -> x‘’x.replace(‘#’, ‘ ’)‘’x) [+] carpet.map(x -> x‘’x‘’x) R carpet.join("\n")   print(sierpinski_carpet(3))
Give a code snippet in #11l Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## #...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#TXR
TXR
@(cases) hey @a how are you @(or) hey @b long time no see @(end)
Give a code snippet in #TXR Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Fortran
Fortran
module anim   type animal end type animal   type, extends(animal) :: dog end type dog   type, extends(animal) :: cat end type cat   type, extends(dog) :: lab end type lab   type, extends(dog) :: collie end type collie   end module anim
Give a code snippet in #Fortran This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent typ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 algor...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program combSort.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file ...
Give a code snippet in #ARM_Assembly Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 co...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#Ada
Ada
generic type Number is range <>; package Generic_Rational is type Rational is private;   function "abs" (A : Rational) return Rational; function "+" (A : Rational) return Rational; function "-" (A : Rational) return Rational; function Inverse (A : Rational) return Rational;   function "+"...
Give a code snippet in #Ada Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Go
Go
package main   import "fmt"   func main() { sieve(1e6) if !search(6, 1e6, "left", func(n, pot int) int { return n % pot }) { panic("997?") } if !search(6, 1e6, "right", func(n, _ int) int { return n / 10 }) { panic("7393?") } }   var c []bool   func sieve(ss int) { c = make([]boo...
Give a code snippet in #Go A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#R
R
# Method pow <- function(x, y) { x <- as.numeric(x) y <- as.integer(y) prod(rep(x, y)) } #Operator "%pow%" <- function(x,y) pow(x,y)   pow(3, 4) # 81 2.5 %pow% 2 # 6.25
Give a code snippet in #R Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Lua
Lua
function sleeprint(n) local t0 = os.time() while os.time() - t0 <= n do coroutine.yield(false) end print(n) return true end   coroutines = {} for i=1, #arg do wrapped = coroutine.wrap(sleeprint) table.insert(coroutines, wrapped) wrapped(tonumber(arg[i])) end   done = false while not done do done =...
Give a code snippet in #Lua 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/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#FreeBASIC
FreeBASIC
  Type Point As Double x,y End Type   Type Line As Point s,f'start/finish End Type   Function isleft(L As Line,p As Point) As Long Return -Sgn((L.s.x-L.f.x)*(p.y-L.f.y)-(p.x-L.f.x)*(L.s.y-L.f.y)) End Function   Function segmentintersections(L1 As Line,L2 As Line) As Long If isleft(L2,L1.s) = is...
Give a code snippet in #FreeBASIC The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#C.2B.2B
C++
#include <array> #include <vector>   // These headers are only needed for the demonstration #include <algorithm> #include <iostream> #include <iterator> #include <string>   // This is a template function that works for any array-like object template <typename Array> void demonstrate(Array& array) { // Array element a...
Give a code snippet in #C.2B.2B This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and ret...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#JavaScript
JavaScript
console.log(new Date()) // => Sat, 28 May 2011 08:22:53 GMT console.log(Date.now()) // => 1306571005417 // Unix epoch
Give a code snippet in #JavaScript Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#8th
8th
: epsilon 1.0e-12 ;   with: n   : iter \ n1 n2 -- n1 n2 2dup * sqrt >r + 2 / r> ;   : agn \ n1 n2 -- n repeat iter 2dup epsilon ~= not while! drop ;   "agn(1, 1/sqrt(2)) = " . 1 1 2 sqrt / agn "%.10f" s:strfmt . cr   ;with bye  
Give a code snippet in #8th This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to ...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#PureBasic
PureBasic
EnableExplicit Dim cG.i(21) Dim nG.i(21) Define.i n, Gen   DataSection Data.i 0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0 EndDataSection For n=1 To 20 Read.i cG(n) Next   OpenConsole() Repeat Print("Generation "+Str(Gen)+": ") For n=1 To 20 Print(Chr(95-cG(n)*60)) Next Gen +1 PrintN("") For n=1 To 20 ...
Give a code snippet in #PureBasic Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the cur...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#FreeBASIC
FreeBASIC
' version 18-10-2016 ' started with SHA-1/FIPS-180-1 ' but used the BBC BASIC native version to finish. ' compile with: fbc -s console   Function SHA_1(test_str As String) As String   Dim As String message = test_str ' strings are passed as ByRef's   Dim As Long i, j Dim As UByte Ptr ww1 Dim As UInteger<32>...
Give a code snippet in #FreeBASIC SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits ...
#Raku
Raku
sub encode-ascii(Str $s) { my @b = flat $s.ords».fmt("%07b")».comb; @b.push(0) until @b %% 8; # padding Buf.new: gather while @b { take reduce * *2+*, (@b.pop for ^8) } }   sub decode-ascii(Buf $b) { my @b = flat $b.list».fmt("%08b")».comb; @b.shift until @b %% 7; # remove padding @b = gathe...
Give a code snippet in #Raku The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the ou...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Seed7
Seed7
const type: matrix is array array float;   const func matrix: (in matrix: left) * (in matrix: right) is func result var matrix: result is matrix.value; local var integer: i is 0; var integer: j is 0; var integer: k is 0; var float: accumulator is 0.0; begin if length(left[1]) <> length(rig...
Give a code snippet in #Seed7 Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Octave
Octave
function h = imagehistogram(imago) if ( isgray(imago) ) for j = 0:255 h(j+1) = numel(imago( imago == j )); endfor else error("histogram on gray img only"); endif endfunction   % test im = jpgread("Lenna100.jpg"); img = rgb2gray(im); h = imagehistogram(img); % let's try to show the histogram bar(...
Give a code snippet in #Octave Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must h...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#Python
Python
  #!/bin/python3 from itertools import zip_longest   # This is wrong, it works only on specific examples def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))     # Demonstration code: print(beadsort([5,3,1,7,4,1,1]))  
Give a code snippet in #Python 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/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Draco
Draco
proc nonrec find([*] int A; word top; int n) bool: word i; bool found; i := 0; found := false; while i < top and not found do found := A[i] = n; i := i + 1 od; found corp   proc nonrec gen_next([*] int A; word n) int: int add, sub; add := A[n-1] + n; sub := A[n-1]...
Give a code snippet in #Draco The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Picat
Picat
go =>    %  % Test predicates  % S = "ablewasiereisawelba", assert("test1",$is_palindrome(S)), assert_failure("test2",$not is_palindrome(S)),   assert("test3",$member(1,1..10)), assert_failure("test4",$member(1,1..10)), % bad test nl,    %  % Test functions  % assert("test5",$2+2,4), assert_fa...
Give a code snippet in #Picat Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#REXX
REXX
/*REXX pgm demonstrates how to achieve movement of the terminal cursor. */   parse value scrsize() with sd sw /*find the display screen size. */ parse value cursor() with row col /*find where the cursor is now. */   colL=col-1; if colL==0 then colL=sw /*prepare to move cursor to left.*/ call cursor row,...
Give a code snippet in #REXX Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (witho...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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 Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Java
Java
import java.util.LinkedList; import java.util.Queue; ... Queue<Integer> queue = new LinkedList<Integer>(); System.out.println(queue.isEmpty()); // empty test - true // queue.remove(); // would throw NoSuchElementException queue.add(1); queue.add(2); queue.add(3); System.out.println(queue); // ...
Give a code snippet in #Java 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 Create a queue data structure and demonstrate its operations. (For implementations of queu...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#MUMPS
MUMPS
SEDOL NEW A,B SEDOL1 READ !,"Enter the first 6 digits of a SEDOL: ",A SET B=$$SEDOLCHK(A) WRITE !,$SELECT($LENGTH(B)=1:"Full SEDOL is "_A_B,1:B) GOTO SEDOL1 QUIT SEDOLCHK(STOCK) NEW WT,VAL,I,CHK,C,FLAG SET WT="1317391",VAL=0,FLAG=0 FOR I=1:1:6 SET C=$$TOUPPER($EXTRACT(STOCK,I)),VAL=VAL+($$SEDVAL(C)*$EXTRACT(WT...
Give a code snippet in #MUMPS Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842...
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.
#Cach.C3.A9_ObjectScript
Caché ObjectScript
Class Utils.Check [ Abstract ] {   ClassMethod Damm(num As %Integer, mode As %Integer = 1) As %Integer { TRY { I mode=0 RETURN ..Damm(num,2)=0 S res=0, str=num S 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], ...
Give a code snippet in #Cach.C3.A9_ObjectScript 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/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | ...
#Tcl
Tcl
package require Tcl 8.5   proc inRange {x range} { lassign $range a aClosed b bClosed expr {($aClosed ? $a<=$x : $a<$x) && ($bClosed ? $x<=$b : $x<$b)} } proc normalize {A} { set A [lsort -index 0 -real [lsort -index 1 -integer -decreasing $A]] for {set i 0} {$i < [llength $A]} {incr i} { lassign [lind...
Give a code snippet in #Tcl All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#BASIC
BASIC
  ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' Remove File Lines V1.1 ' ' ' ' Developed by A. David Garza Marín in VB-DOS for ' ' RosettaCode. November 30, 2016. ' ' ...
Give a code snippet in #BASIC Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to rem...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Forth
Forth
: fmultiply ( F: a b -- F: c ) F* ; : multiply ( a b -- c ) * ;
Give a code snippet in #Forth A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#ALGOL_W
ALGOL W
begin   long real sum, sum2; integer n;   long real procedure sd (long real value x) ; begin sum  := sum + x; sum2 := sum2 + (x*x); n  := n + 1; if n = 0 then 0 else longsqrt(sum2/n - sum*sum/n/n) end sd;   sum := sum2 := n := 0;   r_format := "A"; r_w...
Give a code snippet in #ALGOL_W Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the fun...
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Raku
Raku
my @dates = { :15day, :5month }, { :16day, :5month }, { :19day, :5month }, { :17day, :6month }, { :18day, :6month }, { :14day, :7month }, { :16day, :7month }, { :14day, :8month }, { :15day, :8month }, { :17day, :8month } ;   # Month can't have a unique day my @filtered = @dates.g...
Give a code snippet in #Raku Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells A...
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#SuperCollider
SuperCollider
// play it in the REPL, evaluating line by line a = RockPaperScissors.new; a.next(Scissors); a.next(Scissors); a.next(Scissors); a.next(Paper);
Give a code snippet in #SuperCollider Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#MAXScript
MAXScript
  numCount = 4 -- number of digits to use   digits = #(1, 2, 3, 4, 5, 6, 7, 8, 9) num = "" while num.count < numCount and digits.count > 0 do ( local r = random 1 digits.count append num (digits[r] as string) deleteitem digits r ) digits = undefined numGuesses = 0 inf = "Rules: \n1. Choose only % unique digits in an...
Give a code snippet in #MAXScript Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Scheme
Scheme
  (for-each (lambda (s) (print (string-join (reverse (string-split s #/ +/))))) (string-split "---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   ...
Give a code snippet in #Scheme Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spa...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#XPL0
XPL0
proc Shuffle(Array, Items, BytesPerItem); int Array, Items, BytesPerItem; int I, J; char Temp(8); [for I:= Items-1 downto 1 do [J:= Ran(I+1); \range [0..I] CopyMem(Temp, Array+I*BytesPerItem, BytesPerItem); CopyMem(Array+I*BytesPerItem, Array+J*BytesPerItem, BytesPerItem); CopyMem(Array+J*BytesPe...
Give a code snippet in #XPL0 The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion
Angles (geometric), normalization and conversion
This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 360 degrees, also shown as 360º ...
#Raku
Raku
  my @units = { code => 'd', name => 'degrees' , number => 360 }, { code => 'g', name => 'gradians', number => 400 }, { code => 'm', name => 'mills' , number => 6400 }, { code => 'r', name => 'radians' , number => tau }, ;   my Code %cvt = (@units X @units).map: -> ($a, $b) { "{$a.<code>}2{$b.<...
Give a code snippet in #Raku This task is about the normalization and/or conversion of (geometric) angles using some common scales. The angular scales that will be used in this task are:   degree   gradian   mil   radian Definitions The angular scales used or referenced here:   turn   is a full turn or 36...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#JavaScript
JavaScript
function GameOfLife () {   this.init = function (turns,width,height) { this.board = new Array(height); for (var x = 0; x < height; x++) { this.board[x] = new Array(width); for (var y = 0; y < width; y++) { this.board[x][y] = Math.round(Math.random()); } } this.turns = turns; }   this.nextGen = f...
Give a code snippet in #JavaScript The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when de...
christopher/rosetta-code