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/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#C
C
#include <stdio.h> #include <string.h>   const char *haystack[] = { "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag", NULL };   int search_needle(const char *needle, const char **hs) { int i = 0; while( hs[i] != NULL ) { if ( strcmp(hs[i], needle) == 0 ) return i; i++; ...
Give a code snippet in #C Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that h...
christopher/rosetta-code
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return succe...
#Kotlin
Kotlin
// version 1.0.6   import java.io.File   fun main(args: Array<String>) { // using built-in mkdirs() method val success = File("./path/to/dir").mkdirs() if (success) println("Directory path was created successfully") else println("Failed to create directory path") }
Give a code snippet in #Kotlin Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the direct...
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Kotlin
Kotlin
// version 1.1.51   typealias Matrix = Array<DoubleArray>   /* changes the matrix to RREF 'in place' */ fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r   ...
Give a code snippet in #Kotlin Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenie...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character
Terminal control/Display an extended character
Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
#REXX
REXX
/*REXX program demonstrates displaying an extended character (glyph) to the terminal.*/ /* [↓] this SAY will display the £ glyph (if the term supports it).*/ say '£' /*this assumes the pound sign glyph is displayable on the terminal. */ /*this program can execute c...
Give a code snippet in #REXX Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#BQN
BQN
•file.Chars "file" •file.Bytes "file"   # Shorthands: •FChars "file" •FBytes "file"  
Give a code snippet in #BQN Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished increme...
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 ...
#Factor
Factor
USING: combinators kernel math math.functions math.ranges sequences ;   : prime? ( n -- ? ) { { [ dup 2 < ] [ drop f ] } { [ dup even? ] [ 2 = ] } [ 3 over sqrt 2 <range> [ mod 0 > ] with all? ] } cond ;
Give a code snippet in #Factor 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 loop...
christopher/rosetta-code
http://rosettacode.org/wiki/K-d_tree
K-d tree
This page uses content from Wikipedia. The original article was at K-d tree. 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 k-d tree (short for k-dimensional tree) is a space-partitioning data str...
#Nim
Nim
type   Point[Dim: static Natural; T: SomeNumber] = array[Dim, T]   KdNode[Dim: static Natural; T: SomeNumber] = ref object x: Point[Dim, T] left, right: KdNode[Dim, T]     func toKdNodes[N, Dim: static Natural; T](a: array[N, array[Dim, T]]): array[N, KdNode[Dim, T]] = ## Create an array of KdNodes from a...
Give a code snippet in #Nim This page uses content from Wikipedia. The original article was at K-d tree. 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 k-d tree (short for k-dimensional tree) is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Jaro-Winkler_distance
Jaro-Winkler distance
The Jaro-Winkler distance is a metric for measuring the edit distance between words. It is similar to the more basic Levenstein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler distance also adds an increase ...
#Wren
Wren
import "io" for File import "/fmt" for Fmt import "/sort" for Sort   var jaroSim = Fn.new { |s1, s2| var le1 = s1.count var le2 = s2.count if (le1 == 0 && le2 == 0) return 1 if (le1 == 0 || le2 == 0) return 0 var dist = (le2 > le1) ? le2 : le1 dist = (dist/2).floor - 1 var matches1 = List.fi...
Give a code snippet in #Wren The Jaro-Winkler distance is a metric for measuring the edit distance between words. It is similar to the more basic Levenstein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler d...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Wee_Basic
Wee Basic
include c:\cxpl\codes; \intrinsic 'code' declarations int I; [RanSeed(12345); \set random number generator seed to 12345 for I:= 1 to 5 do [IntOut(0, Ran(1_000_000)); CrLf(0)]; ]
Give a code snippet in #Wee_Basic The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algo...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#PL.2FI
PL/I
  declare 1 node based (p), 2 value fixed, 2 link pointer;  
Give a code snippet in #PL.2FI singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element de...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Icon_and_Unicon
Icon and Unicon
link graphics,printf   procedure main() # generalized colour bars DrawTestCard(Simple_TestCard()) WDone() end   procedure DrawTestCard(TC) size := sprintf("size=%d,%d",TC.width,TC.height) &window := TC.window := open(TC.id,"g","bg=black",size) | stop("Unable to open window")   eve...
Give a code snippet in #Icon_and_Unicon Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Wren
Wren
import "/big" for BigInt   var a = BigInt.new("2988348162058574136915891421498819466320163312926952423791023078876139") var b = BigInt.new("2351399303373464486466122544523690094744975233415544072992656881240319") var m = BigInt.ten.pow(40) System.print(a.modPow(b, m))
Give a code snippet in #Wren Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346...
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
#Excel
Excel
thueMorse =LAMBDA(n, APPLYN(n)( LAMBDA(bits, APPENDCOLS(bits)( LAMBDA(x, IF(0 < x, 0, 1) )(bits) ) ) )(0) )
Give a code snippet in #Excel 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/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Ruby
Ruby
y = lambda do |f| lambda {|g| g[g]}[lambda do |g| f[lambda {|*args| g[g][*args]}] end] end   fac = lambda{|f| lambda{|n| n < 2 ? 1 : n * f[n-1]}} p Array.new(10) {|i| y[fac][i]} #=> [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]   fib = lambda{|f| lambda{|n| n < 2 ? n : f[n-1] + f[n-2]}} p Array.new(10) ...
Give a code snippet in #Ruby In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a var...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#Phix
Phix
constant lines = get_text("abbrev_auto.txt",GT_LF_STRIPPED) for i=1 to length(lines) do string li = lines[i] if length(li) then sequence days = split(li,no_empty:=true) if length(days)!=7 then ?9/0 end if integer len = 1 for j=1 to 7 do for k=j+1 to 7 do ...
Give a code snippet in #Phix The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or dele...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#Go
Go
package main   import ( "fmt" "time" "os" "os/exec" "strconv" )   func main() { tput("clear") // clear screen tput("cup", "6", "3") // an initial position time.Sleep(1 * time.Second) tput("cub1") // left time.Sleep(1 * time.Second) tput("cuf1") // right time.Sleep(1 * tim...
Give a code snippet in #Go Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Clojure
Clojure
; using substring: user=> (subs "knight" 1) "night" user=> (subs "socks" 0 4) "sock" user=> (.substring "brooms" 1 5) "room"   ; using rest and drop-last: user=> (apply str (rest "knight")) "night" user=> (apply str (drop-last "socks")) "sock" user=> (apply str (rest (drop-last "brooms"))) "room"
Give a code snippet in #Clojure The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#FutureBasic
FutureBasic
window 1, @"Count in Octal"   defstr word dim as short i text ,,,,, 50   print @"dec",@"oct" for i = 0 to 25 print i,oct(i) next   HandleEvents
Give a code snippet in #FutureBasic 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 reac...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#Java
Java
import java.util.Scanner;   public class Sundial { public static void main(String[] args) { double lat, slat, lng, ref; Scanner sc = new Scanner(System.in);   System.out.print("Enter latitude: "); lat = sc.nextDouble(); System.out.print("Enter longitude: "); lng = sc....
Give a code snippet in #Java Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island,...
christopher/rosetta-code
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such th...
#Raku
Raku
put "Wieferich primes less than 5000: ", join ', ', ^5000 .grep: { .is-prime and not ( exp($_-1, 2) - 1 ) % .² };
Give a code snippet in #Raku This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#C.2B.2B
C++
#include <fstream> #include <iostream> #include <ctime> using namespace std;   #define note_file "NOTES.TXT"   int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<a...
Give a code snippet in #C.2B.2B Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.T...
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...
#Go
Go
package main   import ( "fmt" "math/rand" "sort" "time" )   const bases = "ACGT"   // 'w' contains the weights out of 300 for each // of swap, delete or insert in that order. func mutate(dna string, w [3]int) string { le := len(dna) // get a random position in the dna to mutate p := rand.Int...
Give a code snippet in #Go 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Sed
Sed
#! /bin/sed -nf   # gcd.sed Copyright (c) 2010 by Paweł Zuzelski <pawelz@pld-linux.org> # dc.sed Copyright (c) 1995 - 1997 by Greg Ubben <gsu@romulus.ncsc.mil>   # usage: # # echo N M | ./gcd.sed # # Computes the greatest common divisor of N and M integers using euclidean # algorithm.   s/^/|P|K0|I10|O10|?~...
Give a code snippet in #Sed Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest c...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Rust
Rust
fn main() { let nums = [1,2,39,34,20, -20, -16, 35, 0];   let mut max = 0; let mut boundaries = 0..0;   for length in 0..nums.len() { for start in 0..nums.len()-length { let sum = (&nums[start..start+length]).iter() .fold(0, |sum, elem| sum+elem); if sum >...
Give a code snippet in #Rust Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are n...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#JavaScript
JavaScript
(function(txt) {   var cs = txt.split(''), i = cs.length, dct = {}, c = '', keys;   while (i--) { c = cs[i]; dct[c] = (dct[c] || 0) + 1; }   keys = Object.keys(dct); keys.sort(); return keys.map(function (c) { return [c, dct[c]]; });   })("Not all...
Give a code snippet in #JavaScript Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string ...
christopher/rosetta-code
http://rosettacode.org/wiki/Minimum_positive_multiple_in_base_10_using_only_0_and_1
Minimum positive multiple in base 10 using only 0 and 1
Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy phrases, the operation "minimum pos...
#ALGOL_68
ALGOL 68
BEGIN # returns B10 for the specified n or -1 if it cannot be found # # based on Rick Heylen's C program linked from the OEIS site # PROC find b10 = ( INT n )LONG INT: IF n < 1 THEN -1 ELIF n = 1 THEN 1 ELSE [ 0 : n ]LONG INT pow, val; INT x, ten...
Give a code snippet in #ALGOL_68 Every positive integer has infinitely many base-10 multiples that only use the digits 0 and 1. The goal of this task is to find and display the minimum multiple that has this property. This is simple to do, but can be challenging to do efficiently. To avoid repeating long, unwieldy p...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#J
J
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr   carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|.   add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+/...
Give a code snippet in #J Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#C.2B.2B
C++
#include <iostream> #include <iomanip> #include <cmath> // for log10() #include <algorithm> // for max()   size_t table_column_width(const int min, const int max) { unsigned int abs_max = std::max(max*max, min*min);   // abs_max is the largest absolute value we might see. // If we take the log10 and add one...
Give a code snippet in #C.2B.2B Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#PowerShell
PowerShell
  [string[]]$colors = "Black" , "DarkBlue" , "DarkGreen" , "DarkCyan", "DarkRed" , "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue" , "Green" , "Cyan", "Red" , "Magenta" , "Yellow" , "White"   for ($i = 0; $i -lt 64; $i++) { ...
Give a code snippet in #PowerShell Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Quackery
Quackery
[ 1 & ] is odd ( n --> b )   [ [] swap [ 10 /mod rot join swap dup 0 = until ] drop ] is digits ( n --> [ )   [ [] [] rot dup size odd dip [ witheach [ nested join swap ] ] not if swap ] is unzip ( [ --> [ [ ...
Give a code snippet in #Quackery 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...
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...
#Forth
Forth
\ grayscale bitmap (without word-alignment for scan lines)   \ bdim, bwidth, bdata all work with graymaps   : graymap ( w h -- gmp ) 2dup * bdata allocate throw dup >r 2! r> ;   : gxy ( x y gmp -- addr ) dup bwidth rot * rot + swap bdata + ;   : g@ ( x y gmp -- c ) gxy c@ ; : g! ( c x y bmp -- ) gxy c! ;   : gfil...
Give a code snippet in #Forth 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....
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...
#Kotlin
Kotlin
object ABC_block_checker { fun run() { println("\"\": " + blocks.canMakeWord("")) for (w in words) println("$w: " + blocks.canMakeWord(w)) }   private fun Array<String>.swap(i: Int, j: Int) { val tmp = this[i] this[i] = this[j] this[j] = tmp }   private fun Ar...
Give a code snippet in #Kotlin 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 alphab...
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...
#Erlang
Erlang
  -module(nr2eng). -import(lists, [foreach/2, seq/2, append/2]). -import(string, [strip/3, str/2]). -export([start/0]).   sym(1) -> "one"; sym(2) -> "two"; sym(3) -> "three"; sym(4) -> "four"; sym(5) -> "five"; sym(6) -> "six"; sym(7) -> "seven"; sym(8) -> "eight"; sym(9) -> "nine"; sym(10) -> "ten"; sym(11) -> "eleven...
Give a code snippet in #Erlang 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 pos...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Raku
Raku
  my $path = "/etc/passwd"; say $path.IO.e ?? "Exists" !! "Does not exist";   given $path.IO { when :d { say "$path is a directory"; } when :f { say "$path is a regular file"; } when :e { say "$path is neither a directory nor a file, but it does exist"; } default { say "$path does not exist" } }
Give a code snippet in #Raku Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#Io
Io
List do( gnomeSortInPlace := method( idx := 1 while(idx <= size, if(idx == 0 or at(idx) > at(idx - 1)) then( idx = idx + 1 ) else( swapIndices(idx, idx - 1) idx = idx - 1 ) ) self) )   lst := list(5, -1, ...
Give a code snippet in #Io Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Erlang
Erlang
mean([]) -> 0; mean(L) -> lists:sum(L)/erlang:length(L).
Give a code snippet in #Erlang 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 est...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Liberty_BASIC
Liberty BASIC
'This demo will try to get the robot to step up 'Run it several times to see the differences; sometimes the robot falls 'quite a ways before making it to the next step up, but sometimes he makes it 'on the first try   result = Stepp.Up()   Function Stepp.Up() While Not(Stepp()) result = Stepp.Up() Wend ...
Give a code snippet in #Liberty_BASIC From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" func...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#XSLT
XSLT
<xsl:template match="/table"> <table> <xsl:apply-templates /> </table> </xsl:template>   <xsl:template match="tr"> <tr><xsl:apply-templates /></tr> </xsl:template>   <xsl:template match="td"> <xsl:variable name="liveNeighbours"> <xsl:apply-templates select="current()" mode="countLiveNeig...
Give a code snippet in #XSLT The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#BASIC
BASIC
FUNCTION RootX (tBase AS DOUBLE, tExp AS DOUBLE, diffLimit AS DOUBLE) AS DOUBLE DIM tmp1 AS DOUBLE, tmp2 AS DOUBLE ' Initial guess: tmp1 = tBase / tExp DO tmp2 = tmp1 ' 1# tells compiler that "1" is a double, not an integer tmp1 = (((tExp - 1#) * tmp2) + (tBase / (tmp2 ^ (tExp - ...
Give a code snippet in #BASIC Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
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      ...
#MATLAB_.2F_Octave
MATLAB / Octave
x='{>\(y>(((-y-(((<(^<ejtq)\{-y.2^*<';z=['x=''',x,''';'];disp([z,x-1]);
Give a code snippet in #MATLAB_.2F_Octave 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 compute...
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#jq
jq
  def weights: { "1": {"3": -2}, "2": {"1" : 4, "3": 3}, "3": {"4": 2}, "4": {"2": -1} };
Give a code snippet in #jq The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been ...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#C
C
#include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h>   typedef uint32_t pint; typedef uint64_t xint; typedef unsigned int uint; #define PRIuPINT PRIu32 /* printf macro for pint */ #define PRIuXINT PRIu64 /* printf macro for xint */ #define MAX_FACTORS 63 /* b...
Give a code snippet in #C The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prim...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
(defun sleeprint(n) (sleep (/ n 10)) (format t "~a~%" n))   (loop for arg in (cdr sb-ext:*posix-argv*) doing (sb-thread:make-thread (lambda() (sleeprint (parse-integer arg)))))   (loop while (not (null (cdr (sb-thread:list-all-threads)))))
Give a code snippet in #Common_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 | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#Julia
Julia
  cmd = "eventcreate /T INFORMATION /ID 123 /D \"Rosetta Code Write to Windows event log task example\"" Base.run(`$cmd`)  
Give a code snippet in #Julia Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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 ...
#PowerShell
PowerShell
  function Get-Ranking { [CmdletBinding(DefaultParameterSetName="Standard")] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string] ...
Give a code snippet in #PowerShell 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/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#TI-89_BASIC
TI-89 BASIC
str = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF."
Give a code snippet in #TI-89_BASIC Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special charact...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#F.23
F#
  // Find Antı-Primes plus. Nigel Galloway: April 9th., 2019 // Increasing the value 14 will increase the number of anti-primes plus found let fI=primes|>Seq.take 14|>Seq.map bigint|>List.ofSeq let N=Seq.reduce(*) fI let fG g=Seq.unfold(fun ((n,i,e) as z)->Some(z,(n+1,i+1,(e*g)))) (1,2,g) let fE n i=n|>Seq.collect(fun...
Give a code snippet in #F.23 Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Seq...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#TUSCRIPT
TUSCRIPT
  $$ MODE DATA $$ script=* /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */   /** * Another comment. */ function something() { } $$ MODE TUSCRIPT ERROR/STOP C...
Give a code snippet in #TUSCRIPT A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Aime
Aime
text next(text s) { integer c, e, l; index v; data d;   l = ~s; while (l) { v[-s[l -= 1]] += 1; }   for (c, e in v) { b_form(d, "%d%c", e, -c); }   return d; }   integer depth(text s, integer i, record r) { integer d;   d = 0; r_j_integer(d, r, s); if ...
Give a code snippet in #Aime There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 31131...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ada
Ada
with Ada.Text_IO; with Ada.Command_Line; use Ada.Command_Line; procedure SleepSort is task type PrintTask (num : Integer); task body PrintTask is begin delay Duration (num) / 100.0; Ada.Text_IO.Put(num'Img); end PrintTask; type TaskAcc is access PrintTask; TaskList : array (1 .. Argument_Coun...
Give a code snippet in #Ada Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Tcl
Tcl
Define cubic(p1,p2,p3,segs) = Prgm Local i,t,u,prev,pt 0 → pt For i,1,segs+1 (i-1.0)/segs → t © Decimal to avoid slow exact arithetic (1-t) → u pt → prev u^2*p1 + 2*t*u*p2 + t^2*p3 → pt If i>1 Then PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2]) EndIf E...
Give a code snippet in #Tcl Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Jacobsthal_numbers
Jacobsthal numbers
Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J0 = 0 J1 = 1 Jn = Jn-1 + 2 ×...
#Sidef
Sidef
func jacobsthal(n) { lucasU(1, -2, n) }   func lucas_jacobsthal(n) { lucasV(1, -2, n) }   say "First 30 Jacobsthal numbers:" say 30.of(jacobsthal)   say "\nFirst 30 Jacobsthal-Lucas numbers:" say 30.of(lucas_jacobsthal)   say "\nFirst 20 Jacobsthal oblong numbers:" say 21.of(jacobsthal).cons(2, {|a,b| a * b }) ...
Give a code snippet in #Sidef Jacobsthal numbers are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J0 =...
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 ≤...
#XQuery
XQuery
  (: Using the EXPath File Module, which is built into most XQuery processors by default and thus does not need to get imported. Some processors bind the namespace automatically, others require explicit declaration. :)   xquery version "3.1";   declare namespace file = 'http://expath.org/ns/file';   let $in ...
Give a code snippet in #XQuery 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, separat...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#11l
11l
F euler(f, y0, a, b, h) V t = a V y = y0 L t <= b print(‘#2.3 #2.3’.format(t, y)) t += h y += h * f(t, y)   V newtoncooling = (time, temp) -> -0.07 * (temp - 20)   euler(newtoncooling, 100.0, 0.0, 100.0, 10.0)
Give a code snippet in #11l Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Elixir
Elixir
File.write("file.txt", string)
Give a code snippet in #Elixir Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Ela
Ela
type Point = Point x y   instance Show Point where show (Point x y) = "Point " ++ (show x) ++ " " ++ (show y)   instance Name Point where getField nm (Point x y) | nm == "x" = x | nm == "y" = y | else = fail "Undefined name." isField nm _ = nm == "x" || nm == "y"   pointX = flip Point 0   pointY = Poi...
Give a code snippet in #Ela Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula
Thiele's interpolation formula
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Thiele's interpolation formula is an interpolation ...
#11l
11l
F thieleInterpolator(x, y) V ρ = enumerate(y).map((i, yi) -> [yi] * (@y.len - i)) L(i) 0 .< ρ.len - 1 ρ[i][1] = (x[i] - x[i + 1]) / (ρ[i][0] - ρ[i + 1][0]) L(i) 2 .< ρ.len L(j) 0 .< ρ.len - i ρ[j][i] = (x[j] - x[j + i]) / (ρ[j][i - 1] - ρ[j + 1][i - 1]) + ρ[j + 1][i - 2] V ρ0 = ρ[0] ...
Give a code snippet in #11l This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Thiele's interpolation...
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,...
#Yabasic
Yabasic
dim a(10) // create a numeric array with 11 elements, from 0 to 10 // Indexed at your preference (0 to 9 or 1 to 10) print arraysize(a(), 1) // this function return the element's higher number of an array   a(7) = 12.3 // access to an element of the array redim a(20) // alias of 'dim'. Grouth size of array  ...
Give a code snippet in #Yabasic This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and ret...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Lua
Lua
--9x9 sudoku solver in lua --based on a branch and bound solution --fields are not tried in plain order --but in a way to detect dead ends earlier concat=table.concat insert=table.insert constraints = { } --contains a table with 3 constraints for every field -- a contraint "cons" is a table containing all fields whic...
Give a code snippet in #Lua Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#QB64
QB64
'declare and initialize variables CONST PI = 3.141592   DIM SHARED Bob_X, Bob_Y, Pivot_X, Pivot_Y, Rod_Length, Rod_Angle, Bob_Angular_Acceleration, Bob_Angular_Velocity, Delta_Time, Drawing_Scale, G AS DOUBLE DIM SHARED exit_flag AS INTEGER   'set gravity to Earth's by default (in m/s squared) G = -9.80665   'set the p...
Give a code snippet in #QB64 One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and an...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#PHP
PHP
$max = 1000; $sum = 0; for ($i = 1 ; $i < $max ; $i++) { if (($i % 3 == 0) or ($i % 5 == 0)) { $sum += $i; } } echo $sum, PHP_EOL;  
Give a code snippet in #PHP Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Batch_File
Batch File
  @echo off   :_main setlocal call:_func1 _func2 3 pause>nul exit/b   :_func1 setlocal enabledelayedexpansion for /l %%i in (1,1,%2) do call:%1 exit /b   :_func2 setlocal echo _func2 has been executed exit /b  
Give a code snippet in #Batch_File Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#Eiffel
Eiffel
  class LARGEST_LEFT_TRUNCABLE_PRIME   create make   feature   make -- Tests find_prime for different bases. local i: INTEGER decimal: INTEGER_64 do from i := 3 until i = 10 loop largest := 0 find_prime ("", i) decimal := convert_to_decimal (largest, i) io.put_string (i....
Give a code snippet in #Eiffel A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2....
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: ...
#C
C
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h>   int main() { wchar_t pi = L'\u03c0'; /* Small pi symbol */ wchar_t ae = L'\u2245'; /* Approximately equals symbol */ double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci +...
Give a code snippet in #C 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Clojure
Clojure
(defn get-code [c] (case c (\B \F \P \V) 1 (\C \G \J \K \Q \S \X \Z) 2 (\D \T) 3 \L 4 (\M \N) 5 \R 6 nil)) ;(\A \E \I \O \U \H \W \Y)   (defn soundex [s] (let [[f & s] (.toUpperCase s)] (-> (map get-code s) distinct (concat , "0000") (->> (cons f ,) (remove nil? ,) ...
Give a code snippet in #Clojure Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#EchoLisp
EchoLisp
  ;; bump count when letter added (define (hash-counter hash key ) ;; (set! key (string-downcase key)) - if ignore case wanted (putprop hash (1+ (or (getprop hash key) 0 )) key))   ;; apply to exploded string ;; and sort result (define (hash-compare a b) ( < (first a) (first b))) (define (count-letters hash strin...
Give a code snippet in #EchoLisp Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (...
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
#Huginn
Huginn
from Algorithms import materialize, zip;   main() { keys = [1, 2, 3]; values = ['a', 'b', 'c']; hash = materialize( zip( key, values ), lookup ); }
Give a code snippet in #Huginn 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/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-digit law, refers to the freque...
#R
R
  pbenford <- function(d){ return(log10(1+(1/d))) }   get_lead_digit <- function(number){ return(as.numeric(substr(number,1,1))) }   fib_iter <- function(n){ first <- 1 second <- 0 for(i in 1:n){ sum <- first + second first <- second second <- sum } return(sum) }   fib_sequence <- mapply(fib_i...
Give a code snippet in #R This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-digi...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Wren
Wren
import "/fmt" for Fmt import "/seq" for Lst   var encode = Fn.new { |s| if (s.isEmpty) return [] var symbols = "abcdefghijklmnopqrstuvwxyz".toList var result = List.filled(s.count, 0) var i = 0 for (c in s) { var index = Lst.indexOf(symbols, c) if (index == -1) Fiber.abort("%(s) con...
Give a code snippet in #Wren Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful ...
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 ...
#VBA
VBA
Option Explicit   Sub Main() Dim s As String, FF As Integer   'read a file line by line FF = FreeFile Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF While Not EOF(FF) Line Input #FF, s Debug.Print s Wend Close #FF   'read a file FF = FreeFile Open "C:\Users\" & Environ("username"...
Give a code snippet in #VBA 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 int...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Go
Go
package main   import ( "bufio" "io" "os" )   func main() { r := bufio.NewReader(os.Stdin) w := bufio.NewWriter(os.Stdout) for { b, err := r.ReadByte() if err == io.EOF { return } w.WriteByte(b) w.Flush() } }
Give a code snippet in #Go Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Rust
Rust
const N: usize = 41; const K: usize = 3; const M: usize = 3; const POSITION: usize = 5;   fn main() { let mut prisoners: Vec<usize> = Vec::new(); let mut executed: Vec<usize> = Vec::new(); for pos in 0..N { prisoners.push(pos); }   let mut to_kill: usize = 0; let mut len: usize = prisone...
Give a code snippet in #Rust Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\d...
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...
#APL
APL
∇ HappyNumbers arg;⎕IO;∆roof;∆first;bin;iroof [1] ⍝0: Happy number [2] ⍝1: http://rosettacode.org/wiki/Happy_numbers [3] ⎕IO←1 ⍝ Index origin [4] ∆roof ∆first←2↑arg,10 ⍝ [5] [6] bin←{ [7] ⍺←⍬ ⍝ Default left arg [8] ⍵=1:...
Give a code snippet in #APL 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Racket
Racket
(define (multiply a b) (* a b))
Give a code snippet in #Racket A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Trith
Trith
1024 [dup print 2 / floor] [dup 0 >] while drop
Give a code snippet in #Trith Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwar...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#Julia
Julia
arr(s) = [c for c in s] alldup(a) = filter(x -> length(x) > 1, [findall(x -> x == a[i], a) for i in 1:length(a)]) firstduplicate(s) = (a = arr(s); d = alldup(a); isempty(d) ? nothing : first(d))   function testfunction(strings) println("String | Length | All Unique | First Duplicate | Pos...
Give a code snippet in #Julia Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its leng...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#JavaScript
JavaScript
<script>   setTimeout(function () { document.write('Awake!') }, prompt("Number of milliseconds to sleep"));   document.write('Sleeping... ');   </script>
Give a code snippet in #JavaScript Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main t...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Java
Java
import java.util.ArrayList; import java.util.Collections; import java.util.List;   public class Horner { public static void main(String[] args){ List<Double> coeffs = new ArrayList<Double>(); coeffs.add(-19.0); coeffs.add(7.0); coeffs.add(-4.0); coeffs.add(6.0); Syste...
Give a code snippet in #Java A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Erlang
Erlang
% Implemented by Arjun Sunel 1> string:strip(" Hello World! ", left). %remove leading whitespaces "Hello World! "   2> string:strip(" Hello World! ", right). % remove trailing whitespaces " Hello World!"   3> string:strip(" Hello World! ", both). % remove both leading and trailing whitespace "Hello Wor...
Give a code snippet in #Erlang Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace r...
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;   procedure Euler is Epsilon : constant  := 1.0E-15; Fact  : Long_Integer := 1; E  : Long_Float  := 2.0; E0  : Long_Float  := 0.0; N  : Long_Integer := 2;   begin   loop E0...
Give a code snippet in #Ada 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/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#GAP
GAP
a := [2, 9, 4, 7, 5, 3]; Random(a);
Give a code snippet in #GAP Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Nim
Nim
  import strutils import bignum   const PrimeProg = "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1"   iterator values(prog: openArray[Rat]; init: Natural): Int = ## Run the program "prog" with initial value "init" and yield the values. var n = newInt(init) var next: Rat while ...
Give a code snippet in #Nim FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#OCaml
OCaml
$ ocaml   # Random.self_init();; - : unit = ()   # let m = Array.make_matrix 10 10 0 ;; val m : int array array = [|[|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0...
Give a code snippet in #OCaml Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is me...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machi...
#Wren
Wren
var NOP = 0 var LDA = 1 var STA = 2 var ADD = 3 var SUB = 4 var BRZ = 5 var JMP = 6 var STP = 7   var ops = {"NOP": NOP, "LDA": LDA, "STA": STA, "ADD": ADD, "SUB": SUB, "BRZ": BRZ, "JMP": JMP, "STP": STP}   var load = Fn.new { |prog| var mem = List.filled(32, 0) var lines = prog.trimEnd().split("\n")...
Give a code snippet in #Wren Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" foun...
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 ...
#Liberty_BASIC
Liberty BASIC
'Levenshtein Distance translated by Brandon Parker '08/19/10 'from http://www.merriampark.com/ld.htm#VB 'No credit was given to the Visual Basic Author on the site :-(   Print LevenshteinDistance("kitten", "sitting") End   'Get the minum of three values Function Minimum(a, b, c) Minimum = Min(a, Min(b, c)) End Func...
Give a code snippet in #Liberty_BASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Rust
Rust
let collection = vec![1,2,3,4,5]; for elem in collection { println!("{}", elem); }
Give a code snippet in #Rust Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/...
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...
#Python
Python
# -*- coding: utf-8 -*-   from itertools import izip   def degree(poly): while poly and poly[-1] == 0: poly.pop() # normalize return len(poly)-1   def poly_div(N, D): dD = degree(D) dN = degree(N) if dD < 0: raise ZeroDivisionError if dN >= dD: q = [0] * dN while dN >= ...
Give a code snippet in #Python 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 lon...
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#PHP
PHP
<?php   $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');   for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched ? '' : $i), PHP_EOL; ...
Give a code snippet in #PHP Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Groovy
Groovy
def haversine(lat1, lon1, lat2, lon2) { def R = 6372.8 // In kilometers def dLat = Math.toRadians(lat2 - lat1) def dLon = Math.toRadians(lon2 - lon1) lat1 = Math.toRadians(lat1) lat2 = Math.toRadians(lat2)   def a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.c...
Give a code snippet in #Groovy This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equ...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Smalltalk
Smalltalk
st> FloatD infinity Inf st> 1.0 / 0.0 Inf
Give a code snippet in #Smalltalk Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherw...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Visual_Basic
Visual Basic
  Public Sub Doors100() ' the state of a door is represented by the data type boolean (false = door closed, true = door opened) Dim doorstate(1 To 100) As Boolean ' the doorstate()-array is initialized by VB with value 'false' Dim i As Long, j As Long   For i = 1 To 100 For j = i To 100 Step i d...
Give a code snippet in #Visual_Basic There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4,...
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim As Integer n   Do Input "Enter size of matrix "; n Loop Until n > 0   Dim zigzag(1 To n, 1 To n) As Integer '' all zero by default   ' enter the numbers 0 to (n^2 - 1) in the matrix's anti-diagonals zigzag(1, 1) = 0 If n > 1 Then Dim As Integer row = 0, col = 3 Dim As Boolean down = true,...
Give a code snippet in #FreeBASIC Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { for (i in 0 .. 2) { for (j in 0 .. 2) { if (i + j == 2) continue if (i + j == 3) break println(i + j) } } println() if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments shou...
Give a code snippet in #Kotlin Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct...
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) ...
#Ruby
Ruby
1.upto(100) do |n| print "Fizz" if a = (n % 3).zero? print "Buzz" if b = (n % 5).zero? print n unless (a || b) puts end
Give a code snippet in #Ruby 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/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 ≤...
#Oberon-2
Oberon-2
MODULE ab;   IMPORT In, Out;   VAR A, B : INTEGER;   BEGIN In.Int (A); In.Int (B); Out.Int (A + B, 8); Out.Ln END ab.
Give a code snippet in #Oberon-2 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, separ...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Octave
Octave
system("ls");
Give a code snippet in #Octave Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Oz
Oz
declare class Something feat name %% immutable, public attribute (called a "feature") attr count %% mutable, private attribute   %% public method which is used as an initializer meth init(N) self.name = N count := 0 end   %% public method meth increas...
Give a code snippet in #Oz In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class....
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Klingphix
Klingphix
:sq_mul  %c %i ( ) !c len [  !i $i get rot $i get rot * $c swap 0 put !c ] for $c ;   :sq_sum 0 swap len [ get rot + swap ] for swap ;   ( 1 3 -5 ) ( 4 -2 -1 ) sq_mul sq_sum pstack   " " input
Give a code snippet in #Klingphix Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#J
J
pad=: 0,0,~0,.0,.~] life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@pad NB. the above could also be a one-line solution: life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@(0,0,~0,.0,.~])  
Give a code snippet in #J The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in ...
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 ...
#GAP
GAP
Filtered([2008 .. 2121], y -> WeekDay([25, 12, y]) = "Sun"); # [ 2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118 ]   # A possible implementation of WeekDayAlt   days := ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];;   WeekDayAlt := function(args) local d, m, ...
Give a code snippet in #GAP 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 20...
christopher/rosetta-code