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/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM The trailing semicolon prevents a newline 20 PRINT "Goodbye, World!";
Give a code snippet in #ZX_Spectrum_Basic Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello...
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...
#Rust
Rust
use std::cmp;   struct Item { name: &'static str, weight: usize, value: usize }   fn knapsack01_dyn(items: &[Item], max_weight: usize) -> Vec<&Item> { let mut best_value = vec![vec![0; max_weight + 1]; items.len() + 1]; for (i, it) in items.iter().enumerate() { for w in 1 .. max_weight + 1 {...
Give a code snippet in #Rust 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Ring
Ring
  text = list(2) text[1] = "Hello " text[2] = "world!" see text[1] + text[2] + nl  
Give a code snippet in #Ring This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Cre...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Factor
Factor
USING: combinators.short-circuit formatting kernel math math.parser qw regexp sequences unicode ; IN: rosetta-code.cusip   : cusip-check-digit ( seq -- n ) but-last-slice [ [ dup alpha? [ digit> ] [ "*@#" index 36 + ] if ] dip odd? [ 2 * ] when 10 /mod + ] map-index sum 10 mod 10 swap - 10 mod ;...
Give a code snippet in #Factor This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeri...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#jq
jq
def count(stream): reduce stream as $i (0; .+1);   # To maintain precision: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   def primes: 2, (range(3; infinite; 2) | select(is_prime));   # divisors as an unsorted stream def divisors: if . == 1 then 1 else . as $n | label $out | range(1; $n) as ...
Give a code snippet in #jq Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#PL.2FSQL
PL/SQL
CREATE OR REPLACE FUNCTION rpn_calc(str VARCHAR2) RETURN NUMBER AS TYPE num_aa IS TABLE OF NUMBER INDEX BY PLS_INTEGER; TYPE num_stack IS RECORD (a num_aa, top PLS_INTEGER DEFAULT 0); ns num_stack; pos1 INTEGER := 1; pos2 INTEGER; token VARCHAR2(100); op2 NUMBER; PROCEDURE push(s IN OUT NOCO...
Give a code snippet in #PL.2FSQL Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#JavaScript
JavaScript
function gamma(x) { var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7 ];   var g = 7; if (x < 0.5) { return Math.PI / (Math.sin(Math...
Give a code snippet in #JavaScript Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-i...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Peloton
Peloton
<@ SAI> <@ ITEFORLI3>2121|2008| <@ LETVARCAP>Christmas Day|25-Dec-<@ SAYVALFOR>...</@></@> <@ TSTDOWVARLIT>Christmas Day|1</@> <@ IFF> <@ SAYCAP>Christmas Day <@ SAYVALFOR>...</@> is a Sunday</@><@ SAYKEY>__Newline</@> </@> </@> </@>
Give a code snippet in #Peloton A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years betwee...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_object_at_a_given_address
Create an object at a given address
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 |...
#Tcl
Tcl
package require critcl   # A command to 'make an integer object' and couple it to a Tcl variable critcl::cproc linkvar {Tcl_Interp* interp char* var1} int { int *intPtr = (int *) ckalloc(sizeof(int));   *intPtr = 0; Tcl_LinkVar(interp, var1, (void *) intPtr, TCL_LINK_INT); return (int) intPtr; }   # A c...
Give a code snippet in #Tcl 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/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#Dart
Dart
import 'dart:math'; main() { var nuggets = List<int>.generate(101, (int index) => index); for (int small in List<int>.generate((100 ~/ (6 + 1)), (int index) => index)) { for (int medium in List<int>.generate((100 ~/ (9 + 1)), (int index) => index)) { for (int large in List<int>.generate((100 ~/ (20 + 1)),...
Give a code snippet in #Dart Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNug...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#D
D
import std.algorithm : fold; import std.exception : enforce; import std.format : formattedWrite; import std.numeric : cmp, gcd; import std.range : iota; import std.stdio; import std.traits;   auto abs(T)(T val) if (isNumeric!T) { if (val < 0) { return -val; } return val; }   struct Frac { long n...
Give a code snippet in #D In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions...
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#Icon_and_Unicon
Icon and Unicon
link "factors"   procedure main(A) n := integer(!A) | 61 every write(carmichael3(!n)) end   procedure carmichael3(p1) every (isprime(p1), (h := 1+!(p1-1)), (d := !(h+p1-1))) do if (mod(((h+p1)*(p1-1)),d) = 0, mod((-p1*p1),h) = mod(d,h)) then { p2 := 1 + (p1-1)*(h+p1)/d p3 := ...
Give a code snippet in #Icon_and_Unicon A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task i...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { while (System.`in`.available() > 0) System.`in`.read() println("Goodbye!") }
Give a code snippet in #Kotlin Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var file: aFile is STD_NULL; var string: line is ""; begin aFile := open("input.txt", "r"); while hasNext(aFile) do readln(aFile, line); writeln("LINE: " <& line); end while; end func;
Give a code snippet in #Seed7 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/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...
#PicoLisp
PicoLisp
$ ersatz/pil + : (setq JFrame "javax.swing.JFrame" MAXIMIZED_BOTH (java (public JFrame 'MAXIMIZED_BOTH)) ICONIFIED (java (public JFrame 'ICONIFIED)) Win (java JFrame T "Window") ) -> $JFrame   # Compare for equality : (== Win Win) -> T   # Set window visible (java Win 'setLocation 10...
Give a code snippet in #PicoLisp 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation....
#Ruby
Ruby
rpn = RPNExpression.new("3 4 2 * 1 5 - 2 3 ^ ^ / +") infix = rpn.to_infix ruby = rpn.to_ruby
Give a code snippet in #Ruby Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
toGrayscale[rgb_Image] := ImageApply[#.{0.2126, 0.7152, 0.0722}&, rgb] toFakeRGB[L_Image] := ImageApply[{#, #, #}&, L]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one f...
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#M2000_Interpreter
M2000 Interpreter
  Module WumpusGame { Print "Game: Hunt The Wumpus" Arrows=5 Dim Room(1 to 20) Room(1)=(2,6,5),(3,8,1),(4,10,2),(5,2,3),(1,14,4) Room(6)=(15,1,7),(17,6,8),(7,2,9),(18,8,10),(9,3,11) Room(11)=(19,10,12),(11,4,13),(20,12,14),(5,11,13), (6,16,14) Room(16)=(20,15,17),(16,7,18),(17,...
Give a code snippet in #M2000_Interpreter This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Befunge
Befunge
52*92*1->01p:01g1-:v v *_$101p011p54*21p>:11g1+:01g*01p:11p/21g1-:v v < ^ _$$>\:^ ^ p12_$>+\:#^_$554**/@
Give a code snippet in #Befunge Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
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 ...
#Octave
Octave
  input=[1 2 6 4 2 32 5 5 4 3 3 5 1 2 32 4 4]; output=unique(input);  
Give a code snippet in #Octave 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/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h>   typedef struct lnode_t { struct lnode_t *prev; struct lnode_t *next; int v; } Lnode;   Lnode *make_list_node(int v) { Lnode *node = malloc(sizeof(Lnode)); if (node == NULL) { return NULL; } node->v = v; node->prev = NU...
Give a code snippet in #C The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a p...
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 |...
#Nim
Nim
var x = 12 var xptr = addr(x) # Get address of variable echo cast[int](xptr) # and print it xptr = cast[ptr int](0xFFFE) # Set the address
Give a code snippet in #Nim 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/Thiele%27s_interpolation_formula
Thiele's interpolation formula
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. 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) Thiele's interpolation formula is an interpolation ...
#J
J
  span =: {. - {: NB. head - tail spans =: span\ NB. apply span to successive infixes  
Give a code snippet in #J This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. 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) Thiele's interpolation f...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Haskell
Haskell
import Data.List import Control.Monad   perms :: (Eq a) => [a] -> [[a]] perms [] = [[]] perms xs = [ x:xr | x <- xs, xr <- perms (xs\\[x]) ]   combs :: (Eq a) => Int -> [a] -> [[a]] combs 0 _ = [[]] combs n xs = [ x:xr | x <- xs, xr <- combs (n-1) xs ]   ringCheck :: [Int] -> Bool ringCheck [x0, x1, x2, x3, x4, x5, x6]...
Give a code snippet in #Haskell 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of t...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Rust
Rust
fn pyth(n: u32) -> impl Iterator<Item = [u32; 3]> { (1..=n).flat_map(move |x| { (x..=n).flat_map(move |y| { (y..=n).filter_map(move |z| { if x.pow(2) + y.pow(2) == z.pow(2) { Some([x, y, z]) } else { None } ...
Give a code snippet in #Rust A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Stata
Stata
clear all set obs 1000 gen x=rnormal(1,0.5)
Give a code snippet in #Stata Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Modula-2
Modula-2
MODULE Permute;   FROM Terminal IMPORT Read, Write, WriteLn;   FROM Terminal2 IMPORT WriteString;   CONST MAXIDX = 6; MINIDX = 1;   TYPE TInpCh = ['a'..'z']; TChr = SET OF TInpCh;   VAR n, nl: INTEGER; ch: CHAR; a: ARRAY[MINIDX..MAXIDX] OF CHAR; kt: TChr = TChr{'a'..'f'};   PROCEDURE output; VAR i: INTEGER...
Give a code snippet in #Modula-2 Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   g...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ -1 4 turn 2dup -v fly 1 4 turn 4 wide ' [ 0 0 0 ] colour ' [ 0 0 0 ] fill [ 2dup 2 1 v/ 1 2 arc 2dup -2 1 v/ 1 2 arc 2dup -v 1 2 arc ] 2dup -v 1 2 arc 1 4 turn 2dup 2 1 v/ fly ' [ 0 0 0 ] colour 1 wide ' [ 25...
Give a code snippet in #Quackery One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#C.23
C#
  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class DOCINFOA { [MarshalAs(UnmanagedType.LPStr)] public string pDocName; [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile; [MarshalAs(UnmanagedType.LPStr)] public string pDataType; }   [DllImport("winspool.Drv", En...
Give a code snippet in #C.23 Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#J
J
coclass 'priorityQueue'   PRI=: '' QUE=: ''   insert=:4 :0 p=. PRI,x q=. QUE,y assert. p -:&$ q assert. 1 = #$q ord=: \: p QUE=: ord { q PRI=: ord { p i.0 0 )   topN=:3 :0 assert y<:#PRI r=. y{.QUE PRI=: y}.PRI QUE=: y}.QUE r )
Give a code snippet in #J 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...
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...
#Nim
Nim
import sets, strformat     proc min[T](s: HashSet[T]): T = ## Return the minimal value in a set. if s.card == 0: raise newException(ValueError, "set is empty.") result = T.high for n in s: if n < result: result = n     iterator humbleNumbers(): Positive = ## Yield the successive humble numbers. var ...
Give a code snippet in #Nim 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#mIRC_Scripting_Language
mIRC Scripting Language
var %x = 99 while (%x) { echo -ag %x bottles of beer on the wall echo -ag %x bottles of beer echo -ag Take one down, pass it around dec %x echo -ag %x bottles of beer on the wall }
Give a code snippet in #mIRC_Scripting_Language Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of bee...
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...
#Frink
Frink
  n = eval[input["Enter highest number: "]] results = array[sieve[n]] println[results] println[length[results] + " prime numbers less than or equal to " + n]   sieve[n] := { // Initialize array array = array[0 to n] array@1 = 0   for i = 2 to ceil[sqrt[n]] if array@i != 0 for j = i^2 to n ste...
Give a code snippet in #Frink 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/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Wren
Wren
var bc = Fn.new { |p| var c = List.filled(p+1, 0) var r = 1 var half = (p/2).floor for (i in 0..half) { c[i] = r c[p-i] = r r = (r * (p-i) / (i+1)).floor } var j = p - 1 while (j >= 0) { c[j] = -c[j] j = j - 2 } return c }   var e = "²³⁴⁵⁶⁷".co...
Give a code snippet in #Wren The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the c...
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
#PHP
PHP
<?php // Puzzle 15 Game - Rosseta Code - PHP 7 as the server-side script language.   // This program DOES NOT use cookies.   session_start([ "use_only_cookies" => 0, "use_cookies" => 0, "use_trans_sid" => 1, ]);   class Location { protected $column, $row;   function __construct($column, $row){ $this->colu...
Give a code snippet in #PHP 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/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...
#MontiLang
MontiLang
30 VAR length . 35 VAR height . FOR length 0 ENDFOR 1 0 ARR VAR list . length 1 - VAR topLen . FOR topLen 0 ENDFOR 1 ARR VAR topLst .   DEF getNeighbors 1 - VAR tempIndex . GET tempIndex SWAP tempIndex 1 + VAR tempIndex . GET tempIndex SWAP tempIndex 1 + VAR tempIndex . GET tempIndex SWAP...
Give a code snippet in #MontiLang 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/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Objeck
Objeck
class Ackermann { function : Main(args : String[]) ~ Nil { for(m := 0; m <= 3; ++m;) { for(n := 0; n <= 4; ++n;) { a := Ackermann(m, n); if(a > 0) { "Ackermann({$m}, {$n}) = {$a}"->PrintLine(); }; }; }; }   function : Ackermann(m : Int, n : Int) ~ Int { if...
Give a code snippet in #Objeck The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#Perl
Perl
use ntheory qw(forprimes is_prime);   my $upto = 1e7; my %class = ( safe => [], unsafe => [2] );   forprimes { push @{$class{ is_prime(($_-1)>>1) ? 'safe' : 'unsafe' }}, $_; } 3, $upto;   for (['safe', 35], ['unsafe', 40]) { my($type, $quantity) = @$_; print "The first $quantity $type primes are:\n"; p...
Give a code snippet in #Perl Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't...
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#Rust
Rust
extern crate rand;   use rand::{ThreadRng, thread_rng}; use rand::distributions::{IndependentSample, Range}; use std::collections::HashSet; use std::env; use std::process;   fn help() { println!("usage: average_loop_length <max_N> <trials>"); }   fn main() { let args: Vec<String> = env::args().collect(); le...
Give a code snippet in #Rust Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number t...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#QUACKASM
QUACKASM
  ; Stores result in cell 2; 1 if yes, 0 if no. :YORN PRINT YORNMSG :YORN1 INPUT >2 AND *2,$5F,'Y >2 /YORN2 AND *2,,'N \YORN1 :YORN2 PRINTC *2 PRINTC 13 AND *2,1 >2 RETURN :YORNMSG " (Y/N)? \  
Give a code snippet in #QUACKASM Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pres...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Python
Python
def lookandsay(number): result = ""   repeat = number[0] number = number[1:]+" " times = 1   for actual in number: if actual != repeat: result += str(times)+repeat times = 1 repeat = actual else: times += 1   return result   num = "...
Give a code snippet in #Python The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#PowerBASIC
PowerBASIC
#COMPILER PBWIN 9 #COMPILER PBWIN, PBCC 5
Give a code snippet in #PowerBASIC Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes comput...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#PureBasic
PureBasic
Procedure.s lcs(a$, b$) Protected x$ , lcs$ If Len(a$) = 0 Or Len(b$) = 0 lcs$ = "" ElseIf Right(a$, 1) = Right(b$, 1) lcs$ = lcs(Left(a$, Len(a$) - 1), Left(b$, Len(b$) - 1)) + Right(a$, 1) Else x$ = lcs(a$, Left(b$, Len(b$) - 1)) y$ = lcs(Left(a$, Len(a$) - 1), b$) If Len(x$) > Len(y$) ...
Give a code snippet in #PureBasic Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be s...
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#APL
APL
carpet←{{⊃⍪/,⌿3 3⍴4 0 4\⊂⍵}⍣⍵⊢⍪'#'}
Give a code snippet in #APL 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/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Lua
Lua
comment_symbols = ";#"   s1 = "apples, pears # and bananas" s2 = "apples, pears ; and bananas"   print ( string.match( s1, "[^"..comment_symbols.."]+" ) ) print ( string.match( s2, "[^"..comment_symbols.."]+" ) )
Give a code snippet in #Lua Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whi...
christopher/rosetta-code
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a...
#jq
jq
# To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   # Input is $d, the number of consecutive digits, 2 <= $d <= 9 # $max is the number of superd numbers to be emitted. def superd($number): . as $d | tostring as $s | ($s * $d) as ...
Give a code snippet in #jq A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#VBA
VBA
Option Explicit   Sub Main() Dim a a = Array(1, 15, 19, 25, 13, 0, -125, 9) Debug.Print Max_VBA(a) End Sub   Function Max_VBA(Arr As Variant) As Long Dim i As Long, temp As Long temp = Arr(LBound(Arr)) For i = LBound(Arr) + 1 To UBound(Arr) If Arr(i) > temp Then temp = Arr(i) Next i Max_VBA = te...
Give a code snippet in #VBA Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. 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 number theory, a Wieferich prime is a prime number p such th...
#Forth
Forth
: prime? ( n -- ? ) here + c@ 0= ; : notprime! ( n -- ) here + 1 swap c! ;   : prime_sieve { n -- } here n erase 0 notprime! 1 notprime! n 4 > if n 4 do i notprime! 2 +loop then 3 begin dup dup * n < while dup prime? if n over dup * do i notprime! dup 2* +loop then ...
Give a code snippet in #Forth This page uses content from Wikipedia. The original article was at Wieferich prime. 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 number theory, a Wieferich prim...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Excel
Excel
FNOVERHALFCARTESIANPRODUCT =LAMBDA(f, LAMBDA(n, LET( ixs, SEQUENCE(n, n, 1, 1),   REM, "1-based indices.", x, 1 + MOD(ixs - 1, n), y, 1 + QUOTIENT(ixs - 1, n),   IF(x >= y, f(x)(y), "" ) ) ) )
Give a code snippet in #Excel Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#F.23
F#
module SudokuBacktrack   //Helpers let tuple2 a b = a,b let flip f a b = f b a let (>>=) f g = Option.bind g f   /// "A1" to "I9" squares as key in values dictionary let key a b = $"{a}{b}"   /// Cross product of elements in ax and elements in bx let cross ax bx = [| for a in ax do for b in bx do key a b |]   // const...
Give a code snippet in #F.23 Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#min
min
("" split reverse "" join) :reverse-str
Give a code snippet in #min Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty s...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_simple
Abbreviations, simple
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. For this task, the following   command table   will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 ...
#C
C
#include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   const char* command_table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " "3 xEdit ...
Give a code snippet in #C 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. For this task, the following   command table   will be used: add 1 alter 3 backup 2 bott...
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#D
D
import std.stdio, std.algorithm, std.array, std.conv;   void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc { if (M.empty) return; immutable nrows = M.length; immutable ncols = M[0].length;   size_t lead; foreach (immutable r; 0 .. nrows) { if (ncols <= lead) retu...
Give a code snippet in #D Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (f...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#MUMPS
MUMPS
ISHAPPY(N)  ;Determines if a number N is a happy number  ;Note that the returned strings do not have a leading digit unless it is a happy number IF (N'=N\1)!(N<0) QUIT "Not a positive integer" NEW SUM,I  ;SUM is the sum of the square of each digit  ;I is a loop variable  ;SEQ is the sequence of previously checked SUM...
Give a code snippet in #MUMPS From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#Kotlin
Kotlin
// version 1.1.2   typealias Matrix = Array<DoubleArray>   fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } // permutation val q = IntArray(n) { it } // inverse permutation val d = IntArray(n) { -1 } // direction = 1 or -1 var sign = 1 val perms = mutableLi...
Give a code snippet in #Kotlin For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while ...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#UNIX_Shell
UNIX Shell
#!/bin/bash function sum_of_square_digits { local -i n="$1" sum=0 while (( n )); do local -i d=n%10 let sum+=d*d let n=n/10 done echo "$sum" }   function is_happy? { local -i n="$1" local seen=() while (( n != 1 )); do if [ -n "${seen[$n]}" ]; then return 1 fi seen[n]...
Give a code snippet in #UNIX_Shell From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endle...
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....
#Ceylon
Ceylon
import ceylon.random {   DefaultRandom }   shared void run() {   value mutationRate = 0.05; value childrenPerGeneration = 100; value target = "METHINKS IT IS LIKE A WEASEL"; value alphabet = {' ', *('A'..'Z')}; value random = DefaultRandom();   value randomLetter => random.nextElement(alphabet);   function fitn...
Give a code snippet in #Ceylon 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 it...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_constant_0.5772...
Euler's constant 0.5772...
Task. Compute the Euler constant 0.5772... Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these. Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ f...
#Ruby
Ruby
n = 1e6 p (1..n).sum{ 1.0/_1 } - Math.log(n)
Give a code snippet in #Ruby Task. Compute the Euler constant 0.5772... Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these. Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simpl...
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.)
#Hope
Hope
! All Hope comments begin with "!" and extend to the end of the line
Give a code snippet in #Hope 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/Terminal_control/Display_an_extended_character
Terminal control/Display an extended character
Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
#Perl
Perl
use feature 'say';   # OK as is say '£';   # these need 'binmode needed to surpress warning about 'wide' char binmode STDOUT, ":utf8"; say "\N{FULLWIDTH POUND SIGN}"; say "\x{FFE1}"; say chr 0xffe1;
Give a code snippet in #Perl Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
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
#C
C
#include <stdio.h> #include <stdlib.h>   #define S 10 typedef struct { double v; int fixed; } node;   #define each(i, x) for(i = 0; i < x; i++) node **alloc2(int w, int h) { int i; node **a = calloc(1, sizeof(node*)*h + sizeof(node)*w*h); each(i, h) a[i] = i ? a[i-1] + w : (node*)(a + h); return a; }   void set_bou...
Give a code snippet in #C 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/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#POV-Ray
POV-Ray
camera { perspective location <2.6,2.2,-4.2> look_at <0,-.5,0> aperture .05 blur_samples 100 variance 1/100000 focal_point <2,1,-2>}   light_source{< 60,20,-20> color rgb 2}   sky_sphere { pigment{ gradient z color_map{[0 rgb 0.3][.1 rgb <.7,.8,1>][1 rgb .2]} }}   box { <0,0,0> <3,2,4> texture { pigment...
Give a code snippet in #POV-Ray Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#TXR
TXR
@(defex u0) @(defex u1) @(define baz (x)) @ (cases) @ (bind x "0") @ (throw u0 "text0") @ (or) @ (bind x "1") @ (throw u1 "text1") @ (end) @(end) @(define bar (x)) @ (baz x) @(end) @(define foo ()) @ (next :list @'("0" "1")) @ (collect) @num @ (try) @ (bar num) @ (catch u0 (arg)) @ (ou...
Give a code snippet in #TXR Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange...
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...
#APL
APL
∇ ret←RLL rll;count [1] count←∣2-/((1,(2≠/rll),1)×⍳1+⍴rll)~0 [2] ret←(⍕count,¨(1,2≠/rll)/rll)~' ' ∇  
Give a code snippet in #APL 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 functi...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#BaCon
BaCon
OPTION GUI TRUE PRAGMA GUI gtk3   gui = GUIDEFINE(" \ { type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=200 } \ { type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \ { type=SPIN_BUTTON name=spin parent=box numeric=TRUE } \ { type=BUTTON_BOX name=bb...
Give a code snippet in #BaCon In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI compo...
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.
#COBOL
COBOL
PROGRAM-ID. memory-allocation.   DATA DIVISION. WORKING-STORAGE SECTION. 01 based-data PIC X(20) VALUE "Hello, World!" BASED.   PROCEDURE DIVISION. *> INITIALIZED sets the data item to the VALUE. ALLOCATE based-dat...
Give a code snippet in #COBOL 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/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...
#Standard_ML
Standard ML
fun binary_search cmp (key, arr) = let fun aux slice = if ArraySlice.isEmpty slice then NONE else let val mid = ArraySlice.length slice div 2 in case cmp (ArraySlice.sub (slice, mid), key) of LESS => aux (ArraySlice.subslice (slice, mid+1, NONE)) | GREATER => ...
Give a code snippet in #Standard_ML 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 se...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#DWScript
DWScript
var i : Integer;   for i := 2 to 8 step 2 do PrintLn(i);
Give a code snippet in #DWScript Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
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.
#HicEst
HicEst
FUNCTION zero_divide(num, denom) XEQ( num// "/" // denom, *99) ! on error jump to label 99 zero_divide = 0 ! division OK RETURN   99 zero_divide = 1 END
Give a code snippet in #HicEst 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/Arena_storage_pool
Arena storage pool
Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a reference to the object. The stora...
#Scala
Scala
package require Tcl 8.6 oo::class create Pool { superclass oo::class variable capacity pool busy unexport create constructor args { next {*}$args set capacity 100 set pool [set busy {}] } method new {args} { if {[llength $pool]} { set pool [lassign $pool obj] } else { if {[llength...
Give a code snippet in #Scala Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a refe...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Processing
Processing
  float cX = -0.7; float cY = 0.27015; float zx, zy; float maxIter = 300;   void setup() { size(640, 480); }   void draw() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { zx = 1.5 * (x - width / 2) / (0.5 * width); zy = (y - height / 2) / (0.5 * height); float i = maxIte...
Give a code snippet in #Processing Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
semiPrimeQ[n_Integer] := Module[{factors, numfactors}, factors = FactorInteger[n] // Transpose; numfactors = factors[[2]] // Total  ; numfactors == 2 ]
Give a code snippet in #Mathematica.2FWolfram_Language Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Groovy
Groovy
def varname = 'foo' def value = 42   new GroovyShell(this.binding).evaluate("${varname} = ${value}")   assert foo == 42
Give a code snippet in #Groovy Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Racket
Racket
  #lang racket (require math) (define T matrix-transpose)   (define (fit X y) (matrix-solve (matrix* (T X) X) (matrix* (T X) y)))  
Give a code snippet in #Racket Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . ...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#zkl
zkl
var [const] BN=Import.lib("zklBigNum");   const N=0d100_000; p:=List.createLong(N+1,BN.fp(0),True); // (0,0,...) all different   fcn calc(n,p){ p[n].set(0); // reset array for each run foreach k in ([1..n]){ d:=n - k *(3*k - 1)/2; do(2){ if (d<0) break(2); if (k.isOdd) p[n].add(p[d]); e...
Give a code snippet in #zkl This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#Salmon
Salmon
open_output_text_file("/dev/lp0").print("Hello World!");
Give a code snippet in #Salmon Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With som...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#HicEst
HicEst
DO i = 1, 1E20 ! for i with 16 or more digits: i == i + 1 == loop infinite WRITE() "SPAM" ENDDO
Give a code snippet in #HicEst Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#J
J
baseN=: (, 'b'&,)&.":
Give a code snippet in #J It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Go
Go
package main   import ( "fmt" "sync" )   func ambStrings(ss []string) chan []string { c := make(chan []string) go func() { for _, s := range ss { c <- []string{s} } close(c) }() return c }   func ambChain(ss []string, cIn chan []string) chan []string { cOu...
Give a code snippet in #Go Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton")....
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
#Ruby
Ruby
  def welcome(name) puts "hello #{name}" end puts "What is your name?" $name = STDIN.gets welcome($name) return
Give a code snippet in #Ruby 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/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...
#Rust
Rust
const LOWER: i32 = 1; const UPPER: i32 = 1000;   // Because the rule for our series is simply adding one, the number of terms are the number of // digits between LOWER and UPPER const NUMBER_OF_TERMS: i32 = (UPPER + 1) - LOWER; fn main() { // Formulaic method println!("{}", (NUMBER_OF_TERMS * (LOWER + UPPER)) /...
Give a code snippet in #Rust 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#Raku
Raku
sub non_continuous_subsequences ( *@list ) { @list.combinations.grep: { 1 != all( .[ 0 ^.. .end] Z- .[0 ..^ .end] ) } }   say non_continuous_subsequences( 1..3 )».gist; say non_continuous_subsequences( 1..4 )».gist; say non_continuous_subsequences( ^4 ).map: {[<a b c d>[.list]].gist};
Give a code snippet in #Raku Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and...
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....
#Common_Lisp
Common Lisp
(defun fitness (string target) "Closeness of string to target; lower number is better" (loop for c1 across string for c2 across target count (char/= c1 c2)))   (defun mutate (string chars p) "Mutate each character of string with probablity p using characters from chars" (dotimes (n (length strin...
Give a code snippet in #Common_Lisp 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’ ...
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...
#Lua
Lua
  function curry2(f) return function(x) return function(y) return f(x,y) end end end   function add(x,y) return x+y end   local adder = curry2(add) assert(adder(3)(4) == 3+4) local add2 = adder(2) assert(add2(3) == 2+3) assert(add2(5) == 2+5)  
Give a code snippet in #Lua 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Haskell
Haskell
isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs   isSquareMatrix xs = null xs || all ((== (length xs)).length) xs   mult:: Num a => [[a]] -> [[a]] -> [[a]] mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss   matI::(Num a) => Int -> [[a...
Give a code snippet in #Haskell Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#BASIC
BASIC
10 DEFINT A-Z 20 FOR I=1 TO 100 30 N=I: GOSUB 100 40 PRINT USING " ##";T; 50 IF I MOD 20=0 THEN PRINT 60 NEXT 70 END 100 T=1 110 IF (N AND 1)=0 THEN N=N\2: T=T+1: GOTO 110 120 P=3 130 GOTO 180 140 C=1 150 IF N MOD P=0 THEN N=N\P: C=C+1: GOTO 150 160 T=T*C 170 P=P+2 180 IF P*P<=N GOTO 140 190 IF N>1 THEN T=T*2 200 RETUR...
Give a code snippet in #BASIC Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#AutoHotkey
AutoHotkey
  mapRange(a1, a2, b1, b2, s) { return b1 + (s-a1)*(b2-b1)/(a2-a1) }   out := "Mapping [0,10] to [-1,0] at intervals of 1:`n"   Loop 11 out .= "f(" A_Index-1 ") = " mapRange(0,10,-1,0,A_Index-1) "`n" MsgBox % out  
Give a code snippet in #AutoHotkey Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linea...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Isabelle
Isabelle
theory Scratch imports Main begin   section‹100 Doors›   datatype doorstate = Open | Closed   fun toggle :: "doorstate ⇒ doorstate" where "toggle Open = Closed" | "toggle Closed = Open"   fun walk :: "('a ⇒ 'a) ⇒ nat ⇒ nat ⇒ 'a list ⇒ 'a list" where "walk f _ _ [] = []" | "walk f eve...
Give a code snippet in #Isabelle There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6,...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
Sorting algorithms/Strand sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Tcl
Tcl
proc merge {listVar toMerge} { upvar 1 $listVar v set i [set j 0] set out {} while {$i<[llength $v] && $j<[llength $toMerge]} { if {[set a [lindex $v $i]] < [set b [lindex $toMerge $j]]} { lappend out $a incr i } else { lappend out $b incr j } } # Done the merge, but will ...
Give a code snippet in #Tcl 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/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...
#Haskell
Haskell
import Control.Monad (when)   main = loop 1024 where loop n = when (n > 0) (do print n loop (n `div` 2))
Give a code snippet in #Haskell Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downw...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#XPL0
XPL0
code ChOut=8, IntOut=11;   func Gen(M); \Generate Mth powers of positive integers int M; int N, R, I; [N:= [0, 0, 0, 0]; \provides own/static variables R:= 1; for I:= 1 to M do R:= R*N(M); N(M):= N(M)+1; return R; ];   func Filter; \Generate squares of positive integers that aren't cubes in...
Give a code snippet in #XPL0 A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that t...
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...
#Perl
Perl
use strict; use warnings; use Math::AnyNum qw(:overload as_bin digits2num);   for my $x (1..10, 95..105, 297, 576, 594, 891, 909, 999) { my $y; if ($x =~ /^9+$/) { $y = digits2num([(1) x (9 * length $x)],2) } # all 9's implies all 1's else { while (1) { last unless as_bin(++$y) % $x } } pr...
Give a code snippet in #Perl 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/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...
#Clojure
Clojure
(require '[clojure.java.io :as jio] '[clojure.string :as str])   (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-...
Give a code snippet in #Clojure 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 r...
christopher/rosetta-code
http://rosettacode.org/wiki/Textonyms
Textonyms
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -...
#Java
Java
  import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector;   public class RTextonyms {   private static...
Give a code snippet in #Java When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO ...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. 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 algebra, polynomial long division is an algorithm for d...
#C.2B.2B
C++
  #include <iostream> #include <iterator> #include <vector>   using namespace std; typedef vector<double> Poly;   // does: prints all members of vector // input: c - ASCII char with the name of the vector // A - reference to polynomial (vector) void Print(char name, const Poly &A) { cout << name << "(" << A.si...
Give a code snippet in #C.2B.2B This page uses content from Wikipedia. The original article was at Polynomial long division. 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 algebra, polynomial lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts She...
#Nim
Nim
proc `<`[T](a, b: openarray[T]): bool = for i in 0 .. min(a.len, b.len): if a[i] < b[i]: return true if a[i] > b[i]: return false return a.len < b.len   echo([1,2,1,3,2] < [1,2,0,4,4,0,0,0])
Give a code snippet in #Nim sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qu...
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...
#BASIC
BASIC
FUNCTION sel$(choices$(), prompt$) IF UBOUND(choices$) - LBOUND(choices$) = 0 THEN sel$ = "" ret$ = "" DO FOR i = LBOUND(choices$) TO UBOUND(choices$) PRINT i; ": "; choices$(i) NEXT i INPUT ;prompt$, index IF index <= UBOUND(choices$) AND index >= LBOUND(choices$) THEN ret$ =...
Give a code snippet in #BASIC 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 stri...
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...
#Swift
Swift
import Foundation   extension String { func dropLastIf(_ char: Character) -> String { if last == char { return String(dropLast()) } else { return self } } }   enum Align { case left, center, right }   func getLines(input: String) -> [String] { input .components(separatedBy: "\n") ...
Give a code snippet in #Swift 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 lef...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 ...
#PARI.2FGP
PARI/GP
bubbleSort(v)={ for(i=1,#v-1, for(j=i+1,#v, if(v[j]<v[i], my(t=v[j]); v[j]=v[i]; v[i]=t ) ) ); v };
Give a code snippet in #PARI.2FGP 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/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q...
#SAS
SAS
data pvalues; input raw_p @@; cards; 4.533744e-01 7.296024e-01 9.936026e-02 9.079658e-02 1.801962e-01 8.752257e-01 2.922222e-01 9.115421e-01 4.355806e-01 5.324867e-01 4.926798e-01 5.802978e-01 3.485442e-01 7.883130e-01 2.729308e-01 8.502518e-01 4.268138e-01 6.442008e-01 3.030266e-01 5.001555e-02 3.194810e-01 7.892933e-...
Give a code snippet in #SAS Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-v...
christopher/rosetta-code