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/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...
#Bracmat
Bracmat
(knapsack= ( things = (map.9.150) (compass.13.35) (water.153.200) (sandwich.50.160) (glucose.15.60) (tin.68.45) (banana.27.60) (apple.39.40) (cheese.23.30) (beer.52.10) ("suntan cream".11.70) (camera.32.30) (T-shirt.24.15) (trousers.48....
Give a code snippet in #Bracmat 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 ha...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Oz
Oz
declare Arr = {Array.new 1 %% lowest index 10 %% highest index 37} %% all 10 fields initialized to 37 in {Show Arr.1} Arr.1 := 64 {Show Arr.1}
Give a code snippet in #Oz This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve...
christopher/rosetta-code
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation ...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::Util 'min'; use ntheory 'is_prime';   sub rotate { my($i,@a) = @_; join '', @a[$i .. @a-1, 0 .. $i-1] }   sub isCircular { my ($n) = @_; return 0 unless is_prime($n); my @circular = split //, $n; return 0 if min(@circular) < $circular[0]; for (1...
Give a code snippet in #Perl Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number ...
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 ...
#Picat
Picat
go => L = [Year : Year in 2008..2121, dow(Year, 12, 25) == 0], println(L), println(len=L.length), nl.   % Day of week, Sakamoto's method dow(Y, M, D) = R => T = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4], if M < 3 then Y := Y - 1 end, R = (Y + Y // 4 - Y // 100 + Y // 400 + T[M] + D) mod 7.  
Give a code snippet in #Picat A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#AutoHotkey
AutoHotkey
SetBatchLines, -1 Tick := A_TickCount ; store tickcount Loop, 1000000 { Random, x, 1, 1000000 Random, y, 1, 1000000 gcd(x, y) } t := A_TickCount - Tick ; store ticks elapsed MsgBox, % t / 1000 " Seconds elapsed.`n" Round(1 / (t / 1000000000), 0) " Loop iterations per second."   gcd(a, b) { ; Euclid...
Give a code snippet in #AutoHotkey Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplis...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#Pascal
Pascal
program zumkeller; //https://oeis.org/A083206/a083206.txt {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON} // {$O+,I+} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils {$IFDEF WINDOWS},Windows{$ENDIF} ; //###################################################################### //prime decom...
Give a code snippet in #Pascal Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divi...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#BASIC
BASIC
DIM timestart AS SINGLE, timedone AS SINGLE, timeelapsed AS SINGLE   timestart = TIMER SLEEP 1 'code or function to execute goes here timedone = TIMER   'midnight check: IF timedone < timestart THEN timedone = timedone + 86400 timeelapsed = timedone - timestart
Give a code snippet in #BASIC Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between...
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...
#Sidef
Sidef
[0,1,2].permutations { |p| say p }
Give a code snippet in #Sidef 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   gene...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#XLISP
XLISP
(defun accumulator (x) (lambda (n) (setq x (+ n x)) x ) )
Give a code snippet in #XLISP A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pas...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Oberon-2
Oberon-2
  MODULE HelloWorld; IMPORT Out; BEGIN Out.String("Goodbye, world!") END HelloWorld.  
Give a code snippet in #Oberon-2 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/St...
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Wren
Wren
import "/big" for BigInt   var pt = "Rosetta Code" System.print("Plain text:  : %(pt)") var n = BigInt.new("9516311845790656153499716760847001433441357") var e = BigInt.new("65537") var d = BigInt.new("5617843187844953170308463622230283376298685") var ptn = BigInt.zero // convert plain text to a number for (b...
Give a code snippet in #Wren Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#J
J
10b123 16b123 8b123 20b123 2b123 1b123 0b123 100b123 99 0 0bsilliness 1 123 291 83 443 11 6 3 10203 99 0 1 28
Give a code snippet in #J Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be int...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#AWK
AWK
BEGIN { printf "" > "output.txt" close("output.txt") printf "" > "/output.txt" close("/output.txt") system("mkdir docs") system("mkdir /docs") }
Give a code snippet in #AWK In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#JavaScript
JavaScript
function happy(number) { var m, digit ; var cycle = [] ;   while(number != 1 && cycle[number] !== true) { cycle[number] = true ; m = 0 ; while (number > 0) { digit = number % 10 ; m += digit * digit ; number = (number - digit) / 10 ; } ...
Give a code snippet in #JavaScript 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/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...
#Python
Python
from itertools import zip_longest   txt = """Given$a$txt$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$t...
Give a code snippet in #Python Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either le...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Batch_File
Batch File
@echo off ::The Main Thing... cls echo. call :reverse "---------- Ice and Fire ------------" call :reverse call :reverse "fire, in end will world the say Some" call :reverse "ice. in say Some" call :reverse "desire of tasted I've what From" call :reverse "fire. favor who those with hold I" call :reverse call :reverse ...
Give a code snippet in #Batch_File Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#TI-83_BASIC
TI-83 BASIC
PROGRAM:XORPATT " •.-,+-°-1+o*:πOX"→Str1   ClrHome   {0,0,0,0}→L1 {0,0,0,0)→L2   For(I,1,8,1) For(J,1,16,1) J→A I→B   If A>8 Then A-8→A 1→L1(1) Else 0→L1(1) End   If A>4 Then A-4→A 1→L1(2) Else 0→L1(2) End   If A>2 Then A-2→A 1→L1(3) Else 0→L1(3) End   If A>1 Then 1→L1(4) Else 0→L1(4) End   0→L2(1)   If B>4 Then B-4→B ...
Give a code snippet in #TI-83_BASIC Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Vlang
Vlang
fn main() { println('a'[0]) // prints "97" println('π'[0]) // prints "207"   s := 'aπ' println('string cast to bytes: ${s.bytes()}') for c in s { print('0x${c:x} ') } }
Give a code snippet in #Vlang Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conv...
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 ...
#Vedit_macro_language
Vedit macro language
Sort(0, File_Size) // sort the data While(Replace("^(.*)\N\1$", "\1", REGEXP+BEGIN+NOERR)){} // remove duplicates
Give a code snippet in #Vedit_macro_language 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 ...
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
#C.23
C#
using System;   namespace CalculateE { class Program { public const double EPSILON = 1.0e-15;   static void Main(string[] args) { ulong fact = 1; double e = 2.0; double e0; uint n = 2; do { e0 = e; fact *= n+...
Give a code snippet in #C.23 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/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Ruby
Ruby
class DNA_Seq attr_accessor :seq   def initialize(bases: %i[A C G T] , size: 0) @bases = bases @seq = Array.new(size){ bases.sample } end   def mutate(n = 10) n.times{|n| method([:s, :d, :i].sample).call} end   def to_s(n = 50) just_size = @seq.size / n (0...@seq.size).step(n).map{|fro...
Give a code snippet in #Ruby Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#D
D
import std.stdio;   int[] divisors(int n) { import std.range;   int[] divs = [1]; int[] divs2;   for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs ~= i; if (i != j) { divs2 ~= j; } } } divs ~= ...
Give a code snippet in #D An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternate...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Scala
Scala
import java.io.File import java.util.Scanner   object ReadFastaFile extends App { val sc = new Scanner(new File("test.fasta")) var first = true   while (sc.hasNextLine) { val line = sc.nextLine.trim if (line.charAt(0) == '>') { if (first) first = false else println() printf("%s: ", line....
Give a code snippet in #Scala In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Roset...
christopher/rosetta-code
http://rosettacode.org/wiki/War_card_game
War card game
War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell Poker hand_analyser Go Fish...
#11l
11l
UInt32 seed = 0 F nonrandom(n)  :seed = (1664525 * :seed + 1013904223) [&] FFFF'FFFF R Int(:seed >> 16) % n   F nonrandom_shuffle(&x) L(i) (x.len - 1 .< 0).step(-1) V j = nonrandom(i + 1) swap(&x[i], &x[j])   V SUITS = [‘♣’, ‘♦’, ‘♥’, ‘♠’] V FACES = [‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’, ‘J’...
Give a code snippet in #11l War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell ...
christopher/rosetta-code
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two...
#Racket
Racket
#lang racket (require racket/draw)   (define (percentage-difference bitmap1 bitmap2) (define width (send bitmap1 get-width)) (define height (send bitmap1 get-height)) (define buffer1 (make-bytes (* width height 4))) (define buffer2 (make-bytes (* width height 4))) (send (send bitmap1 make-dc) get-argb-pixels ...
Give a code snippet in #Racket basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The e...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_partitions
Ordered partitions
In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r g 1 , a r g 2 , ...
#FreeBASIC
FreeBASIC
Function Perm(x() As Integer) As Boolean Dim As Integer i, j For i = Ubound(x,1)-1 To 0 Step -1 If x(i) < x(i+1) Then Exit For Next i If i < 0 Then Return False j = Ubound(x,1) While x(j) <= x(i) j -= 1 Wend Swap x(i), x(j) i += 1 j = Ubound(x,1) While i < j...
Give a code snippet in #FreeBASIC In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#R
R
i <- 42 primeCount <- 0 while(primeCount < 42) { if(gmp::isprime(i) == 2)#1 means "probably prime" and won't come up for numbers this small, 2 is what we want. { primeCount <- primeCount + 1 extraCredit <- format(i, big.mark=",", scientific = FALSE) cat("Prime count:", paste0(primeCount, ";"), "The prim...
Give a code snippet in #R Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#Relation
Relation
  program fivenum(X) rename X^ x order x 1 dup project x min, x median, x max, x count set q1 = x_count / 4 set q1min = floor(q1) set q1weight = q1 - q1min set q3 = x_count * 3 / 4 set q3min = floor(q3) set q3weight = q3 - q3min swap dup select rownumber = q1min + 1 or rownumber = q1min + 2 extend w = q1weight * (rownu...
Give a code snippet in #Relation Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example...
christopher/rosetta-code
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the i...
#Phix
Phix
without js -- libcurl string test = "00-11-22-33-44-55-66" -- CIMSYS Inc --string test = "10-11-22-33-44-55-66" -- N/A include builtins/libcurl.e curl_global_init() atom curl = curl_easy_init() string url = sprintf("http://api.macvendors.com/%s",{test}) curl_easy_setopt(curl, CURLOPT_URL, url) object res = cur...
Give a code snippet in #Phix Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or nume...
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 ...
#Prolog
Prolog
reverse("abcd", L), string_to_list(S,L).
Give a code snippet in #Prolog 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 Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#Groovy
Groovy
def time = "unknown" def text = new URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl').eachLine { line -> def matcher = (line =~ "<BR>(.+) UTC") if (matcher.find()) { time = matcher[0][1] } } println "UTC Time was '$time'"
Give a code snippet in #Groovy Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this p...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Plain_English
Plain English
To run: Start up. Make a vector from 3 and 4 and 5. Make another vector from 4 and 3 and 5. Make a third vector from -5 and -12 and -13. Write "A vector: " then the vector on the console. Write "Another vector: " then the other vector on the console. Write "A third vector: " then the third vector on the console. Write ...
Give a code snippet in #Plain_English A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a tripl...
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...
#Factor
Factor
program permutations   implicit none integer, parameter :: value_min = 1 integer, parameter :: value_max = 3 integer, parameter :: position_min = value_min integer, parameter :: position_max = value_max integer, dimension (position_min : position_max) :: permutation   call generate (position_min)   contai...
Give a code snippet in #Factor 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   gen...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#DCL
DCL
$ i = 0 $ loop: $ write sys$output f$fao( "!OL", i ) $ i = i + 1 $ goto loop
Give a code snippet in #DCL Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
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 ...
#VTL-2
VTL-2
1000 #=2000 1010 R=! 1020 N=M 1030 X=Y 1040 #=N>3*1070 1050 N=N+12 1060 X=X-1 1070 J=X/100 1080 K=% 1090 W=N+1*26/10+D+K+(K/4)+(J/4)+(5*J)/7*0+% 1100 #=R 2000 ?="25th of December is a Sunday in"; 2010 Y=2008 2020 M=12 2030 D=25 2040 #=1010 2050 #=W=1=0*2080 2060 $=32 2070 ?=Y 2080 Y=Y+1 2090 #=Y<2121*2040 2100 ?=""
Give a code snippet in #VTL-2 A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#TI-83_BASIC
TI-83 BASIC
"HELLO"→Str0 Str0+" WORLD!"→Str0
Give a code snippet in #TI-83_BASIC String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another stri...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Clojure
Clojure
(defn van-der-corput "Get the nth element of the van der Corput sequence." ([n] ;; Default base = 2 (van-der-corput n 2)) ([n base] (let [s (/ 1 base)] ;; A multiplicand to shift to the right of the decimal. ;; We essentially want to reverse the digits of n and put them after the ;; decimal po...
Give a code snippet in #Clojure When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#PILOT
PILOT
T:Hello world!
Give a code snippet in #PILOT Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Common_Lisp
Common Lisp
(ql:quickload 'ironclad) (defun string-to-ripemd-160 (str) "Return the RIPEMD-160 digest of the given ASCII string." (ironclad:byte-array-to-hex-string (ironclad:digest-sequence :ripemd-160 (ironclad:ascii-string-to-byte-array str)))   (string-to-ripemd-160 "Rosetta Code")
Give a code snippet in #Common_Lisp RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#Rust
Rust
extern crate regex;   use regex::Regex; use std::collections::HashMap; use std::io;   fn main() { let mut input_line = String::new(); let mut template = String::new();   println!("Please enter a multi-line story template with <parts> to replace, terminated by a blank line.\n"); loop { io::stdin(...
Give a code snippet in #Rust This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#Objeck
Objeck
  \b //Backspace \n //Line Feed \r //Carriage Return \t //Tab \0 //Null \' //Single Quote \" //Double Q
Give a code snippet in #Objeck Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling i...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Objeck
Objeck
class Brainfu_k { @program : String; @mem : Int[]; @ip : Int; @dp : Int;   New(program : String, size : Int) { @program := program; @mem := Int → New[size]; }   function : Main(args : String[]) ~ Nil { if(args → Size() = 2) { Brainfu_k → New(args[0], args[1] → ToInt()) → Execute(); };...
Give a code snippet in #Objeck Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly imple...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_square_curve
Sierpinski square curve
Task Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
#11l
11l
F sierpinski_square(fname, size, length, order) V x = (size - length) / 2 V y = Float(length) V angle = 0.0   V outfile = File(fname, ‘w’) outfile.write(‘<svg xmlns='http://www.w3.org/2000/svg' width='’size‘' height='’size"'>\n") outfile.write("<rect width='100%' height='100%' fill='white'/>\n") ou...
Give a code snippet in #11l Task Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#COBOL
COBOL
identification division. program-id. show-continued-fractions.   environment division. configuration section. repository. function continued-fractions function all intrinsic.   procedure division. fractions-main.   display "Square root 2 appr...
Give a code snippet in #COBOL continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wri...
christopher/rosetta-code
http://rosettacode.org/wiki/Cut_a_rectangle
Cut a rectangle
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles...
#Java
Java
import java.util.*;   public class CutRectangle {   private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};   public static void main(String[] args) { cutRectangle(2, 2); cutRectangle(4, 3); }   static void cutRectangle(int w, int h) { if (w % 2 == 1 && h % 2 == 1) ...
Give a code snippet in #Java A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#XLISP
XLISP
XLISP 3.3, September 6, 2002 Copyright (c) 1984-2002, by David Betz [1] (expt 0 0)   1 [2]
Give a code snippet in #XLISP Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#D
D
import std.stdio, std.bigint, std.math;   T gcd(T)(T a, T b) pure nothrow { while (b) { immutable t = b; b = a % b; a = t; } return a; }   T lcm(T)(T m, T n) pure nothrow { if (m == 0) return m; if (n == 0) return n; return abs((m * n) / gcd(m, n)); }   void main() { ...
Give a code snippet in #D Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has bot...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions   on run   -- FIRST FIFTEEN RECAMANs ------------------------------------------------------   script term15 on |λ|(i) 15 = (i as integer) end |λ| end script set strFirst15 to unwords(snd(recamanUpto(true, term15)))   ...
Give a code snippet in #AppleScript The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n....
christopher/rosetta-code
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ...
#Ruby
Ruby
Test = Struct.new(:limits, :data) tests = Test.new( [23, 37, 43, 53, 67, 83], [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]), Test.new( [14, 18, 249, 312, 389, 392, 513, 59...
Give a code snippet in #Ruby You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#AutoHotkey
AutoHotkey
DllCall("AllocConsole") FileAppend, Goodbye`, World!, CONOUT$ FileReadLine, _, CONIN$, 1
Give a code snippet in #AutoHotkey Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard er...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Raku
Raku
sub n-van-ecks ($init) { $init, -> $i, { state %v; state $k; $k++; my $t = %v{$i}.defined ?? $k - %v{$i} !! 0; %v{$i} = $k; $t } ... * }   for < A181391 0 A171911 1 A171912 2 A171913 3 A171914 4 A171915 5 A171916 6 A171917 7 A1...
Give a code snippet in #Raku The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured ...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#M4
M4
define(`palindrorev',`ifelse(`$1',invert(`$1'),`yes',`no')')dnl palindrorev(`ingirumimusnocteetconsumimurigni') palindrorev(`this is not palindrome')
Give a code snippet in #M4 A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Maple
Maple
lst := ["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"]: perm := table(): for letter in "ABCD" do perm[letter] := 0: end do: for item in lst do for letter in "ABCD" do perm[letter] += StringTools:-First...
Give a code snippet in #Maple ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ [] swap [ dup while base share /mod rot join swap again ] drop ] is digits ( n --> [ )   [ base put digits reverse dup 0 swap witheach [ base share rot * + ] base take rot size ** reduce ] ...
Give a code snippet in #Quackery When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Racket
Racket
  #lang racket   ;; GUI version (require racket/gui) (message-box "Yes/No example" "Yes or no?" #f '(yes-no))   ;; Text version, via stty (define stty (let ([exe (find-executable-path "stty")]) (λ args (void (apply system* exe args))))) (define tty-settings (string-trim (with-output-to-string (λ() (stty "-g")))))...
Give a code snippet in #Racket 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 presse...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Maple
Maple
TrialDivision := proc( n :: integer ) if n <= 1 then false elif n = 2 then true elif type( n, 'even' ) then false else for local i from 3 by 2 while i * i <= n do if irem( n, i ) = 0 then ...
Give a code snippet in #Maple Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Brat
Brat
$ brat # Interactive Brat brat:1> f = { a, b, s | a + s + s + b } #=> function: 0xb737ac08 brat:2> f "Rosetta" "Code" ":" #=> Rosetta::Code brat:3> quit Exiting
Give a code snippet in #Brat Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#BBC_BASIC
BBC BASIC
DIM test%(20) test%() = 0, 1, 2, 19, 20, 21, 99, 100, 101, 300, 310, 1001, -1327, 1501, \ \ 10203, 12609, 101104, 102003, 467889, 1005006, -123000789 FOR i% = 0 TO DIM(test%(),1) PRINT FNsaynumber(test%(i%)) NEXT END   DEF FNsaynumber(n%) LOCAL number%(), ...
Give a code snippet in #BBC_BASIC Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Elixir
Elixir
  defmodule SieveofEratosthenes do def init(lim) do find_primes(2,lim,(2..lim)) end   def find_primes(count,lim,nums) when (count * count) > lim do nums end   def find_primes(count,lim,nums) when (count * count) <= lim do e = Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count)) find_primes(c...
Give a code snippet in #Elixir A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prim...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#COBOL
COBOL
* FIZZBUZZ.COB * cobc -x -g FIZZBUZZ.COB * IDENTIFICATION DIVISION. PROGRAM-ID. fizzbuzz. DATA DIVISION. WORKING-STORAGE SECTION. 01 CNT PIC 9(03) VALUE 1. 01 REM PIC 9(03) VALUE 0. 01 QUOTIENT PIC 9(03)...
Give a code snippet in #COBOL Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_identity
Euler's identity
This page uses content from Wikipedia. The original article was at Euler's_identity. 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 mathematics, Euler's identity is the equality: ...
#Racket
Racket
#lang racket (+ (exp (* 0+i pi)) 1)
Give a code snippet in #Racket This page uses content from Wikipedia. The original article was at Euler's_identity. 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 mathematics, Euler's identity...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#FreeBASIC
FreeBASIC
#macro min(x,y) Iif(x>y,y,x) #endmacro #macro max(x,y) Iif(x>y,x,y) #endmacro   type pnt 'typedef for a point x as double y as double end type   type edg 'typedef for an edge p1 as pnt p2 as pnt end type   function point_in_tri( r as pnt, a as pnt, b as pnt, c as pnt ) as boolean 'uses baryc...
Give a code snippet in #FreeBASIC Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#XBasic
XBasic
' Loop over multiple arrays simultaneously PROGRAM "loopoverarrays"   DECLARE FUNCTION Entry()   FUNCTION Entry() DIM arr1$[2], arr2$[2], arr3%[2] arr1$[0] = "a": arr1$[1] = "b": arr1$[2] = "c" arr2$[0] = "A": arr2$[1] = "B": arr2$[2] = "C" arr3%[0] = 1: arr3%[1] = 2: arr3%[2] = 3 FOR i% = 0 TO 2 PRIN...
Give a code snippet in #XBasic Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this exa...
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...
#Sidef
Sidef
func forprimes(a, b, callback) { for (a = (a-1 -> next_prime); a <= b; a.next_prime!) { callback(a) } }   forprimes(3, 61, func(p) { for h3 in (2 ..^ p) { var ph3 = (p + h3) for d in (1 ..^ ph3) { ((-p * p) % h3) != (d % h3) && next ((p-1) * ph3) % d && next var...
Give a code snippet in #Sidef 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 inves...
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...
#F.23
F#
let rec binarySearch (myArray:array<IComparable>, low:int, high:int, value:IComparable) = if (high < low) then null else let mid = (low + high) / 2   if (myArray.[mid] > value) then binarySearch (myArray, low, mid-1, value) else if (myArray.[mid] < value) then ...
Give a code snippet in #F.23 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 nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#ALGOL_68
ALGOL 68
BEGIN # procedure that counts the number of times the letters in jewels occur in stones # PROC count jewels = ( STRING stones, jewels )INT: BEGIN # count the occurences of each letter in stones # INT upper a pos = 0; INT lower a pos = 1 + ( ABS "Z" - ABS "A" ); ...
Give a code snippet in #ALGOL_68 Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower c...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#PHP
PHP
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
Give a code snippet in #PHP “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structure...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Quackery
Quackery
[ tuck take swap join swap put ] is append ( [ s --> )   $ "L'homme qui attend de voir un canard roti voler " temp put $ "dans sa bouche doit attendre tres, tres longtemps." temp append temp take echo$
Give a code snippet in #Quackery 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#UNIX_Shell
UNIX Shell
VAR1="VAR1" echo ${VAR1:-"Not set."} echo ${VAR2:-"Not set."}
Give a code snippet in #UNIX_Shell
christopher/rosetta-code
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Vorpal
Vorpal
a = new() a.f = method(){ .x.print() }   c = new() c.g = method(){ (.x + 1).print() }   # array of delegates b = new() b.delegate = new() b.delegate[0] = a b.delegate[1] = c b.x = 3 b.f() b.g()   # single delegate d = new() d.delegate = a d.x = 7 d.f()
Give a code snippet in #Vorpal A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also ...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#C
C
#include <stdbool.h> #include <stdio.h> #include <math.h>   int connections[15][2] = { {0, 2}, {0, 3}, {0, 4}, // A to C,D,E {1, 3}, {1, 4}, {1, 5}, // B to D,E,F {6, 2}, {6, 3}, {6, 4}, // G to C,D,E {7, 3}, {7, 4}, {7, 5}, // H to D,E,F {2, 3}, {3, 4}, {4, 5}, // C-D, D-E, E-F };   int pegs[8]; in...
Give a code snippet in #C You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#FreeBASIC
FreeBASIC
  Dim As Integer l(100), a, b, c, n For a = 0 To 100/6 For b = 0 To 100/9 For c = 0 To 100/20 n = a*6 + b*9 + c*20 If n <= 100 Then l(n) = true Next c Next b Next a For n = 100 To 1 Step -1 If l(n) = false Then Print "El mayor número que no sea McNugget es:"; n: Exit...
Give a code snippet in #FreeBASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Transact-SQL
Transact-SQL
PRINT 'Goodbye, World!'
Give a code snippet in #Transact-SQL 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 worl...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Factor
Factor
TRUE . \ -1 FALSE . \ 0
Give a code snippet in #Factor Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#Lua
Lua
  -- This program takes two optional command line arguments. The first (arg[1]) -- specifies the input file, or defaults to standard input. The second -- (arg[2]) specifies the number of results to show, or defaults to 10.   -- in freq, each key is a word and each value is its count local freq = {} for line in io.lin...
Give a code snippet in #Lua Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#Lingo
Lingo
on getScreenPixelColor (x, y) sx = xtra("ScrnXtra3").new() img = sx.ScreenToImage(rect(x, y, x+1, y+1)) return img.getPixel(0, 0) end
Give a code snippet in #Lingo Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
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 ...
#Raku
Raku
say "hello world".flip; say "as⃝df̅".flip; say 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺'.flip;
Give a code snippet in #Raku 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 ...
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....
#Julia
Julia
  function parseRPNstring(rpns) infix = [] rpn = split(rpns) for tok in rpn if all(isnumber, tok) push!(infix, parse(Int, tok)) else last = pop!(infix) prev = pop!(infix) push!(infix, Expr(:call, Symbol(tok), prev, last)) println("C...
Give a code snippet in #Julia 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 equivalen...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#jq
jq
def count(stream): reduce stream as $i (0; . + 1);   # unordered def proper_divisors: . as $n | if $n > 1 then 1, ( range(2; 1 + (sqrt|floor)) as $i | if ($n % $i) == 0 then $i, (($n / $i) | if . == $i then empty else . end) else empty end) else empty end;   # The first ...
Give a code snippet in #jq The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors...
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#C.2B.2B
C++
#include <iostream>   const int WIDTH = 81; const int HEIGHT = 5;   char lines[WIDTH*HEIGHT];   void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos...
Give a code snippet in #C.2B.2B Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#AWK
AWK
BEGIN { for(i=1; i < 6; i++) { for(j=1; j <= i; j++ ) { printf "*" } print } }
Give a code snippet in #AWK “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structure...
christopher/rosetta-code
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat...
#Phix
Phix
function game_combinations(sequence res, integer pool, needed, sequence chosen={}) if needed=0 then res = append(res,chosen) -- collect the full sets else for i=iff(length(chosen)=0?1:chosen[$]+1) to pool do res = game_combinations(res,pool,needed-1,append(deep_copy(chosen),i)) ...
Give a code snippet in #Phix It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Java
Java
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner;   public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; ...
Give a code snippet in #Java Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the g...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#TXR
TXR
@(define paren)@(maybe)[@(coll)@(paren)@(until)]@(end)]@(end)@(end) @(do (defvar r (make-random-state nil))   (defun generate-1 (count) (let ((bkt (repeat "[]" count))) (cat-str (shuffle bkt))))   (defun generate-list (num count) [[generate tf (op generate-1 count)] 0..num])) @(next :li...
Give a code snippet in #TXR Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nes...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Brat
Brat
numbers = g.split[0,1].map(:to_i) p numbers[0] + numbers[1] #Prints the sum of the input
Give a code snippet in #Brat A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algor...
#PureBasic
PureBasic
;sorts an array of integers Procedure combSort11(Array a(1)) Protected i, gap, swaps = 1 Protected nElements = ArraySize(a())   gap = nElements While (gap > 1) Or (swapped = 1) gap * 10 / 13 If gap = 9 Or gap = 10: gap = 11: EndIf If gap < 1: gap = 1: EndIf   i = 0 swaps = 0 While (i...
Give a code snippet in #PureBasic Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compa...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#Perl
Perl
#!perl use strict; use warnings; my @players = @ARGV; @players = qw(Joe Mike); my @scores = (0) x @players; while( 1 ) { PLAYER: for my $i ( 0 .. $#players ) { my $name = $players[$i]; my $score = $scores[$i]; my $roundscore = 1 + int rand 6; print "$name, your score so far is $score.\n"; print "You rolled a...
Give a code snippet in #Perl The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to th...
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...
#Oforth
Oforth
: mapRange(p1, p2, s) s p1 first - p2 second p2 first - * p1 second p1 first - asFloat / p2 first + ;
Give a code snippet in #Oforth 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#BASIC
BASIC
@echo off for /L %%i in (1,1,100) do call :tester %%i goto :eof   :tester set /a test = %1 %% 15 if %test% NEQ 0 goto :NotFizzBuzz echo FizzBuzz goto :eof   :NotFizzBuzz set /a test = %1 %% 5 if %test% NEQ 0 goto :NotBuzz echo Buzz goto :eof   :NotBuzz set /a test = %1 %% 3 if %test% NEQ 0 goto :Not...
Give a code snippet in #BASIC Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MultiplicativeOrder[37, 1000] MultiplicativeOrder[10^100 + 1, 7919] (*10^3th prime number Prime[1000]*) MultiplicativeOrder[10^1000 + 1, 15485863] (*10^6th prime number*) MultiplicativeOrder[10^10000 - 1, 22801763489] (*10^9th prime number*) MultiplicativeOrder[13, 1 + 10^80] MultiplicativeOrder[11,...
Give a code snippet in #Mathematica.2FWolfram_Language The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possibl...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#PureBasic
PureBasic
EnableExplicit Define fwx$, n.i NewMap uchar.i()   Macro RowPrint(ns,ls,es,ws) Print(RSet(ns,4," ")+RSet(ls,12," ")+" "+es+" ") : If Len(ws)<55 : PrintN(ws) : Else : PrintN("...") : EndIf EndMacro   Procedure.d nlog2(x.d) : ProcedureReturn Log(x)/Log(2) : EndProcedure   Procedure countchar(s$, Map uchar()) If Len(s...
Give a code snippet in #PureBasic The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wor...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#hexiscript
hexiscript
let in openin "input.txt" let out openout "output.txt" while !(catch (let c read char in)) write c out endwhile close in; close out
Give a code snippet in #hexiscript File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a f...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Logtalk
Logtalk
  :- object(folding_examples).   :- public(show/0). show :- integer::sequence(1, 10, List), write('List: '), write(List), nl, meta::fold_left([Acc,N,Sum0]>>(Sum0 is Acc+N), 0, List, Sum), write('Sum of all elements: '), write(Sum), nl, meta::fold_left([Acc,N,Product0]>>(P...
Give a code snippet in #Logtalk Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#VHDL
VHDL
LIBRARY ieee; USE std.TEXTIO.all; entity quine is end entity quine; architecture beh of quine is type str_array is array(1 to 20) of string(1 to 80); ...
Give a code snippet in #VHDL A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Liberty_BASIC
Liberty BASIC
  run "sndrec32.exe"  
Give a code snippet in #Liberty_BASIC Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other samp...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#XPL0
XPL0
code ChOut=8, CrLf=9, Text=12; string 0; \use zero-terminated strings   proc XmlOut(S); \Output string in XML format char S; repeat case S(0) of \character entity substitutions ^<: Text(0, "&lt;"); ^>: Text(0, "&gt;"); ^&: Text(0, "&amp;"); ^": Text(0, "...
Give a code snippet in #XPL0 Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> ele...
christopher/rosetta-code
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
SeedRandom[1234]; ClearAll[ComputerChoose, HumanChoose] ComputerChoose[n_] := If[n < 18, RandomChoice[{1, 2, 3}], 21 - n] HumanChoose[] := ChoiceDialog["How many?", {1 -> 1, 2 -> 2, 3 -> 3, "Quit" -> -1}] runningtotal = 0; whofirst = ChoiceDialog["Who goes first?", {"You" -> 1, "Computer" -> 2}]; While[runningtotal < 2...
Give a code snippet in #Mathematica_.2F_Wolfram_Language 21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whos...
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 ...
#UNIX_Shell
UNIX Shell
#! /bin/bash   for (( i=2008; i<=2121; ++i )) do date -d "$i-12-25" done |grep Sun   exit 0
Give a code snippet in #UNIX_Shell 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 bet...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#AWK
AWK
BEGIN { r=7.125 printf " %9.3f\n",-r printf " %9.3f\n",r printf " %-9.3f\n",r printf " %09.3f\n",-r printf " %09.3f\n",r printf " %-09.3f\n",r }
Give a code snippet in #AWK Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Legendre_prime_counting_function
Legendre prime counting function
The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number. then π(n) ...
#Swift
Swift
import Foundation   extension Numeric where Self: Strideable { @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) } }   func eratosthenes(limit: Int) -> [Int] { guard limit >= 3 else { return limit < 2 ? [] : [2] }   let ndxLimi...
Give a code snippet in #Swift The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the...
christopher/rosetta-code