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/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Microsoft_Small_Basic
Microsoft Small Basic
  While "True" TextWindow.WriteLine("SPAM") EndWhile  
Give a code snippet in #Microsoft_Small_Basic Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#FreeBASIC
FreeBASIC
function factorial( n as uinteger ) as ulongint if n = 0 then return 1 return n*factorial(n-1) end function   function s_Lah( n as uinteger, k as uinteger ) as ulongint if n = k then return 1 if n = 0 orelse k = 0 then return 0 if k = 1 then return factorial(n) return ((-1)^n)*(factorial(n)*fact...
Give a code snippet in #FreeBASIC Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linea...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#zkl
zkl
reg attrs=List(), S,N; do{ attrs.clear(); do(6){ abcd:=(4).pump(List,(0).random.fp(1,7)); // list of 4 [1..6] randoms attrs.append(abcd.sum(0) - (0).min(abcd)); // sum and substract min } }while((S=attrs.sum(0))<75 or (N=attrs.filter('>=(15)).len())<2); println("Random numbers: %s\nSums to %d, wi...
Give a code snippet in #zkl RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-side...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#TI-83_BASIC
TI-83 BASIC
:1->C :While 1 :Prompt I :C->dim(L1) :I->L1(C) :Disp mean(L1) :1+C->C :End
Give a code snippet in #TI-83_BASIC Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving avera...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Dim As Integer ancho = 143, alto = 188, x, y, p, red, green, blue, luminancia Dim As String imagen = "Mona_Lisa.bmp" Screenres ancho,alto,32 Bload imagen   For x = 0 To ancho-1 For y = 0 To alto-1 p = Point(x,y) red = p Mod 256 p = p \ 256 green = p Mod 256 p = p \ 256 ...
Give a code snippet in #F.C5.8Drmul.C3.A6 Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward...
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
#Shiny
Shiny
say 'Hello world!'
Give a code snippet in #Shiny 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/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Scala
Scala
object RemoveLinesFromAFile extends App { args match { case Array(filename, start, num) =>   import java.nio.file.{Files,Paths} val lines = scala.io.Source.fromFile(filename).getLines val keep = start.toInt - 1 val top = lines.take(keep).toList val drop = lines.take(num.toInt).toList...
Give a code snippet in #Scala Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to rem...
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Ceylon
Ceylon
  module rosetta.fiveweekends "1.0.0" { import ceylon.time "1.2.2"; }  
Give a code snippet in #Ceylon The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (the...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#REXX
REXX
x= -4.9 y= 1.7   point=x y
Give a code snippet in #REXX Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Re...
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...
#FreeBASIC
FreeBASIC
-- comment here until end of line {- comment here -}
Give a code snippet in #FreeBASIC 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, enablin...
christopher/rosetta-code
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#Quackery
Quackery
[ stack ] is seqbits ( --> s )   [ bit seqbits take | seqbits put ] is seqadd ( n --> )   [ bit seqbits share & not ] is notinseq ( n --> b )   [ temp put ' [ 1 2 3 ] 7 seqbits put 4 [ dip [ dup -1 peek over -2 peek ] dup...
Give a code snippet in #Quackery The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Vim_Script
Vim Script
Sub Main() End Sub
Give a code snippet in #Vim_Script Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Tcl
Tcl
proc ordinal {n} { if {$n%100<10 || $n%100>20} { set suff [lindex {th st nd rd th th th th th th} [expr {$n % 10}]] } else { set suff th } return "$n'$suff" }   foreach start {0 250 1000} { for {set n $start; set l {}} {$n<=$start+25} {incr n} { lappend l [ordinal $n] } puts $l }
Give a code snippet in #Tcl Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show h...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 ...
#Sidef
Sidef
var table = [ <UK London>, <US New\ York>, <US Birmingham>, <UK Birmingham>, ];   table.sort {|a,b| a[0] <=> b[0]}.each { |col| say "#{col[0]} #{col[1]}" }
Give a code snippet in #Sidef 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Java
Java
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*;   public class FlippingBitsGame extends JPanel { final int maxLevel = 7; final int minLevel = 3;   private Random rand = new Random(); private int[][] grid, target; private Rectangle box; private int n = maxLev...
Give a code snippet in #Java The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { A[1] = 49927398716; A[2] = 49927398717; A[3] = 1234567812345678; A[4] = 1234567812345670; A[5] = "01234567897"; A[6] = "01234567890"; A[7] = "00000000000"; for (k in A) print "isLuhn("A[k]"): ",isLuhn(A[k]); }   function isLuhn(cardno) { s = 0; m = "024...
Give a code snippet in #AWK The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#D
D
import std.stdio, std.string;   void main(in string[] args) { if (args.length != 2 || args[1].length != args[1].countchars("hHqQ9+")) { writeln("Not valid HQ9+ code."); return; }   ulong accumulator; foreach (immutable c; args[1]) { final switch(c) { case 'Q',...
Give a code snippet in #D Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
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 |...
#Ada
Ada
with Ada.Strings.Fixed, Ada.Text_IO; use Ada.Strings, Ada.Text_IO; procedure String_Replace is Original : constant String := "Mary had a @__@ lamb."; Tbr : constant String := "@__@"; New_Str : constant String := "little"; Index : Natural := Fixed.Index (Original, Tbr); begin Put_Line (Fixed.Replace_Slic...
Give a code snippet in #Ada Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Groovy
Groovy
def lower = ('a'..'z')
Give a code snippet in #Groovy Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a...
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#TI-89_BASIC
TI-89 BASIC
FnOff PlotsOff NewPlot 1, 1, x, y ZoomData
Give a code snippet in #TI-89_BASIC Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4,...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#bc
bc
define g(a) { auto b   b = 3   "Inside g: a = "; a "Inside g: b = "; b "Inside g: c = "; c "Inside g: d = "; d   a = 3; b = 3; c = 3; d = 3 }   define f(a) { auto b, c   b = 2; c = 2 "Inside f (before call): a = "; a "Inside f (before call): b = "; b "Inside f (before cal...
Give a code snippet in #bc Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scopi...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Standard_ML
Standard ML
fun stripchars (string, chars) = let fun aux c = if String.isSubstring (str c) chars then "" else str c in String.translate aux string end
Give a code snippet in #Standard_ML Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any character...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Groovy
Groovy
def map = new TreeMap<Integer,Map<String,List<String>>>()   new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt').eachLine { word -> def size = - word.size() map[size] = map[size] ?: new TreeMap<String,List<String>>() def norm = word.toList().sort().sum() map[size][norm] = map[size][norm] ?: [] ...
Give a code snippet in #Groovy Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Delphi
Delphi
unit Unit1;   interface   uses Windows, SysUtils, Graphics, Forms, Controls, Classes, ExtCtrls;   type TForm1 = class(TForm) PaintBox1: TPaintBox; procedure FormPaint(Sender: TObject); private { Private declarations } public { Public declarations } end;   var Form1: TForm1;   implementation ...
Give a code snippet in #Delphi A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a
Pseudo-random numbers/Combined recursive generator MRG32k3a
MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of...
#Python
Python
# Constants a1 = [0, 1403580, -810728] m1 = 2**32 - 209 # a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 # d = m1 + 1   class MRG32k3a():   def __init__(self, seed_state=123): self.seed(seed_state)   def seed(self, seed_state): assert 0 <seed_state < d, f"Out of Range 0 x < {d}" self.x1 =...
Give a code snippet in #Python MRG32k3a Combined recursive generator (pseudo-code) /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] ...
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#XPL0
XPL0
real Circles, MinX, MaxX, MinY, MaxY, Temp, X, Y, DX, DY, Area; int N, Cnt1, Cnt2; def Del = 0.0005; def Inf = float(-1>>1); [\ X Y R Circles:= [ 1.6417233788, 1.6121789534, 0.0848270516, -1.4944608174, 1.2077959613, 1.1039549836, 0.6110294452, -0.6...
Give a code snippet in #XPL0 Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Yabasic
Yabasic
sub isPrime(v) if v < 2 then return False : fi if mod(v, 2) = 0 then return v = 2 : fi if mod(v, 3) = 0 then return v = 3 : fi d = 5 while d * d <= v if mod(v, d) = 0 then return False else d = d + 2 : fi wend return True end sub   for i = 101 to 999 if isPrime(i) print str$(i), "...
Give a code snippet in #Yabasic Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Haskell
Haskell
import Data.Array (Array, listArray, (!))   ------------------- TRADITIONAL STRINGS ------------------ ats :: Array Int (Char, String) ats = listArray (0, 9) $ zip -- 天干 tiangan – 10 heavenly stems "甲乙丙丁戊己庚辛壬癸" (words "jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi")   ads :: Array Int (String, String)...
Give a code snippet in #Haskell Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities resu...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
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 |...
#Swift
Swift
func factors(n: Int) -> [Int] {   return filter(1...n) { n % $0 == 0 } }
Give a code snippet in #Swift 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Forth
Forth
: lucas-lehmer 1+ 2 do 4 i 2 <> * abs swap 1+ dup + 1- swap i 1- 1 ?do dup * 2 - over mod loop 0= if ." M" i . then loop cr ;   1 15 lucas-lehmer
Give a code snippet in #Forth Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Phix
Phix
without js -- (peek/poke, call_back) constant Here_am_I = "Here am I" function Query(atom pData, pLength) integer len = peekNS(pLength,machine_word(),0) if poke_string(pData,len,Here_am_I) then return 0 end if pokeN(pLength,length(Here_am_I)+1,machine_word()) return 1 end function constant Q...
Give a code snippet in #Phix This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Forth
Forth
: egcd ( a b -- a b ) dup 0= IF 2drop 1 0 ELSE dup -rot /mod \ -- b r=a%b q=a/b -rot recurse \ -- q (s,t) = egcd(b, r) >r swap r@ * - r> swap \ -- t (s - q*t) THEN ;   : egcd>gcd ( a b x y -- n ) \ calculate gcd from egcd rot * -rot * +...
Give a code snippet in #Forth Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displays...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Arturo
Arturo
name: strip input "enter a variable name: " value: strip input "enter a variable value: "   let name value   print ["the value of variable" name "is:" var name]
Give a code snippet in #Arturo Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Phix
Phix
-- demo\rosetta\Bitmap_Histogram.exw (runnable version) include ppm.e -- black, white, read_ppm(), write_ppm() (covers above requirements)   function to_bw(sequence image) sequence hist = repeat(0,256) for x=1 to length(image) do for y=1 to length(image[x]) do integer pixel = image[x][y]...
Give a code snippet in #Phix Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must hav...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Lua
Lua
  math.randomseed( os.time() ) local puz = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 } local dir = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } } local sx, sy = 4, 4   function isValid( tx, ty ) return tx > 0 and tx < 5 and ty > 0 and ty < 5 end function display() io.write( "\n\n" ) for j = 1,...
Give a code snippet in #Lua Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Bracmat
Bracmat
( 24-game = m-w m-z 4numbers answer expr numbers , seed get-random convertBinaryMinusToUnary , convertDivisionToMultiplication isExpresssion reciprocal . (seed=.!arg:(~0:~/#?m-w.~0:~/#?m-z)) & seed$!arg & ( get-random = . 36969*mod$(!m-z.65536)+div$(!m-z.6553...
Give a code snippet in #Bracmat The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fortunate_numbers
Fortunate numbers
Definition A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers. For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 ...
#Phix
Phix
with javascript_semantics include mpfr.e mpz primorial = mpz_init(1), pj = mpz_init() sequence fortunates = {} for p=1 to 75 do mpz_mul_si(primorial,primorial,get_prime(p)) integer j = 3 mpz_add_si(pj,primorial,3) while not mpz_prime(pj) do mpz_add_si(pj,pj,2) j = j + 2 end while...
Give a code snippet in #Phix Definition A Fortunate number is the smallest integer m > 1 such that for a given positive integer n, primorial(n) + m is a prime number, where primorial(n) is the product of the first n prime numbers. For example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 whi...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#Picat
Picat
go => Emp = [  % Employee Name,Employee ID,Salary,Department ["Tyler Bennett","E10297","32000","D101"], ["John Rappl","E21437","47000","D050"], ["George Woltman","E00127","53500","D101"], ["Adam Smith","E63535","18000","D202"], ["Claire Buckman","E39876","278...
Give a code snippet in #Picat Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64   Function Mean(array() As Double) As Double Dim length As Integer = Ubound(array) - Lbound(array) + 1 If length = 0 Then Return 0.0/0.0 'NaN End If Dim As Double sum = 0.0 For i As Integer = LBound(array) To UBound(array) sum += array(i) Next Return sum/length End Function   F...
Give a code snippet in #FreeBASIC Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an ...
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)...
#Go
Go
package main   import "fmt"   type point struct { x, y float64 }   func (p point) String() string { return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y) }   type triangle struct { p1, p2, p3 point }   func (t *triangle) String() string { return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3) }   func (t *t...
Give a code snippet in #Go 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)    ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Objeck
Objeck
  function : Swap(p : Int[]) ~ Nil { t := p[0]; p[0] := p[1]; p[1] := t; }   function : Sort(a : Int[]) ~ Nil { do { sorted := true; size -= 1; for (i:=0; i<a->Size(); i+=1;) { if (a[i+1] < a[i]) { swap(a+i); sorted := 0; }; }; } while (sorted = false); }  
Give a code snippet in #Objeck Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_If_2 is   type Two_Bool is range 0 .. 3;   function If_2(Cond_1, Cond_2: Boolean) return Two_Bool is (Two_Bool(2*Boolean'Pos(Cond_1)) + Two_Bool(Boolean'Pos(Cond_2)));   begin for N in 10 .. 20 loop Put(Integer'Image(N) & " is "); case If_2(...
Give a code snippet in #Ada Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. b...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#OCaml
OCaml
let compose f g x = f (g x)
Give a code snippet in #OCaml Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Scala
Scala
val keys = List(1, 2, 3) val values = Array("A", "B", "C") // Array mixed with List val map = keys.zip(values).toMap // and other Seq are possible.   // Testing assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C")) println("Successfully completed without errors.")
Give a code snippet in #Scala Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Common_Lisp
Common Lisp
(defun average (list) (/ (reduce #'+ list) (length list)))   (defun radians (angle) (* pi 1/180 angle))   (defun degrees (angle) (* (/ 180 pi) angle))   (defun mean-angle (angles) (let* ((angles (map 'list #'radians angles)) (cosines (map 'list #'cos angles)) (sines (map 'list #'sin angles))) (degrees (...
Give a code snippet in #Common_Lisp When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the firs...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#Sidef
Sidef
func max_prime_bases(ndig, maxbase=36) {   var maxprimebases = [[]] var nwithbases = [0] var maxprime = (10**ndig - 1)   for p in (idiv(maxprime + 1, 10) .. maxprime) { var dig = p.digits var bases = (2..maxbase -> grep {|b| dig.all { _ < b } && dig.digits2num(b).is_prime }) if (...
Give a code snippet in #Sidef Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a differen...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Haskell
Haskell
pyth :: Int -> [(Int, Int, Int)] pyth n = [ (x, y, z) | x <- [1 .. n] , y <- [x .. n] , z <- [y .. n] , x ^ 2 + y ^ 2 == z ^ 2 ]
Give a code snippet in #Haskell A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Emacs_Lisp
Emacs Lisp
(require 'seq)   (defun quicksort (xs) (if (null xs) () (let* ((head (car xs)) (tail (cdr xs)) (lower-part (quicksort (seq-filter (lambda (x) (<= x head)) tail))) (higher-part (quicksort (seq-filter (lambda (x) (> x head)) tail)))) (append lower-part (list head) higher...
Give a code snippet in #Emacs_Lisp 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 | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#REXX
REXX
/*REXX pgm finds: 1st N Brazilian #s; odd Brazilian #s; prime Brazilian #s; ZZZth #.*/ parse arg t.1 t.2 t.3 t.4 . /*obtain optional arguments from the CL*/ if t.4=='' | t.4=="," then t.4= 0 /*special test case of Nth Brazilian #.*/ hdr.1= 'first'; hdr.2= "first odd"; hdr.3= ...
Give a code snippet in #REXX Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1...
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...
#Lambdatalk
Lambdatalk
  {def maprange {lambda {:a0 :a1 :b0 :b1 :s} {+ :b0 {/ {* {- :s :a0} {- :b1 :b0}} {- :a1 :a0}}}}} -> maprange   {maprange 0 10 -1 0 5} -> -0.5   {S.map {maprange 0 10 -1 0} {S.serie 0 10}} -> 0 maps to -1 1 maps to -0.9 2 maps to -0.8 3 maps to -0.7 4 maps to -0.6 5 maps to -0.5 6 maps to -0.4 7 maps to -0.3...
Give a code snippet in #Lambdatalk Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linea...
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Perl
Perl
sub complement { my $s = shift;   $s =~ tr/01/10/;   return $s; }   my $str = '0';   for (0..6) { say $str; $str .= complement($str); }  
Give a code snippet in #Perl Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
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-...
#Phix
Phix
with javascript_semantics function entropy(sequence s) sequence symbols = unique(s), counts = repeat(0,length(symbols)) for i=1 to length(s) do integer k = find(s[i],symbols) counts[k] += 1 end for atom H = 0 for i=1 to length(counts) do atom ci = counts[i]/lengt...
Give a code snippet in #Phix 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#C.2B.2B
C++
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath>   double log2( double number ) { return log( number ) / log( 2 ) ; }   int main( int argc , char *argv[ ] ) { std::string teststring( argv[ 1 ] ) ; std::map<char , int> frequencies ; for ( char c : teststring ) f...
Give a code snippet in #C.2B.2B Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary)...
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 ...
#Modula-2
Modula-2
MODULE Palindrome; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   PROCEDURE IsPalindrome(str : ARRAY OF CHAR) : BOOLEAN; VAR i,m : INTEGER; VAR buf : ARRAY[0..63] OF CHAR; BEGIN i := 0; m := HIGH(str) - 1; WHILE i<m DO IF str[i] # str[m-i] THEN RETURN...
Give a code snippet in #Modula-2 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#Quackery
Quackery
[] $ "rosetta/unixdict.txt" sharefile drop nest$ [ behead reverse swap 2dup find over found iff [ dip [ nested join ] ] else nip dup [] = until ] drop say "Number of semordnilaps: " dup size echo cr sortwith [ size swap size > ] 5 split drop say "Five longest: " witheach [ ...
Give a code snippet in #Quackery A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the t...
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...
#Elixir
Elixir
defmodule Van_der_corput do def sequence( n, base \\ 2 ) do "0." <> (Integer.to_string(n, base) |> String.reverse ) end   def float( n, base \\ 2 ) do Integer.digits(n, base) |> Enum.reduce(0, fn i,acc -> (i + acc) / base end) end   def fraction( n, base \\ 2 ) do str = Integer.to_string(n, base) ...
Give a code snippet in #Elixir 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/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function ToVlq(v As ULong) As ULong Dim array(8) As Byte Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray buffer.CopyTo(array, 0) Return BitConverter.ToUInt64(array, 0) End Function   Function FromVlq(v As ULong) As ULong ...
Give a code snippet in #Visual_Basic_.NET Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#PowerShell
PowerShell
  [regex]::Matches("the three truths", "th").count  
Give a code snippet in #PowerShell Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#PowerShell
PowerShell
$date = [DateTime]::Parse("March 7 2009 7:30pm -5" ) write-host $date write-host $date.AddHours(12) write-host [TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($date.AddHours(12),"Vladivostok Standard Time")
Give a code snippet in #PowerShell Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Rust
Rust
fn sum(arr: &[f64]) -> f64 { arr.iter().fold(0.0, |p,&q| p + q) }   fn mean(arr: &[f64]) -> f64 { sum(arr) / arr.len() as f64 }   fn main() { let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0]; println!("mean of {:?}: {:?}", v, mean(v));   let w = &[]; println!("mean of {:?}: {:?}", w, mean(w...
Give a code snippet in #Rust Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an estab...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Batch_File
Batch File
  curl.exe -s -L http://rosettacode.org/  
Give a code snippet in #Batch_File Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given f...
#PicoLisp
PicoLisp
(setq P (struct (native "@" "malloc" 'N 39) 'N # Align 144 # nop 144 # nop   # Prepare stack 106 12 # pushq $12 184 7 0 0 0 # mov $7, %eax 72 193 224 32 # shl $32, %rax 80 # pushq %rax   ...
Give a code snippet in #PicoLisp The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following as...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#PHP
PHP
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } //Fills a rectangle, or the whole image with black by default public fu...
Give a code snippet in #PHP Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#AutoHotkey
AutoHotkey
LineIntersectionByPoints(L1, L2){ x1 := L1[1,1], y1 := L1[1,2] x2 := L1[2,1], y2 := L1[2,2] x3 := L2[1,1], y3 := L2[1,2] x4 := L2[2,1], y4 := L2[2,2] return ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) ", " . ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / ((x1-x2)*...
Give a code snippet in #AutoHotkey [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#C.23
C#
class Segment { public Segment(PointF p1, PointF p2) { P1 = p1; P2 = p2; }   public readonly PointF P1; public readonly PointF P2;   public float Length() { return (float)Math.Sqrt(LengthSquared()); }   public float LengthSquared() { return (P1.X -...
Give a code snippet in #C.23 This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a func...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#WDTE
WDTE
let noargs => + 2 5; noargs -- print;   let fixedargs a b => + a b; fixedargs 3 5 -- print;   let m => import 'math'; m.cos 3 -- print;   # WDTE only has expressions, not statements, so statement vs. # first-class context doesn't make sense.   # Arguments in WDTE are technically passed by reference, in a way, but # bec...
Give a code snippet in #WDTE Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a var...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#MMIX
MMIX
// main registers p IS $255 % pointer pp GREG % backup for p A GREG % first int B GREG % second int // arg registers argc IS $0 argv IS $1   LOC Data_Segment GREG @ ERR BYTE "Wrong number of arguments",#a,0 ILLH BYTE "Argument -> ",0 ILLT BYTE " <- contains an illegal character",#a,0 LT BYTE "A is less than B",#a...
Give a code snippet in #MMIX Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Ruby
Ruby
module TicTacToe LINES = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]   class Game def initialize(player_1_class, player_2_class) @board = Array.new(10) # we ignore index 0 for convenience   @current_player_id = 0 @players = [player_1_class.new(self, "X"), player_2_class.n...
Give a code snippet in #Ruby Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™,...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#D
D
struct SLinkedNode(T) { T data; typeof(this)* next; }   void insertAfter(T)(SLinkedNode!T* listNode, SLinkedNode!T* newNode) { newNode.next = listNode.next; listNode.next = newNode; }   void main() { alias N = SLinkedNode!char;   auto lh = new N('A', new N('B')); auto c = new N('C');   /...
Give a code snippet in #D Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, E...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Nim
Nim
#-- # if statements #--   template `?`(expression, condition) = if condition: expression   let raining = true var needUmbrella: bool   # Normal syntax if raining: needUmbrella = true   # Inverted syntax (needUmbrella = true) ? (raining == true)   #-- # Assignments #--   template `~=`(right, left) = left = right...
Give a code snippet in #Nim Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the state...
christopher/rosetta-code
http://rosettacode.org/wiki/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#Rust
Rust
use std::convert::TryInto; use std::env; use std::num::Wrapping;   const REPLACEMENT_TABLE: [[u8; 16]; 8] = [ [4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3], [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9], [5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11], [7, 13, 10, 1, 0, 8, 9, 15...
Give a code snippet in #Rust GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and...
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#Scala
Scala
import java.util._ import scala.swing._   def easter(year: Int) = { // Start at March 21. val cal = new GregorianCalendar(year, 2, 21);   /* * Calculate e = day of Easter, following the 1886 paper, * Kalender-Formeln (Calendar Formulae) by Chr. Zeller. * http://www.merlyn.demon.co.uk/zel-1886.htm * ...
Give a code snippet in #Scala Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   year...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#PureBasic
PureBasic
If OpenConsole() ; Declare a string and a integer to be used Define txt.s, num.i   Print("Enter a string: ") txt=Input()   Repeat Print("Enter the number 75000: ") num=Val(Input()) ; Converts the Input to a Value with Val() Until num=75000 ; Check that the user really gives us 75000!   Print("Yo...
Give a code snippet in #PureBasic User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#J
J
coclass 'Animal'
Give a code snippet in #J This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. U...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#Raku
Raku
# based on http://www.mathpropress.com/stan/bibliography/spigot.pdf   sub stream(&next, &safe, &prod, &cons, $z is copy, @x) { gather loop { $z = safe($z, my $y = next($z)) ?? prod($z, take $y) !! cons($z, @x[$++]) } }   sub extr([$q, $r, $s, $t], $x) { ($q * $x ...
Give a code snippet in #Raku Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal seque...
christopher/rosetta-code
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a...
#Sidef
Sidef
func super_d(d) { var D = Str(d)*d 1..Inf -> lazy.grep {|n| Str(d * n**d).contains(D) } }   for d in (2..8) { say ("#{d}: ", super_d(d).first(10)) }
Give a code snippet in #Sidef A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Standard_ML
Standard ML
foldl (fn (a, sum) => sum + a * a) 0 ints
Give a code snippet in #Standard_ML Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
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...
#Shen
Shen
  (define permute [] -> [] [X] -> [[X]] X -> (permute-helper [] X))   (define permute-helper _ [] -> [] Done [X|Rest] -> (append (prepend-all X (permute (append Done Rest))) (permute-helper [X|Done] Rest)) )   (define prepend-all _ [] -> [] X [Next|Rest] -> [[X|Next]|(prepend-all X Rest)] )   (set *ma...
Give a code snippet in #Shen 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   gener...
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.
#XSLT
XSLT
<xsl:value-of select="format-number(7.125, '00000000.#############')" />
Give a code snippet in #XSLT 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/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and computer science, the Levenshtein ...
#Arturo
Arturo
print levenshtein "kitten" "sitting"
Give a code snippet in #Arturo This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and co...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Prolog
Prolog
loop(I) :- writeln(I), I1 is I+1, loop(I1).  
Give a code snippet in #Prolog Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations l...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#GML
GML
src = "string"; dest = src;
Give a code snippet in #GML This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty str...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Elixir
Elixir
defmodule JensenDevice do def task, do: sum( 1, 100, fn i -> 1 / i end )   defp sum( i, high, _term ) when i > high, do: 0 defp sum( i, high, term ) do temp = term.( i ) temp + sum( i + 1, high, term ) end end   IO.puts JensenDevice.task
Give a code snippet in #Elixir Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the AL...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Java
Java
import java.util.*;   public class HashJoin {   public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}};   String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"A...
Give a code snippet in #Java An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" ...
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...
#D
D
void main() /*@safe*/ { import std.stdio, std.algorithm, std.range, std.typecons;   immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ => iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0 && n != x);   iota(1, 11).map!properDivs.writeln; iota(1, 20_001).map!(n => tuple(properDivs(n)....
Give a code snippet in #D 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/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#Julia
Julia
function bernoulli(n) A = Vector{Rational{BigInt}}(undef, n + 1) for i in 0:n A[i + 1] = 1 // (i + 1) for j = i:-1:1 A[j] = j * (A[j] - A[j + 1]) end end return n == 1 ? -A[1] : A[1] end   function faulhabercoeffs(p) coeffs = Vector{Rational{BigInt}}(undef, p + 1)...
Give a code snippet in #Julia Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#REXX
REXX
/*REXX program reads the files specified and globally replaces a string. */ old= "Goodbye London!" /*the old text to be replaced. */ new= "Hello New York!" /* " new " used for replacement. */ parse arg fileList ...
Give a code snippet in #REXX Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#Go
Go
package raster   const b3Seg = 30   func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) { var px, py [b3Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) fx4, fy4 := float64(x4), float64(y4) for i := range...
Give a code snippet in #Go Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Tcl
Tcl
proc turing {states initial terminating symbols blank tape rules {doTrace 1}} { set state $initial set idx 0 set tape [split $tape ""] if {[llength $tape] == 0} { set tape [list $blank] } foreach rule $rules { lassign $rule state0 sym0 sym1 move state1 set R($state0,$sym0) [list $sym1 $move $...
Give a code snippet in #Tcl One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine i...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#UNIX_Shell
UNIX Shell
# Use the default printer queue, with lp(1) or lpr(1). # 1. The system must have a printer queue. # 2. The printer queue must understand plain text. # 3. System V has lp(1). BSD has lpr(1). # CUPS has both lp(1) and lpr(1). # echo 'Hello World!' | lp echo 'Hello World!' | lpr   # Use a character device. # 1. Th...
Give a code snippet in #UNIX_Shell Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Vim_Script
Vim Script
function! Factorial(n) if a:n < 2 return 1 else return a:n * Factorial(a:n-1) endif endfunction
Give a code snippet in #Vim_Script Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial o...
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/2D%2B
Deconvolution/2D+
This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} dimensions of two functions ...
#Wren
Wren
import "/complex" for Complex import "/fmt" for Fmt   var fft2 // recursive fft2 = Fn.new { |buf, out, n, step, start| if (step < n) { fft2.call(out, buf, n, step*2, start) fft2.call(out, buf, n, step*2, start + step) var j = 0 while (j < n) { var t = (Complex.imagMinusOn...
Give a code snippet in #Wren This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in d {\displaystyle {\mathit {d}}} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Erlang
Erlang
%% Compile %% %% erlc scriptname.erl %% %% Run %% %% erl -noshell -s scriptname   -module(scriptname). -export([start/0]).   start() -> Program = ?FILE, io:format("Program: ~s~n", [Program]), init:stop().
Give a code snippet in #Erlang The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
PolynomialQuotientRemainder[x^3-12 x^2-42,x-3,x]
Give a code snippet in #Mathematica.2FWolfram_Language This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Wren
Wren
import "/fmt" for Fmt, Conv import "/str" for Str   var toOctets = Fn.new { |n| var s = Conv.itoa(n, 2) var le = s.count var r = le % 7 var d = (le/7).floor if (r > 0) { d = d + 1 s = Fmt.zfill(7 * d, s) } var chunks = Str.chunks(s, 7) var last = "0" + chunks[-1] s = ...
Give a code snippet in #Wren Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert t...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#MATLAB_.2F_Octave
MATLAB / Octave
function testABC combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ... 'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ... 'PC' ; 'ZM']; words = {'A' 'BARK' 'BOOK' 'TREAT' 'COMMON' 'SQUAD' 'CONFUSE'}; for k = 1:length(words) possible = canMakeWor...
Give a code snippet in #MATLAB_.2F_Octave ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A comp...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Vlang
Vlang
fn is_cusip(s string) bool { if s.len != 9 { return false } mut sum := 0 for i in 0..8 { c := s[i] mut v :=0 match true { c >= '0'[0] && c <= '9'[0] { v = c - 48 } c >= 'A'[0] && c <= 'Z'[0] { v = c - 55 } c ==...
Give a code snippet in #Vlang This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeric...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM Only positive numbers 20 LET n=10 30 LET n1=0: LET n2=1 40 FOR k=1 TO n 50 LET sum=n1+n2 60 LET n1=n2 70 LET n2=sum 80 NEXT k 90 PRINT n1
Give a code snippet in #ZX_Spectrum_Basic The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive s...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
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 |...
#jq
jq
# Lines which do not have two integers are skipped:   def arithmetic: split(" ") | select(length > 0) | map(tonumber) | if length > 1 then .[0] as $a | .[1] as $b | "For a = \($a) and b = \($b):\n" + "a + b = \($a + $b)\n" + "a - b = \($a - $b)\n" + "a * b = \($a * $b)\n" + "a/b|floo...
Give a code snippet in #jq 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 Con...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Groovy
Groovy
assert URLDecoder.decode('http%3A%2F%2Ffoo%20bar%2F') == 'http://foo bar/'
Give a code snippet in #Groovy This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded...
christopher/rosetta-code