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/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#F.C5.8Drmul.C3.A6
Fōrmulæ
# We will compute the sum exactly   # Computing an approximation of a rationnal (giving a string) # Value is truncated toward zero Approx := function(x, d) local neg, a, b, n, m, s; if x < 0 then x := -x; neg := true; else neg := false; fi; a := NumeratorRat(x); b := DenominatorRat(x); n := QuoInt(a, b); ...
Give a code snippet in #F.C5.8Drmul.C3.A6 Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Pascal
Pascal
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
Give a code snippet in #Pascal Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Arturo
Arturo
data: { 3/13/2009 CostaRica 5.1 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 }   define :earthquake [date place magnitude][]   print first sort.descending.by:'magnitude map split.lines data => [to :earthquake split.words &]
Give a code snippet in #Arturo Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#D
D
import std.file: remove;   void main() { remove("data.txt"); }
Give a code snippet in #D Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#C.2B.2B
C++
#include <iostream> #include <set> #include <vector> #include <iterator> #include <algorithm> typedef std::set<int> set_type; typedef std::set<set_type> powerset_type;   powerset_type powerset(set_type const& set) { typedef set_type::const_iterator set_iter; typedef std::vector<set_iter> vec; typedef vec::iterato...
Give a code snippet in #C.2B.2B A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Giv...
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...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program priorqueue.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ NBMAXIELEMENTS, 100   /*******************************************/ /* Structures ...
Give a code snippet in #ARM_Assembly 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 ...
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...
#Tcl
Tcl
proc main {} { fconfigure stdout -buffering none set length 4   puts "I have chosen a number from $length unique digits from 1 to 9 arranged in a random order. You need to input a $length digit, unique digit number as a guess at what I have chosen "   while true { set word [generateWord $len...
Give a code snippet in #Tcl 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 gu...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
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 |...
#ECL
ECL
  LogicalOperations(BOOLEAN A,BOOLEAN B) := FUNCTION ANDit := A AND B; ORit  := A OR B; NOTA  := NOT A; XORit := (A OR B) AND NOT (A AND B); DS  := DATASET([{A,B,'A AND B is:',ANDit}, {A,B,'A OR B is:',ORit}, {A,B,'NOT A is:',NOTA}, {A,B,'A XOR B i...
Give a code snippet in #ECL 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 Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Maxima
Maxima
f: openw("/output.txt"); close(f);   f: openw("output.txt"); close(f);   /* Maxima has no function to create directories, but one can use the underlying Lisp system */   :lisp (mapcar #'ensure-directories-exist '("docs/" "/docs/"))
Give a code snippet in #Maxima In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Objeck
Objeck
  use XML;   bundle Default { class Test { function : Main(args : String[]) ~ Nil { in := String->New(); in->Append("<inventory title=\"OmniCorp Store #45x10^3\">"); in->Append("<section name=\"health\">"); in->Append("<item upc=\"123456789\" stock=\"12\">"); in->Append("<name>Invisi...
Give a code snippet in #Objeck Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#Nim
Nim
  import re, strformat, strutils   type TokenKind = enum tkUnknown = "UNKNOWN_TOKEN", tkMul = "Op_multiply", tkDiv = "Op_divide", tkMod = "Op_mod", tkAdd = "Op_add", tkSub = "Op_subtract", tkNeg = "Op_negate", tkLt = "Op_less", tkLte = "Op_lessequal", tkGt = "Op_greater", t...
Give a code snippet in #Nim Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or sca...
christopher/rosetta-code
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Dart
Dart
  import 'dart:math'; void main() {   int x1; for(x1=1;x1<1000000;x1++){ int x; int i,y,y1,l1,z,l; double o,o1,o2,o3; x=pow(x1,2); for(i=0;;i++) {z=pow(10,i); if(x%z==x)break;} if(i.isEven) { y=pow(10,i/2); l=x%y; o=x/y; o=o-l/y; o3=o; for(int j=0;j<4;j++) { if(o%10==0) o=o/10; ...
Give a code snippet in #Dart A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#jq
jq
  # The number of prime factors (as in prime factorization) def numfactors: . as $num | reduce range(1; 1 + sqrt|floor) as $i (null; if ($num % $i) == 0 then ($num / $i) as $r | if $i == $r then .+1 else .+2 end else . end );   # Output: a stream def A06954: foreach range(1; i...
Give a code snippet in #jq Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactl...
christopher/rosetta-code
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. 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) In logic, a three-valued logic (also trivalent, ternary, or trinary...
#Python
Python
class Trit(int): def __new__(cls, value): if value == 'TRUE': value = 1 elif value == 'FALSE': value = 0 elif value == 'MAYBE': value = -1 return super(Trit, cls).__new__(cls, value // (abs(value) or 1))   def __repr__(self): if self >...
Give a code snippet in #Python This page uses content from Wikipedia. The original article was at Ternary logic. 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) In logic, a three-valued logic (als...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#REXX
REXX
/*REXX program computes/display the left factorial (or its dec. width) of N (or a range)*/ parse arg bot top inc . /*obtain optional arguments from the CL*/ if bot=='' | bot=="," then bot= 1 /*Not specified: Then use the default.*/ if top=='' | top=="," then top= bot ...
Give a code snippet in #REXX Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Haskell
Haskell
import Text.PhoneticCode.Soundex   main :: IO () main = mapM_ print $ ((,) <*> soundexSimple) <$> ["Soundex", "Example", "Sownteks", "Ekzampul"]
Give a code snippet in #Haskell Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#PL.2FI
PL/I
  constrain: procedure options (main); declare 1 point (100), 2 x fixed binary, 2 y fixed binary; declare (i, j, a, b, c) fixed binary;   j = 0; do i = 1 to 100; a = 30*random()-15; b = 30*random()-15; c = sqrt(a**2 + b**2); if abs(c) >= 10 & abs(c) <= 15 then ...
Give a code snippet in #PL.2FI Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" ci...
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
#AutoIt
AutoIt
ConsoleWrite("Hello world!" & @CRLF)
Give a code snippet in #AutoIt 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/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#Julia
Julia
const limits = [3:10, 11:18, 19:36, 37:54, 55:86, 87:118]   function periodic_table(n) (n < 1 || n > 118) && error("Atomic number is out of range.") n == 1 && return [1, 1] n == 2 && return [1, 18] 57 <= n <= 71 && return [8, n - 53] 89 <= n <= 103 && return [9, n - 85] row, limitstart, limitsto...
Give a code snippet in #Julia Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#SNOBOL4
SNOBOL4
define('rfact(n)') :(rfact_end) rfact rfact = le(n,0) 1 :s(return) rfact = n * rfact(n - 1) :(return) rfact_end
Give a code snippet in #SNOBOL4 Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#Ada
Ada
with Ada.Containers.Indefinite_Vectors; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.Text_IO;   procedure Abbreviations is   package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Ada.Text_...
Give a code snippet in #Ada The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or delet...
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...
#Fortran
Fortran
MODULE Exp_Mod IMPLICIT NONE   INTERFACE OPERATOR (.pow.) ! Using ** instead would overload the standard exponentiation operator MODULE PROCEDURE Intexp, Realexp END INTERFACE   CONTAINS   FUNCTION Intexp (base, exponent) INTEGER :: Intexp INTEGER, INTENT(IN) :: base, exponent INTEGER :: i   IF (...
Give a code snippet in #Fortran 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 p...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#APL
APL
symdiff ← ∪~∩
Give a code snippet in #APL Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#11l
11l
V c = 1 L(n) 1..15 print(c) c = 2 * (2 * n - 1) * c I/ (n + 1)
Give a code snippet in #11l Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  fo...
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.
#AWK
AWK
  # syntax: GAWK -f ROOTS_OF_UNITY.AWK BEGIN { pi = 3.1415926 for (n=2; n<=5; n++) { printf("%d: ",n) for (root=0; root<=n-1; root++) { real = cos(2 * pi * root / n) imag = sin(2 * pi * root / n) printf("%8.5f %8.5fi",real,imag) if (root != n-1) { printf(", ") } ...
Give a code snippet in #AWK 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/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...
#Visual_Basic_.NET
Visual Basic .NET
Module Program Sub Main() Const ROWS = 10 Const COLS = 10   ' Initialize with seed 0 to get deterministic output (may vary across .NET versions, though). Dim rand As New Random(0)   ' VB uses max index array declarations Dim nums(ROWS - 1, COLS - 1) As Integer   ...
Give a code snippet in #Visual_Basic_.NET 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#PowerShell
PowerShell
  function Find-UnimplementedTask { [CmdletBinding()] [OutputType([string[]])] Param ( [Parameter(Mandatory=$true, Position=0)] [string] $Language )   $url = "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_$Language" $web = Invoke-WebR...
Give a code snippet in #PowerShell Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string demosort(selectionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") end     procedure selectionsort(X,op) #: return sorted list ascending(or descending) local i,m   op := sortop(op,X) ...
Give a code snippet in #Icon_and_Unicon Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modified_random_distribution
Modified random distribution
Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating rand...
#Ada
Ada
with Ada.Text_Io; with Ada.Numerics.Float_Random; with Ada.Strings.Fixed;   procedure Modified_Distribution is   Observations : constant := 20_000; Buckets  : constant := 25; Divider  : constant := 12; Char  : constant Character := '*';   generic with function Modifier (X : Float) re...
Give a code snippet in #Ada Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following ...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#MBS
MBS
! A pling in a line starts a comment   INT n:=5  ! Comments can appear at the end of a line   /* A comment block can also be defined using climbstar and starclimb symbols. This allows comments to be stretched across several lines */
Give a code snippet in #MBS Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#J
J
derangement=: (A.&i.~ !)~ (*/ .~: # [) i. NB. task item 1 subfactorial=: ! * +/@(_1&^ % !)@i.@>: NB. task item 3
Give a code snippet in #J A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Lucid
Lucid
gcd(n,m) where z = [% n, m %] fby if x > y then [% x - y, y %] else [% x, y - x%] fi; x = hd(z); y = hd(tl(z)); gcd(n, m) = (x asa x*y eq 0) fby eod; end
Give a code snippet in #Lucid Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#Delphi.2FPascal
Delphi/Pascal
program AveragesMeanSquare;   {$APPTYPE CONSOLE}   uses Types;   function MeanSquare(aArray: TDoubleDynArray): Double; var lValue: Double; begin Result := 0;   for lValue in aArray do Result := Result + (lValue * lValue); if Result > 0 then Result := Sqrt(Result / Length(aArray)); end;   begin Writeln...
Give a code snippet in #Delphi.2FPascal Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Hy
Hy
(import [numpy [ones column-stack]] [numpy.random [randn]] [numpy.linalg [lstsq]])   (setv n 1000) (setv x1 (randn n)) (setv x2 (randn n)) (setv y (+ 3 (* 1 x1) (* -2 x2) (* .25 x1 x2) (randn n)))   (print (first (lstsq (column-stack (, (ones n) x1 x2 (* x1 x2))) y)))
Give a code snippet in #Hy Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . ...
christopher/rosetta-code
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} ) ...
#Nim
Nim
import lenientops import math import nimPNG   const MaxBrightness = 255   type Pixel = int16 # Used instead of byte to be able to store negative values.   #---------------------------------------------------------------------------------------------------   func convolution*[normalize: static bool](input: seq[Pixel]...
Give a code snippet in #Nim Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y ...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Clojure
Clojure
(apply str (map (partial format "%02x") (.digest (doto (java.security.MessageDigest/getInstance "MD5") .reset (.update (.getBytes "The quick brown fox jumps over the lazy dog"))))))
Give a code snippet in #Clojure Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than th...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Tcl
Tcl
proc isleap1 {year} { return [expr {($year % 4 == 0) && (($year % 100 != 0) || ($year % 400 == 0))}] } isleap1 1988 ;# => 1 isleap1 1989 ;# => 0 isleap1 1900 ;# => 0 isleap1 2000 ;# => 1
Give a code snippet in #Tcl Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#Julia
Julia
# v0.6   function numrevgame() l = collect(1:9) while issorted(l) shuffle!(l) end score = 0 println("# Number reversal game") while !issorted(l) print("$l\nInsert the index up to which to revert: ") n = parse(Int, readline()) reverse!(l, 1, n) score += 1 end p...
Give a code snippet in #Julia Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Rust
Rust
fn step_up() { while !step() { step_up(); } }
Give a code snippet in #Rust From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function dete...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Visual_Basic
Visual Basic
'Knapsack problem/0-1 - 12/02/2017 Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer   Private Sub Form_Load() Dim i As Integer, j As Integer DataList = Array("map", ...
Give a code snippet in #Visual_Basic A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it wi...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Pike
Pike
import Stdio;   int main(){ write(file_size("input.txt") + "\n"); write(file_size("/input.txt") + "\n"); }
Give a code snippet in #Pike Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Cuban_primes
Cuban primes
The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   primes of the form:   n3 - ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1 Dim primes As List(Of Long) = {3L, 5L}.ToList()   Sub Main(args As String()) Const cutOff As Integer = 200, bigUn As Integer = 100000, tn As String = " cuban prime" Console.WriteLine("The first {0:n0}{1}s:", cutOff, tn) Dim c As Integer = 0, showEach As Boole...
Give a code snippet in #Visual_Basic_.NET The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#REXX
REXX
/*REXX program computes and displays humble numbers, also will display counts of sizes.*/ parse arg n m . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/ if m=='' | m=="," then m= 60 ...
Give a code snippet in #REXX Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above ...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#D
D
main() { print(new Date.fromEpoch(0,new TimeZone.utc())); }
Give a code snippet in #D Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scene...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Ursala
Ursala
strip = ~&j   #cast %s   test = strip('she was a soul stripper. she took my heart','aei')
Give a code snippet in #Ursala Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Forth
Forth
  20 constant date-size create max-dates date-size 100 * allot variable max-out variable counter   stdin value input   : process ( addr len -- ) 8 /string over 3 s" OUT" compare 0= if 1 counter +! counter @ max-out @ > if counter @ max-out ! drop 5 + date-size max-dates place else counter @...
Give a code snippet in #Forth A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a che...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#VBA
VBA
'N-queens problem - non recursive & structured - vba - 26/02/2017 Sub n_queens() Const l = 15 'number of queens Const b = False 'print option Dim a(l), s(l), u(4 * l - 2) Dim n, m, i, j, p, q, r, k, t, z For i = 1 To UBound(a): a(i) = i: Next i For n = 1 To l m = 0 i = 1 ...
Give a code snippet in #VBA Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tou...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Python
Python
import random   def count(w1,wnew): return sum(c1==c2 for c1,c2 in zip(w1, wnew))   def best_shuffle(w): wnew = list(w) n = len(w) rangelists = (list(range(n)), list(range(n))) for r in rangelists: random.shuffle(r) rangei, rangej = rangelists for i in rangei: for j in rangej...
Give a code snippet in #Python Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time...
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,...
#Standard_ML
Standard ML
  (* create first array and assign elements *) -val first = Array.tabulate (10,fn x=>x+10) ; val first = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array   (* assign to array 'second' *) -val second=first ; val second = fromList[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]: int array   (* retrieve 5th element *) ...
Give a code snippet in #Standard_ML 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#Icon_and_Unicon
Icon and Unicon
  $include "distribution-checker.icn"   # return a uniformly distributed number from 1 to 7, # but only using a random number in range 1 to 5. procedure die_7 () while rnd := 5*?5 + ?5 - 6 do { if rnd < 21 then suspend rnd % 7 + 1 } end   procedure main () if verify_uniform (create (|die_7()), 1000000, 0.01) ...
Give a code snippet in #Icon_and_Unicon Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#6502_Assembly
6502 Assembly
PRHEX EQU $FDDA ; <= REPLACE THIS WITH THE PRHEX ROUTINE FOR YOUR MACHINE   string EQU $EC length EQU $EE crc0 EQU $FA crc1 EQU $FB crc2 EQU $FC crc3 EQU $FD table0 EQU $9200 table1 EQU $9300 table2 EQU $9400 table3 EQU $9500 ORG $9114 LDA #<text STA string LDA #>text STA string+1 LDA #$2b ; length ...
Give a code snippet in #6502_Assembly Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1
Minimum positive multiple in base 10 using only 0 and 1
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum pos...
#Phix
Phix
with javascript_semantics function b10(integer n) if n=1 then return "1" end if integer NUM = n+1, count = 0, ten = 1, x sequence val = repeat(0,NUM), pow = repeat(0,NUM) -- -- Calculate each 10^k mod n, along with all possible sums that can be -- made from it and the things we've s...
Give a code snippet in #Phix Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phras...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have b...
#Gambas
Gambas
sWindow As New String[4] '________________________ Public Sub Form_Open()   Manipulate   End '________________________ Public Sub Manipulate() Dim siDelay As Short = 2   Me.Show Print "Show" Wait siDelay   sWindow[0] = Me.Width sWindow[1] = Me.Height sWindow[2] = Me.X sWindow[3] = Me.y   Me.Hide Print "Hidden" CompareW...
Give a code snippet in #Gambas Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window o...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Quackery
Quackery
/O> $ "1.2.3.4.5" $->n ... not if [ $ "not a valid integer" fail ] ... 1+ ... number$ echo$ ... Problem: not a valid integer Quackery Stack: 12345 Return stack: {[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 4} /O> $ "12345" $->n ... not if [ $ "not a valid integer" fail ] ... 1+ ... nu...
Give a code snippet in #Quackery Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Python
Python
try: from functools import reduce except: pass   def mdroot(n): 'Multiplicative digital root' mdr = [n] while mdr[-1] > 9: mdr.append(reduce(int.__mul__, (int(dig) for dig in str(mdr[-1])), 1)) return len(mdr) - 1, mdr[-1]   if __name__ == '__main__': print('Number: (MP, MDR)\n======...
Give a code snippet in #Python The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#AutoHotkey
AutoHotkey
length:=4, i:=0, S:=P(9,length)   Gui, Add, Text, w83 vInfo, Think of a %length%-digit number with no duplicate digits. Gui, Add, Edit, w40 vBulls Gui, Add, Text, x+3, Bulls Gui, Add, Edit, xm w40 vCows Gui, Add, Text, x+3, Cows Gui, Add, Button, xm w83 Default vDefault, Start Gui, Add, Edit, ym w130 r8 vHistory ReadOn...
Give a code snippet in #AutoHotkey Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only ...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#UNIX_Shell
UNIX Shell
queue_push() { typeset -n q=$1 shift q+=("$@") }   queue_pop() { if queue_empty $1; then print -u2 "queue $1 is empty" return 1 fi typeset -n q=$1 print "${q[0]}" # emit the value of the popped element q=( "${q[@]:1}" ) # and remove the first element from the que...
Give a code snippet in #UNIX_Shell Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#D
D
void main() { import std.stdio, std.algorithm;   [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2] .sort() .uniq .writeln; }
Give a code snippet in #D 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: runCode (in string: code) is func local var char: ch is ' '; var integer: bottles is 0; var integer: accumulator is 0; begin for ch range code do case ch of when {'H'}: writeln("Hello, world!"); when {'Q'}: writeln(code); when {'9...
Give a code snippet in #Seed7 Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Scala
Scala
Stream from 1 foreach println
Give a code snippet in #Scala Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations li...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"TIMERLIB"   DIM Buckets%(100) FOR i% = 1 TO 100 : Buckets%(i%) = RND(10) : NEXT   tid0% = FN_ontimer(10, PROCdisplay, 1) tid1% = FN_ontimer(11, PROCflatten, 1) tid2% = FN_ontimer(12, PROCroughen, 1)   ON ERROR PROCcleanup : REPORT : PRINT : END ON CLOSE PRO...
Give a code snippet in #BBC_BASIC Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of al...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Go
Go
package main   import "fmt"   type vector []float64   func (v vector) add(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi + v2[i] } return r }   func (v vector) sub(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi...
Give a code snippet in #Go Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (leng...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#TXR
TXR
@(collect) @ (coll)@{item /[^$]+/}@(end) @(end) @; nc = number of columns @; pi = padded items (data with row lengths equalized with empty strings) @; cw = vector of max column widths @; ce = center padding @(bind nc @[apply max [mapcar length item]]) @(bind pi @(mapcar (op append @1 (repeat '("") (- nc (length @1))))...
Give a code snippet in #TXR Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left ...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
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 |...
#FutureBasic
FutureBasic
window 1, @"Logical Operations", (0,0,480,270)   Boolean a, b   text ,,,,, 43   print @"In FB, the Boolean constants _true or YES = 1, _false or NO = 0" print fn StringByPaddingToLength( @"", 39, @"-", 0 )   print @"a\tb\tand\tor\txor\tnand\tnor" print fn StringByPaddingToLength( @"", 39, @"-", 0 )   a = NO  : b = NO  ...
Give a code snippet in #FutureBasic 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 Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Vala
Vala
int i = 1024; while (i > 0) { stdout.printf("%d\n", i); i /= 2; }
Give a code snippet in #Vala Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Python
Python
>>> from array import array >>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'), ('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])] >>> for typecode, initializer in argslist: a = array(typecode, initializer) print a del a     array('l') array('c', 'hello world') array('u', u'hello \u2641') array('...
Give a code snippet in #Python Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example of Currying in a specific la...
#Visual_Basic_.NET
Visual Basic .NET
Option Explicit On Option Infer On Option Strict On   Module Currying ' The trivial curry. Function Curry(Of T1, TResult)(func As Func(Of T1, TResult)) As Func(Of T1, TResult) ' At least satisfy the implicit contract that the result isn't reference-equal to the original function. Return Function...
Give a code snippet in #Visual_Basic_.NET This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonst...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
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 |...
#REXX
REXX
/*REXX program prompts for two integers, compares them, and displays the results.*/ numeric digits 2000 /*for the users that really go ka─razy.*/ @=copies('─', 20) /*eyeball catcher for the user's eyen. */ a=getInt(@ 'Please enter your 1st integer:') ...
Give a code snippet in #REXX 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#.D0.9C.D0.9A-61.2F52
МК-61/52
ПП 54 С/П ПП 66 С/П ИП0 ИП3 ИП6 П3 -> П0 -> П6 ИП1 ИП4 ИП7 П4 -> П1 -> П7 ИП2 ИП5 ИП8 П5 -> П2 -> П8 ПП 66 ИП6 ИП7 ИП8 П2 -> П1 -> П0 ИП9 ИПA ИПB П5 -> П4 -> П3 ПП 54 С/П ПП 66 С/П ИП0 ИП3 * ИП1 ИП4 * + ИП2 ИП5 * + В/О ИП1 ИП5 * ИП2 ИП4 * - П9 ИП2 ИП3 * ИП0 ИП5 * - ПA ИП0 ИП4 * ИП1 ИП3 * - ПB В/О
Give a code snippet in #.D0.9C.D0.9A-61.2F52 A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Forth
Forth
4096 constant max-line   : third ( A b c -- A b c A ) >r over r> swap ;   : read-lines ( fileid -- ) begin pad max-line third read-line throw while pad swap ( fileid c-addr u ) \ string excludes the newline 2drop repeat 2drop ;
Give a code snippet in #Forth Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#PHP
PHP
<?php $stdin = fopen("php://stdin", "r"); $allowed = array(1 => 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock');   for(;;) { foreach ($allowed as $id => $name) { echo " $id: $name\n"; } echo "Which is from the four pigs: "; $stdin_string = fgets($stdin, 4096); if (isset($allowed[(...
Give a code snippet in #PHP Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string...
christopher/rosetta-code
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Arturo
Arturo
fileExtensions: map ["zip" "rar" "7z" "gz" "archive" "A##"] => ["." ++ lower]   hasExtension?: function [file][ in? extract.extension lower file fileExtensions ]   files: ["MyData.a##" "MyData.tar.Gz" "MyData.gzip" "MyData.7z.backup" "MyData..." "MyData"]   loop files 'file -> print [file "=> hasExtensi...
Give a code snippet in #Arturo File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of exten...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Sidef
Sidef
func is_pernicious(n) { n.sumdigits(2).is_prime }   say is_pernicious.first(25).join(' ') say is_pernicious.grep(888_888_877..888_888_888).join(' ')
Give a code snippet in #Sidef A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Groovy
Groovy
def sumMul = { n, f -> BigInteger n1 = (n - 1) / f; f * n1 * (n1 + 1) / 2 } def sum35 = { sumMul(it, 3) + sumMul(it, 5) - sumMul(it, 15) }
Give a code snippet in #Groovy Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#E
E
__makeInt("1234", 10).next().toString(10)
Give a code snippet in #E Task Increment a numerical string.
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...
#SQL
SQL
  /* This code is an implementation of "Determination if a string has all the same characters" in SQL ORACLE 19c p_in_str -- input string */ WITH FUNCTION same_characters_in_string(p_in_str IN varchar2) RETURN varchar2 IS v_que varchar2(32767) := p_in_str; v_res varchar2(32767); v_first varchar2(1); ...
Give a code snippet in #SQL 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 st...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#ALGOL_W
ALGOL W
for n := 1 until 100 do begin % show the largest proper divisors for n = 1..100 % for j := n div 2 step -1 until 2 do begin if n rem j = 0 then begin writeon( i_w := 3, s_w := 0, j ); goto foundLargestProperDivisor end if_n_rem_j_eq_0 end for_j; writeon( i_w := 3, s_w...
Give a code snippet in #ALGOL_W Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Visual_Basic_.NET
Visual Basic .NET
Dim x = 5 Dim ptrX As IntPtr ptrX = Marshal.AllocHGlobal(Marshal.SizeOf(GetType(Integer))) Marshal.StructureToPtr(5, ptrX, False) Dim addressX = ptrX.ToInt64
Give a code snippet in #Visual_Basic_.NET 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Octave
Octave
function r = browniantree(xsize, ysize = xsize, numparticle = 1000) r = zeros(xsize, ysize, "uint8"); r(unidrnd(xsize), unidrnd(ysize)) = 1;   for i = 1:numparticle px = unidrnd(xsize-1)+1; py = unidrnd(ysize-1)+1; while(1) dx = unidrnd(2) - 1; dy = unidrnd(2) - 1; if ( (dx+px < 1) |...
Give a code snippet in #Octave Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initi...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Pony
Pony
use "random"   actor Main let _env: Env let _rand: MT = MT // Mersenne Twister let _target: String = "METHINKS IT IS LIKE A WEASEL" let _possibilities: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " let _c: U16 = 100 // number of spawn per generation let _min_mutate_rate: F64 = 0.09 let _perfect_fitness: USize = ...
Give a code snippet in #Pony Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its ...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Ela
Ela
xs = [1,2,3] ys = [4,5,6] xs ++ ys
Give a code snippet in #Ela Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Pascal
Pascal
sub prompt { my $prompt = shift; while (1) { print "\n", $prompt, ": "; # type ^D, q, quit, quagmire, etc to quit defined($_ = <STDIN>) and !/^\s*q/ or exit;   return $_ if /^\s*\d+\s*$/s; $prompt = "Please give a non-negative integer"; } }   my $tgt = int(rand prompt("Hola! Please tell me the upper bound"...
Give a code snippet in #Pascal Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: h...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#EasyLang
EasyLang
len f[] 9 state = 0 textsize 14 # func init . . linewidth 2 clear color 666 move 34 4 line 34 80 move 62 4 line 62 80 move 10 28 line 86 28 move 10 56 line 86 56 linewidth 2.5 for i range 9 f[i] = 0 . if state = 1 timer 0.2 . . func draw ind . . c = ind mod 3 r = ind div 3 ...
Give a code snippet in #EasyLang Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWor...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#EGL
EGL
  // 2012-09-26 SysLib.writeStdout(StrLib.formatDate(DateTimeLib.currentDate(), "yyyy-MM-dd")); // Wednesday, September 26, 2012 SysLib.setLocale("en", "US"); SysLib.writeStdout(StrLib.formatDate(DateTimeLib.currentDate(), "EEEE, MMMM dd, yyyy"));  
Give a code snippet in #EGL This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
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...
#PureBasic
PureBasic
#Recursive = 0 ;recursive binary search method #Iterative = 1 ;iterative binary search method #NotFound = -1 ;search result if item not found   ;Recursive Procedure R_BinarySearch(Array a(1), value, low, high) Protected mid If high < low ProcedureReturn #NotFound EndIf   mid = (low + high) / 2 If a(mid)...
Give a code snippet in #PureBasic 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 secr...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#Kotlin
Kotlin
// version 1.1.0 (Linux)   import java.io.FileWriter   fun main(args: Array<String>) { val lp0 = FileWriter("/dev/tape") lp0.write("Hello, world!") lp0.close() }
Give a code snippet in #Kotlin The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Sidef
Sidef
var haystack = %w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo);   %w(Bush Washington).each { |needle| var i = haystack.first_index{|item| item == needle}; if (i >= 0) { say "#{i} #{needle}"; } else { die "#{needle} is not in haystack"; } }
Give a code snippet in #Sidef Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle th...
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...
#C.2B.2B
C++
#include <ggi/ggi.h> #include <set> #include <map> #include <utility> #include <iostream> #include <fstream> #include <string>   #include <unistd.h> // for usleep   enum cell_type { none, wire, head, tail };   // ***************** // * display class * // *****************   // this is just a small wrapper for the ggi i...
Give a code snippet in #C.2B.2B 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 cel...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into ...
#Raku
Raku
constant %dict = 'unixdict.txt'.IO.lines .classify(*.chars) .map({ .key => .value.Set });   sub word_ladder ( Str $from, Str $to ) { die if $from.chars != $to.chars;   my $sized_dict = %dict{$from.chars};   my @workqueue = (($from,),); my $us...
Give a code snippet in #Raku Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the follo...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Oz
Oz
functor import Application QTk at 'x-oz://system/wp/QTk.ozf' define Count = {NewCell 0} Label GUI = td(action:proc {$} {Application.exit 0} end %% exit on close label(text:"There have been no clicks yet." handle:Label) button(text:"Click Me" action:proc {$} Count := @Count + 1 ...
Give a code snippet in #Oz Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Phix
Phix
with javascript_semantics integer swapWins = 0, stayWins = 0, winner, choice, reveal, other atom t0 = time() for game=1 to 1_000_000 do winner = rand(3) choice = rand(3) while 1 do reveal = rand(3) if reveal!=winner and reveal!=choice then exit end if end while stayWins += (choice=...
Give a code snippet in #Phix 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/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...
#Go
Go
package main   import "fmt"   // encoding scheme: // encode to byte array // byte value < 26 means single character: byte value + 'A' // byte value 26..255 means (byte value - 24) copies of next byte func rllEncode(s string) (r []byte) { if s == "" { return } c := s[0] if c < 'A' || c > 'Z' { ...
Give a code snippet in #Go 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 functio...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Maple
Maple
StringTools:-Join(StringTools:-Split("Hello,How,Are,You,Today", ","),".");
Give a code snippet in #Maple Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks re...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#BQN
BQN
Acc ← { 𝕊 sum: {sum+↩𝕩} } x ← Acc 1 X 5 Acc 3 X 2.3
Give a code snippet in #BQN A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passe...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Erlang
Erlang
  -module(fib). -export([fib/1]).   fib(0) -> 0; fib(1) -> 1; fib(N) -> fib(N-1) + fib(N-2).  
Give a code snippet in #Erlang The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Lua
Lua
function sumdigits(n) local sum = 0 while n > 0 do sum = sum + n % 10 n = math.floor(n/10) end return sum end   primegen:generate(nil, 500) aprimes = primegen:filter(function(n) return primegen.tbd(sumdigits(n)) end) print(table.concat(aprimes, " ")) print("Count:", #aprimes)
Give a code snippet in #Lua Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#C.2B.2B
C++
  #include <iostream> #include <vector> using namespace std; typedef unsigned int uint;   class NarcissisticDecs { public: void makeList( int mx ) { uint st = 0, tl; int pwr = 0, len; while( narc.size() < mx ) { len = getDigs( st ); if( pwr != len ) { pwr = len; fillPower( pwr ); ...
Give a code snippet in #C.2B.2B A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#REXX
REXX
/*REXX program finds and displays N number of anti─primes or highly─composite numbers.*/ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/ maxD= 0 ...
Give a code snippet in #REXX The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Tcl
Tcl
set src "Rosetta Code" set dst $src
Give a code snippet in #Tcl This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty str...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub van_eck { my($init,$max) = @_; my(%v,$k); my @V = my $i = $init; for (1..$max) { $k++; my $t = $v{$i} ? $k - $v{$i} : 0; $v{$i} = $k; push @V, $i = $t; } @V; }   for ( ['A181391', 0], ['A171911', 1], ...
Give a code snippet in #Perl The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured ...
christopher/rosetta-code