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/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Java
Java
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException;   class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.le...
Give a code snippet in #Java DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#XLISP
XLISP
(defun logical-functions (a b) (print `(a and b = ,(and a b))) (print `(a or b = ,(or a b))) (print `(not a = ,(not a))) )
Give a code snippet in #XLISP Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, base...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use feature qw{ say };   use JSON::PP; use Time::Piece;   use constant { NAME => 0, CATEGORY => 1, DATE => 2, DB => 'simple-db', };   my $operation = shift // "";   my %dispatch = ( n => \&add_new, l => \&print_latest, L => \&print_late...
Give a code snippet in #Perl Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Yabasic
Yabasic
// Charles Babbage habría sabido que solo un número que termina en 4 o 6 // podría producir un cuadrado que termina en 6, y cualquier número por // debajo de 520 produciría un cuadrado menor que 269696. Podemos detenernos // cuando hayamos alcanzado 99736, sabemos que es cuadrado y termina en 269696.   number = 524 // ...
Give a code snippet in #Yabasic Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#C
C
int isPrime(int n){ if (n%2==0) return n==2; if (n%3==0) return n==3; int d=5; while(d*d<=n){ if(n%d==0) return 0; d+=2; if(n%d==0) return 0; d+=4;} return 1;}   main() {int i,d,p,r,q=929; if (!isPrime(q)) return 1; r=q; while(r>0) r<<=1; d=2*q+1; do { for(p=r, i= 1; p; p<<= 1){ i=((long long)i *...
Give a code snippet in #C A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before start...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#Rust
Rust
fn splitter(string: &str) -> String { let chars: Vec<_> = string.chars().collect(); let mut result = Vec::new(); let mut last_mismatch = 0; for i in 0..chars.len() { if chars.len() == 1 { return chars[0..1].iter().collect(); } if i > 0 && chars[i-1] != chars[i] { ...
Give a code snippet in #Rust Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Perl
Perl
use strict; use warnings;   sub stern_brocot { my @list = (1, 1); sub { push @list, $list[0] + $list[1], $list[1]; shift @list; } }   { my $generator = stern_brocot; print join ' ', map &$generator, 1 .. 15; print "\n"; }   for (1 .. 10, 100) { my $index = 1; my $generator = stern_bro...
Give a code snippet in #Perl For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#D
D
import std.stdio, std.random;   void main() { const items = ["foo", "bar", "baz"]; items[uniform(0, $)].writeln; }
Give a code snippet in #D Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#PicoLisp
PicoLisp
(scl 2)   (de price (Pr) (format (cdr (rank Pr (quote (0.00 . 0.10) (0.06 . 0.18) (0.11 . 0.26) (0.16 . 0.32) (0.21 . 0.38) (0.26 . 0.44) (0.31 . 0.50) (0.36 . 0.54) ...
Give a code snippet in #PicoLisp A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   a...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#AutoHotkey
AutoHotkey
exact_equality(a,b){ return (a==b) } exact_inequality(a,b){ return !(a==b) } equality(a,b){ return (a=b) } inequality(a,b){ return !(a=b) } ordered_before(a,b){ return ("" a < "" b) } ordered_after(a,b){ return ("" a > "" b) }
Give a code snippet in #AutoHotkey Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#PureBasic
PureBasic
Procedure Counting_sort(Array data_array(1), min, max) Define i, j Dim c(max - min)   For i = 0 To ArraySize(data_array()) c(data_array(i) - min) + 1 Next   For i = 0 To ArraySize(c()) While c(i) data_array(j) = i + min j + 1 c(i) - 1 Wend Next EndProcedure
Give a code snippet in #PureBasic Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Nemerle
Nemerle
using System; using System.IO; using System.Console;   module DeleteFile { Main() : void { when (File.Exists("input.txt")) File.Delete("input.txt"); try { when (File.Exists(@"\input.txt")) File.Delete(@"\input.txt"); } catch { |e is UnauthorizedAccessExcep...
Give a code snippet in #Nemerle Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Ring
Ring
  aString = "radar" bString = "" for i=len(aString) to 1 step -1 bString = bString + aString[i] next see aString if aString = bString see " is a palindrome." + nl else see " is not a palindrome" + nl ok  
Give a code snippet in #Ring A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Frink
Frink
URLDecode["google.com/search?q=%60Abdu%27l-Bah%C3%A1","UTF8"]
Give a code snippet in #Frink This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded ...
christopher/rosetta-code
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Ruby
Ruby
Pt = Struct.new(:x, :y) Circle = Struct.new(:x, :y, :r)   def circles_from(pt1, pt2, r) raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0 # handle single point and r == 0 return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0 dx, dy = pt2.x - pt1.x, pt2.y - pt1...
Give a code snippet in #Ruby Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#Go
Go
package main   import ( "fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort" )   func main() { if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err...
Give a code snippet in #Go Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime,...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Factor
Factor
$ factor -run=none -e="USE: io \"hi\" print"
Give a code snippet in #Factor Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementat...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#AWK
AWK
function fact_r(n) { if ( n <= 1 ) return 1; return n*fact_r(n-1); }
Give a code snippet in #AWK Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a num...
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...
#Axe
Axe
Lbl LINK r₂→{r₁}ʳ 0→{r₁+2}ʳ r₁ Return   Lbl NEXT {r₁+2}ʳ Return   Lbl VALUE {r₁}ʳ Return
Give a code snippet in #Axe 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 defin...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Julia
Julia
methods(methods) methods(println)
Give a code snippet in #Julia Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#B
B
main() { putstr("Goodbye, World!"); return(0); }
Give a code snippet in #B Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard ...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#PowerShell
PowerShell
  function div ($a, $b) { try{$a/$b} catch{"Bad parameters: `$a = $a and `$b = $b"} } div 10 2 div 1 0  
Give a code snippet in #PowerShell Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#E
E
[1,2,3,2,3,4].asSet().getElements()
Give a code snippet in #E Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O...
christopher/rosetta-code
http://rosettacode.org/wiki/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#Objeck
Objeck
  bundle Default { class CompileTime { function : Main(args : String[]) ~ Nil { (10*9*8*7*6*5*4*3*2*1)->PrintLine(); } } }  
Give a code snippet in #Objeck Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Transd
Transd
#lang transd   MainModule: { _start: (λ (textout (max 9 6 2 11 3 4) " ") (with v [1, 45, 7, 274, -2, 34] (textout (max-element v) " ") (textout (max-element-idx v)) )) }
Give a code snippet in #Transd Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#Perl
Perl
#!/usr/bin/perl use strict ; use warnings ;   sub longestCommonSubstr { my $first = shift ; my $second = shift ; my %firstsubs = findSubstrings ( $first ); my %secondsubs = findSubstrings ( $second ) ; my @commonsubs ; foreach my $subst ( keys %firstsubs ) { if ( exists $secondsubs{ $subst } ) {...
Give a code snippet in #Perl Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecuti...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Fortran
Fortran
program mandelbrot   implicit none integer , parameter :: rk = selected_real_kind (9, 99) integer , parameter :: i_max = 800 integer , parameter :: j_max = 600 integer , parameter :: n_max = 100 real (rk), parameter :: x_centre = -0.5_rk real (rk), parameter :: y_centre = 0.0_rk r...
Give a code snippet in #Fortran Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two...
#Perl
Perl
use Image::Imlib2;   my $img1 = Image::Imlib2->load('Lenna50.jpg') || die; my $img2 = Image::Imlib2->load('Lenna100.jpg') || die;   my $w = $img1->width; my $h = $img1->height;   my $sum = 0;   for my $x (0..$w-1) { for my $y (0..$h-1) { my ($r1, $g1, $b1) = $img1->query_pixel($x, $y); my ($r2, $g2...
Give a code snippet in #Perl basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The exp...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def sequence /# ( ini end [step] ) #/ ( ) swap for 0 put endfor enddef   1000 var limit   ( 1 limit ) sequence   ( 2 limit ) for >ps ( tps dup * limit tps ) for dup limit < if 0 swap set else drop endif endfor cps endfor ( 1 limit 0 ) remove pstack
Give a code snippet in #Phixmonti This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Elixir
Elixir
defmodule RC do def sierpinski_triangle(n) do f = fn(x) -> IO.puts "#{x}" end Enum.each(triangle(n, ["*"], " "), f) end   defp triangle(0, down, _), do: down defp triangle(n, down, sp) do newDown = (for x <- down, do: sp<>x<>sp) ++ (for x <- down, do: x<>" "<>x) triangle(n-1, newDown, sp<>sp) ...
Give a code snippet in #Elixir Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Haskell
Haskell
import qualified Data.List as L import System.IO import System.Random   data CoinToss = H | T deriving (Read, Show, Eq)   parseToss :: String -> [CoinToss] parseToss [] = [] parseToss (s:sx) | s == 'h' || s == 'H' = H : parseToss sx | s == 't' || s == 'T' = T : parseToss sx | otherwise = parseToss sx   notToss ::...
Give a code snippet in #Haskell Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads,...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#PowerShell
PowerShell
function invmod($a,$n){ if ([int]$n -lt 0) {$n = -$n} if ([int]$a -lt 0) {$a = $n - ((-$a) % $n)}   $t = 0 $nt = 1 $r = $n $nr = $a % $n while ($nr -ne 0) { $q = [Math]::truncate($r/$nr) $tmp = $nt $nt = $t - $q*$nt $t = $tmp $tmp = $nr $nr = $r - $q*$nr $r = $tmp } if ($r -gt 1) {r...
Give a code snippet in #PowerShell From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#AutoHotkey
AutoHotkey
  ; Author: AlephX, Aug 18 2011 data = %A_scriptdir%\rosettaconfig.txt comma := ","   Loop, Read, %data% { if NOT (instr(A_LoopReadLine, "#") == 1 OR A_LoopReadLine == "")   { if instr(A_LoopReadLine, ";") == 1 { parameter := RegExReplace(Substr(A_LoopReadLine,2), "^[ \s]+|[ \s]+$", "") %parameter% = "1...
Give a code snippet in #AutoHotkey The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#C.2B.2B
C++
#include <vector> #include <iostream> #include <algorithm> #include <sstream> #include <string> #include <cmath>   bool isPrime ( int number ) { if ( number <= 1 ) return false ; if ( number == 2 ) return true ; for ( int i = 2 ; i <= std::sqrt( number ) ; i++ ) { if ( number % i == 0 ) re...
Give a code snippet in #C.2B.2B An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th ...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#Factor
Factor
USE: math.vectors : accum-left ( seq id quot -- seq ) accumulate nip ; inline : accum-right ( seq id quot -- seq ) [ <reversed> ] 2dip accum-left <reversed> ; inline : equilibrium-indices ( seq -- inds ) 0 [ + ] [ accum-left ] [ accum-right ] 3bi [ = ] 2map V{ } swap dup length iota [ [ suffix ] curry [ ] if ] 2eac...
Give a code snippet in #Factor An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#RLaB
RLaB
  >> sum( (1 ./ [1:1000]) .^ 2 ) - const.pi^2/6 -0.000999500167  
Give a code snippet in #RLaB Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Pascal
Pascal
program TemperatureConvert;   type TemperatureType = (C, F, K, R);   var kelvin: real;   function ConvertTemperature(temperature: real; fromType, toType: TemperatureType): real;   var initial, result: real;   begin (* We are going to first convert whatever we're given into Celsius. ...
Give a code snippet in #Pascal There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#Oz
Oz
declare [Path] = {Module.link ['x-oz://system/os/Path.ozf']} [Regex] = {Module.link ['x-oz://contrib/regex']}   Files = {Filter {Path.readdir "."} Path.isFile} Pattern = ".*\\.oz$" MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end} in {ForAll MatchingFiles System.showInfo}
Give a code snippet in #Oz Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Rescale[#,{0,10},{-1,0}]&/@Range[0,10]
Give a code snippet in #Mathematica.2FWolfram_Language Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#Java
Java
import java.util.*;   public class SetConsolidation {   public static void main(String[] args) { List<Set<Character>> h1 = hashSetList("AB", "CD"); System.out.println(consolidate(h1));   List<Set<Character>> h2 = hashSetList("AB", "BD"); System.out.println(consolidateR(h2));   ...
Give a code snippet in #Java Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input se...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#PowerShell
PowerShell
$reader = [System.IO.File]::OpenText($mancorfile) try { do { $line = $reader.ReadLine() if ($line -eq $null) { break } DoSomethingWithLine($line) } while ($TRUE) } finally { $reader.Close() }  
Give a code snippet in #PowerShell Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Oz
Oz
declare fun {NextTriangle Triangle} Sp = {Spaces {Length Triangle}} in {Flatten [{Map Triangle fun {$ X} Sp#X#Sp end} {Map Triangle fun {$ X} X#" "#X end} ]} end   fun {Spaces N} if N == 0 then nil else & |{Spaces N-1} end end   fun lazy {Iterate F X} X|{Iterate F {F X}} end ...
Give a code snippet in #Oz Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Ruby
Ruby
# stripped version of Andrea Fazzi's submission to Ruby Quiz #179   class Modulo include Comparable   def initialize(n = 0, m = 13) @n, @m = n % m, m end   def to_i @n end   def <=>(other_n) @n <=> other_n.to_i end   [:+, :-, :*, :**].each do |meth| define_method(meth) { |other_n| Modulo...
Give a code snippet in #Ruby Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, tw...
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...
#D
D
import std.stdio, std.algorithm, std.conv;   string[] selfReferentialSeq(string n, string[] seen=[]) nothrow { __gshared static string[][string] cache; if (n in cache) return cache[n]; if (seen.canFind(n)) return [];   int[10] digit_count; foreach (immutable d; n) digit_count...
Give a code snippet in #D 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, 31131122...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#FreeBASIC
FreeBASIC
' version 08-04-2017 ' compile with: fbc -s console   Sub Subfactorial(a() As ULongInt)   Dim As ULong i Dim As ULongInt num   For i = 0 To UBound(a) num = num * i If (i And 1) = 1 Then num -= 1 Else num += 1 End If a(i) = num Next   End Su...
Give a code snippet in #FreeBASIC A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' One way to return multiple values is to use ByRef parameters for the additional one(s) Function tryOpenFile (fileName As String, ByRef fileNumber As Integer) As Boolean Dim result As Integer fileNumber = FreeFile result = Open(fileName For Input As # fileNumber) If result <> 0 Then ...
Give a code snippet in #FreeBASIC Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#jq
jq
def catalan: if . == 0 then 1 elif . < 0 then error("catalan is not defined on \(.)") else (2 * (2*. - 1) * ((. - 1) | catalan)) / (. + 1) end;
Give a code snippet in #jq Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Gener...
#Xojo
Xojo
    Function ShuntingYard(strInfix As String) As String     Dim i as Integer Dim token, tokenArray() As String Dim stack(), queue() As Variant Dim discard As String Dim op1, op2 As String   Dim Left_Brackets, Right_Brackets As Integer   Dim output As String Dim dbl_output As Double     Left_Brackets =...
Give a code snippet in #Xojo Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens represent...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Haskell
Haskell
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { mem...
Give a code snippet in #Haskell Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly impl...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Standard_ML
Standard ML
open XWindows ; open Motif ;   val helloWindow = fn () =>   let val shell = XtAppInitialise "" "demo" "top" [] [XmNwidth 400, XmNheight 300 ] ; val main = XmCreateMainWindow shell "main" [XmNmappedWhenManaged true ] ; val text = XmCreateLabel main "show" [ XmNlabelString "Hello World!"] in   ( XtMan...
Give a code snippet in #Standard_ML Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#Go
Go
package main   import ( "fmt" "log" )   var limits = [][2]int{ {3, 10}, {11, 18}, {19, 36}, {37, 54}, {55, 86}, {87, 118}, }   func periodicTable(n int) (int, int) { if n < 1 || n > 118 { log.Fatal("Atomic number is out of range.") } if n == 1 { return 1, 1 } if n == 2 { ...
Give a code snippet in #Go Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 1...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#J
J
require '~addons/ide/qt/qt.ijs' getsha1=: 'sha1'&gethash_jqtide_ getsha1 'Rosetta Code' 48c98f7e5a6e736d790ab740dfc3f51a61abe2b5
Give a code snippet in #J SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identif...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Fantom
Fantom
  class Main { public static Void main () { str := "Hello,How,Are,You,Today" words := str.split(',') words.each |Str word| { echo ("${word}. ") } } }  
Give a code snippet in #Fantom Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks r...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Octave
Octave
# I am a comment till the end of line % I am a comment till the end of line %{ This comment spans multiple lines %}  
Give a code snippet in #Octave Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Ruby
Ruby
system 'clear'
Give a code snippet in #Ruby Task Clear the terminal window.
christopher/rosetta-code
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#Python
Python
from math import isqrt   def juggler(k, countdig=True, maxiters=1000): m, maxj, maxjpos = k, k, 0 for i in range(1, maxiters): m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m) if m >= maxj: maxj, maxjpos = m, i if m == 1: print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str...
Give a code snippet in #Python Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in th...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Smalltalk
Smalltalk
$!/?\=false= + =true=# \-/
Give a code snippet in #Smalltalk Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Java
Java
void convertToGrayscale(final BufferedImage image){ for(int i=0; i<image.getWidth(); i++){ for(int j=0; j<image.getHeight(); j++){ int color = image.getRGB(i,j);   int alpha = (color >> 24) & 255; int red = (color >> 16) & 255; int green = (color >> 8) & 255; ...
Give a code snippet in #Java 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/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#UNIX_Shell
UNIX Shell
a=(1 2 3 4 5) unset e[@] for ((i=0;i<${#a[@]};i++)); do [ $((a[$i]%2)) -eq 0 ] && e[$i]="${a[$i]}" done
Give a code snippet in #UNIX_Shell Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#Haskell
Haskell
import System.Random import Data.List import Control.Monad import Control.Arrow   distribCheck :: IO Int -> Int -> Int -> IO [(Int,(Int,Bool))] distribCheck f n d = do nrs <- replicateM n f let group = takeWhile (not.null) $ unfoldr (Just. (partition =<< (==). head)) nrs avg = (fromIntegral n) / fromInteg...
Give a code snippet in #Haskell This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing rando...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Openscad
Openscad
// This will produce a simple cuboid cube([2,3,4]);  
Give a code snippet in #Openscad Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Ursala
Ursala
#import std   permsort "p" = ~&ihB+ ordered"p"*~+ permutations   #cast %sL   example = permsort(lleq) <'pmf','oao','ejw','hhp','oqh','ock','dwj'>
Give a code snippet in #Ursala Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#COBOL
COBOL
identification division. program-id. box-compass. data division. working-storage section. 01 point pic 99. 01 degrees usage float-short. 01 degrees-rounded pic 999v99. 01 show-degrees pic zz9.99. 01 box ...
Give a code snippet in #COBOL There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and di...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#AWK
AWK
•Out "dsdfsdfsad ""fsadf""sdf"
Give a code snippet in #AWK A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed ...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Fortran
Fortran
include ''char-literal-constant''
Give a code snippet in #Fortran Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#zkl
zkl
fcn isNum(text){ try{ text.toInt(); True } catch{ try{ text.toFloat(); True } catch{ False } } }
Give a code snippet in #zkl Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Arr...
christopher/rosetta-code
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#FreeBASIC
FreeBASIC
  #include "isprime.bas"   dim as ulongint M(0 to 41) M(0) = 1 : M(1) = 1 print "1" : print "1" for n as integer = 2 to 41 M(n) = M(n-1) for i as uinteger = 0 to n-2 M(n) += M(i)*M(n-2-i) next i print M(n), if isprime(M(n)) then print "is a prime" else print next n  
Give a code snippet in #FreeBASIC Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Nim
Nim
for i in 1..5: for j in 1..i: stdout.write("*") echo("")
Give a code snippet in #Nim “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structure...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Python
Python
# See the class definitions and constructors with, e.g. getClass("pixmapIndexed", package=pixmap) pixmapIndexed   # Image with all one colour plot(p1 <- pixmapIndexed(matrix(0, nrow=3, ncol=4), col="red"))   # Image with one pixel specified cols <- rep("blue", 12); cols[7] <- "red" plot(p2 <- pixmapIndexed(matrix(1:1...
Give a code snippet in #Python Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB c...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Wren
Wren
var calc = Fn.new { |f, n| var t = 0 for (i in n..1) { var p = f.call(i) t = p[1] / (p[0] + t) } return f.call(0)[0] + t }   var pList = [ ["sqrt(2)", Fn.new { |n| [(n > 0) ? 2 : 1, 1] }], ["e ", Fn.new { |n| [(n > 0) ? n : 2, (n > 1) ? n - 1 : 1] }], ["pi ", Fn.new ...
Give a code snippet in #Wren continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to writ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Racket
Racket
#lang racket   (define (multi-factorial-fn m) (lambda (n) (let inner ((acc 1) (n n)) (if (<= n m) (* acc n) (inner (* acc n) (- n m))))))   ;; using (multi-factorial-fn m) as a first-class function (for*/list ([m (in-range 1 (add1 5))] [mf-m (in-value (multi-factorial-fn m))]) (for/list ([n (in-...
Give a code snippet in #Racket The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\di...
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...
#Rust
Rust
import scala.util.Random   /** * Histogram of 200 throws with two dices. */ object Throws extends App { Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2) .take(200).groupBy(identity).toList.sortBy(_._1) .foreach { case (a, b) => println(f"$a%2d:" + "X" * b.size) } }
Give a code snippet in #Rust 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your p...
#zkl
zkl
var [const] MsgHash=Import.lib("zklMsgHash"); var [const] gotEm=Atomic.Int(); // global signal for all threads   const THREADS=9, // how we will split task, THREADS<=26 CHR_a="a".toAsc();   fcn crack(c,n,hashes){ // thread sha256:=MsgHash.SHA256; // the SHA-256 hash method, byte bucket bytes,hash := Data(...
Give a code snippet in #zkl Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56a...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Forth
Forth
:noname dup . ." bottles" ; :noname ." 1 bottle"  ; :noname ." no more bottles" ; create bottles , , ,   : .bottles dup 2 min cells bottles + @ execute ; : .beer .bottles ." of beer" ; : .wall .beer ." on the wall" ; : .take ." Take one down, pass it around" ; : .verse .wall cr .beer cr ...
Give a code snippet in #Forth Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
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
#11l
11l
V keys = [‘a’, ‘b’, ‘c’] V values = [1, 2, 3] V hash_ = Dict(zip(keys, values)) print(hash_)
Give a code snippet in #11l 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/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Phix
Phix
without js -- (no class yet) class Fib private function fib_i(integer n) return iff(n<2?n:this.fib_i(n-1)+this.fib_i(n-2)) end function public function fib(integer n) if n<0 then throw("constraint error") end if return this.fib_i(n) end function end class Fib f = new() function ...
Give a code snippet in #Phix While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwante...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#LSE64
LSE64
t : " true" ,t f : " false" ,t true if t false ifnot f true ifelse t f
Give a code snippet in #LSE64 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#CLU
CLU
% Binary search in an array % If the item is found, returns `true' and the index; % if the item is not found, returns `false' and the leftmost insertion point % The datatype must support the < and > operators. binary_search = proc [T: type] (a: array[T], val: T) returns (bool, int) where T has lt: proct...
Give a code snippet in #CLU A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret num...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#Wren
Wren
import "/dynamic" for Enum import "/trait" for Comparable import "/fmt" for Fmt import "/str" for Str import "/math" for Nums import "/sort" for Sort import "random" for Random   var Color = Enum.create("Color", ["RED", "GREEN", "PURPLE"]) var Symbol = Enum.create("Symbol", ["OVAL", "SQUIGGLE", "DIAMOND"]) var Nu...
Give a code snippet in #Wren Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, n...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Scala
Scala
case class Pair(name:String, value:Double) val input = Array(Pair("Krypton", 83.798), Pair("Beryllium", 9.012182), Pair("Silicon", 28.0855)) input.sortBy(_.name) // Array(Pair(Beryllium,9.012182), Pair(Krypton,83.798), Pair(Silicon,28.0855))   // alternative versions: input.sortBy(struct => (struct.name, struct.value))...
Give a code snippet in #Scala Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#CoffeeScript
CoffeeScript
  missing_permutation = (arr) -> # Find the missing permutation in an array of N! - 1 permutations.   # We won't validate every precondition, but we do have some basic # guards. if arr.length == 0 throw Error "Need more data" if arr.length == 1 return [arr[0][1] + arr[0][0]]   # Now we know that f...
Give a code snippet in #CoffeeScript ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#PARI.2FGP
PARI/GP
bc()={ my(u,v,bulls,cows); while(#vecsort(v=vector(4,i,random(9)+1),,8)<4,); while(bulls<4, u=input(); if(type(u)!="t_VEC"|#u!=4,next); bulls=sum(i=1,4,u[i]==v[i]); cows=sum(i=1,4,sum(j=1,4,i!=j&v[i]==u[j])); print("You have "bulls" bulls and "cows" cows") ) };
Give a code snippet in #PARI.2FGP Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if ...
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...
#Forth
Forth
( ANSI terminal control lexicon ) DECIMAL   ( support routines) 27 CONSTANT ESC : <##> ( n -- ) ( sends n, radix 10, no spaces) BASE @ >R DECIMAL 0 <# #S #> TYPE R> BASE ! ;   : ESC[ ( -- ) ESC EMIT ." [" ;   ( ANSI terminal commands as Forth words) : <CUU> ( row --) ESC[ <##> ." A" ; : <CUD> ( r...
Give a code snippet in #Forth 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 (with...
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 ...
#Haskell
Haskell
import System.Environment import Control.Concurrent import Control.Monad   sleepSort :: [Int] -> IO () sleepSort values = do chan <- newChan forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time)) forM_ values (\_ -> readChan chan >>= print)   main :: IO () main = getA...
Give a code snippet in #Haskell 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/RIPEMD-160
RIPEMD-160
RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a string of octets. Use the ASCII encoded string “Rosetta Cod...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Hash["Rosetta code","RIPEMD160","HexString"]
Give a code snippet in #Mathematica.2FWolfram_Language RIPEMD-160 is another hash function; it computes a 160-bit message digest. There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160. For padding the message, RIPEMD-160 acts like MD4 (RFC 1320). Find the RIPEMD-160 message digest of a str...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Kotlin
Kotlin
// Version 1.3.21   import java.math.BigInteger import kotlin.math.sqrt   const val MAX = 33   fun isPrime(n: Int) = BigInteger.valueOf(n.toLong()).isProbablePrime(10)   fun generateSmallPrimes(n: Int): List<Int> { val primes = mutableListOf<Int>() primes.add(2) var i = 3 while (primes.size < n) { ...
Give a code snippet in #Kotlin Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Rust
Rust
  fn same_digits(x: u64, base: u64) -> bool { let f = x % base; let mut n = x; while n > 0 { if n % base != f { return false; } n /= base; }   true } fn is_brazilian(x: u64) -> bool { if x < 7 { return false; }; if x % 2 == 0 { return t...
Give a code snippet in #Rust Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Groovy
Groovy
import java.security.MessageDigest   String.metaClass.md5Checksum = { MessageDigest.getInstance('md5').digest(delegate.bytes).collect { String.format("%02x", it) }.join('') }
Give a code snippet in #Groovy Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Oforth
Oforth
a b c f
Give a code snippet in #Oforth Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a v...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#6502_Assembly
6502 Assembly
start: LDA #(Array_End-Array)  ;evaluates to 13 RTS   Array: byte "apple",0 byte "orange",0 Array_End:
Give a code snippet in #6502_Assembly Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Lett...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Arturo
Arturo
num: "12349"   print ["The next number is:" (to :integer num)+1]
Give a code snippet in #Arturo Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Groovy
Groovy
final random = new Random()   while (true) { def random1 = random.nextInt(20) print random1 if (random1 == 10) break print ' ' println random.nextInt(20) }
Give a code snippet in #Groovy Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Haskell
Haskell
mulfac :: (Num a, Enum a) => a -> [a] mulfac k = 1 : s where s = [1 .. k] <> zipWith (*) s [k + 1 ..]   -- For single n:   mulfac1 :: (Num a, Enum a) => a -> a -> a mulfac1 k n = product [n, n - k .. 1]   main :: IO () main = mapM_ (print . take 10 . tail . mulfac) [1 .. 5]  
Give a code snippet in #Haskell The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#CoffeeScript
CoffeeScript
  sorenson = require('sieve').primes # Sorenson's extensible sieve from task: Extensible Prime Number Generator   # Test if 2^n-1 is a Mersenne prime. # assumes that the argument p is prime. # isMersennePrime = (p) -> if p is 2 then yes else n = (1n << BigInt p) - 1n s = 4n s = (s*s - 2...
Give a code snippet in #CoffeeScript Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n )...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim s(1 To 4) As String = {"&H1a", "26", "&O32", "&B11010"} '' 26 in various bases For i As Integer = 1 To 4 Print s(i); Tab(9); "="; CInt(s(i)) Next   Sleep
Give a code snippet in #FreeBASIC It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing...
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.
#PARI.2FGP
PARI/GP
for(y=1,12,printf("%2Ps| ",y);for(x=1,12,print1(if(y>x,"",x*y)"\t"));print)
Give a code snippet in #PARI.2FGP 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/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Scala
Scala
object PythagoreanTriples extends App {   println(" Limit Primatives All")   for {e <- 2 to 7 limit = math.pow(10, e).longValue() } { var primCount, tripCount = 0   def parChild(a: BigInt, b: BigInt, c: BigInt): Unit = { val perim = a + b + c val (a2, b2, c2, c3) ...
Give a code snippet in #Scala A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Bracmat
Bracmat
( out$"Number of rows? " & get':?R & -1:?I & whl ' ( 1+!I:<!R:?I & 1:?C & -1:?K & !R+-1*!I:?tabs & whl'(!tabs+-1:>0:?tabs&put$\t) & whl ' ( 1+!K:~>!I:?K & put$(!C \t\t) & !C*(!I+-1*!K)*(!K+1)^-1:?C ) & put$\n ) & )
Give a code snippet in #Bracmat Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is eith...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Nim
Nim
import sequtils, strutils   func digits(n: Natural): seq[int] = result.add n mod 10 var n = n div 10 while n != 0: result.add n mod 10 n = n div 10   proc findNarcissistic(count: Natural): seq[int] = var n = 0 m = 10 powers = toseq(0..9) while true: while n < m: var s = 0 f...
Give a code snippet in #Nim A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#XPL0
XPL0
func GCD(N, D); \Return the greatest common divisor of N and D int N, D; \numerator and denominator int R; [if D > N then [R:= D; D:= N; N:= R]; \swap D and N while D > 0 do [R:= rem(N/D); N:= D; D:= R; ]; return N; ]; \GCD   func Totient(N); \Return the totie...
Give a code snippet in #XPL0 The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the ...
christopher/rosetta-code