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/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Sidef
Sidef
require('DateTime') var (year=2016) = ARGV.map{.to_i}...   for month (1..12) { var dt = %O<DateTime>.last_day_of_month(year => year, month => month) while (dt.day_of_week != 5) { dt.subtract(days => 1) } say dt.ymd }
Give a code snippet in #Sidef Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#PowerShell
PowerShell
  function power-set ($array) { if($array) { $n = $array.Count function state($set, $i){ if($i -gt -1) { state $set ($i-1) state ($set+@($array[$i])) ($i-1) } else { "$($set | sort)" } } $set = s...
Give a code snippet in #PowerShell A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Sidef
Sidef
# Build a list of all possible solutions. The regular expression weeds # out numbers containing zeroes or repeated digits. var candidates = (1234..9876 -> grep {|n| !("#{n}" =~ /0 | (\d) .*? \1 /x) }.map{.digits});   # Repeatedly prompt for input until the user supplies a reasonable score. # The regex validates the us...
Give a code snippet in #Sidef Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those...
christopher/rosetta-code
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Python
Python
import pyaudio   chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100   p = pyaudio.PyAudio()   stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk)   data = stream.read(chunk) print [ord(i)...
Give a code snippet in #Python Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#Lingo
Lingo
now = the systemDate put now -- date( 2018, 3, 21 )   babylonianDate = date(-1800,1,1)   -- print approx. year difference between "babylonianDate" and now put (now-babylonianDate)/365.2425 -- 3818.1355
Give a code snippet in #Lingo Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the s...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Ruby
Ruby
def simple_moving_average(size) nums = [] sum = 0.0 lambda do |hello| nums << hello goodbye = nums.length > size ? nums.shift : 0 sum += hello - goodbye sum / nums.length end end   ma3 = simple_moving_average(3) ma5 = simple_moving_average(5)   (1.upto(5).to_a + 5.downto(1).to_a).each do |num| ...
Give a code snippet in #Ruby Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Haskell
Haskell
import System.IO s = "hello" s1 = s ++ " literal" main = do putStrLn (s ++ " literal") putStrLn s1
Give a code snippet in #Haskell String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string l...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#VBScript
VBScript
Function Selection_Sort(s) arr = Split(s,",") For i = 0 To UBound(arr) For j = i To UBound(arr) temp = arr(i) If arr(j) < arr(i) Then arr(i) = arr(j) arr(j) = temp End If Next Next Selection_Sort = (Join(arr,",")) End Function   WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted" WScript.StdOut....
Give a code snippet in #VBScript 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/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#OCaml
OCaml
let _mod = 1_000_000_000 let state = Array.create 55 0 let si = ref 0 let sj = ref 0   let rec subrand_seed _p1 = let p1 = ref _p1 in let p2 = ref 1 in state.(0) <- !p1 mod _mod; let j = ref 21 in for i = 1 to pred 55 do if !j >= 55 then j := !j - 55; state.(!j) <- !p2; p2 := !p1 - !p2; if !p2...
Give a code snippet in #OCaml A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {...
christopher/rosetta-code
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::Util 'min';   my %cache; sub leven { my ($s, $t) = @_; return length($t) if $s eq ''; return length($s) if $t eq ''; $cache{$s}{$t} //= do { my ($s1, $t1) = (substr($s, 1), substr($t, 1)); (substr($s, 0, 1) eq substr($t, 0, 1))...
Give a code snippet in #Perl Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. No...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Elena
Elena
import extensions;   public program() { int randomNumber := randomGenerator.eval(1,10); console.printLine("I'm thinking of a number between 1 and 10. Can you guess it?"); bool numberCorrect := false; until(numberCorrect) { console.print("Guess: "); int userGuess := console.readLine(...
Give a code snippet in #Elena Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hi...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#Dyalect
Dyalect
print("There are twelve tokens.") print("You can take 1, 2, or 3 on your turn.") print("Whoever takes the last token wins.\n")   var tokens = 12 while tokens > 0 { print("There are \(tokens) remaining.") print("How many do you take?") var playertake = Integer(readLine())   if playertake < 1 || playerta...
Give a code snippet in #Dyalect Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player take...
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
#min
min
boolTrue = true boolFalse = false   if boolTrue then print "boolTrue is true, and its value is: " + boolTrue   if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse   mostlyTrue = 0.8 kindaTrue = 0.4 print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue) print "mostlyTrue OR kinda...
Give a code snippet in #min 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/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...
#PicoLisp
PicoLisp
(de gcd (A B) (until (=0 B) (let M (% A B) (setq A B B M) ) ) (abs A) )
Give a code snippet in #PicoLisp 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   great...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#Java
Java
package org.rosettacode;   import java.util.Collections; import java.util.Arrays;   /* * recursive backtracking algorithm * shamelessly borrowed from the ruby at * http://weblog.jamisbuck.org/2010/12/27/maze-generation-recursive-backtracking */ public class MazeGenerator { private final int x; private final int y...
Give a code snippet in #Java This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Verilog
Verilog
  module main; initial begin $display("Hello world!"); $finish ; end endmodule  
Give a code snippet in #Verilog Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error...
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#DWScript
DWScript
function Encode(v : Integer) : Integer; begin Result := v xor (v shr 1); end;   function Decode(v : Integer) : Integer; begin Result := 0; while v>0 do begin Result := Result xor v; v := v shr 1; end; end;   PrintLn('decimal binary gray decoded');   var i : Integer; for i:=0 to 31 do begin ...
Give a code snippet in #DWScript Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are ma...
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 ...
#Befunge
Befunge
& 211p > : 1 - #v_ 25*, @ > 11g:. / v > : 11g %!| > 11g 1+ 11p v ^ <
Give a code snippet in #Befunge 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Processing
Processing
// define a rudimentary class class HelloWorld { public static void sayHello() { println("Hello, world!"); } public void sayGoodbye() { println("Goodbye, cruel world!"); } }   // call the class method HelloWorld.sayHello();   // create an instance of the class HelloWorld hello = ...
Give a code snippet in #Processing In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a stati...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Peloton
Peloton
<@ ENU$$$LSTPSTLITLIT>UPP| [<@ SAYELTLST>...</@>] <@ SAYHLPELTLST>...</@><@ DEFKEYELTLST>__SuperMacro|...</@> <@ SAY&&&LIT>alphaBETA</@>   </@>
Give a code snippet in #Peloton Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not...
christopher/rosetta-code
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Wren
Wren
class TinyInt { construct new(n) { if (!(n is Num && n.isInteger && n >= 1 && n <= 10)) { Fiber.abort("Argument must be an integer between 1 and 10.") } _n = n }   n { _n }   +(other) { TinyInt.new(_n + other.n) } -(other) { TinyInt.new(_n - other.n) } *(other...
Give a code snippet in #Wren Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/Diversity_prediction_theorem
Diversity prediction theorem
The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that assumes independence of the i...
#Groovy
Groovy
class DiversityPredictionTheorem { private static double square(double d) { return d * d }   private static double averageSquareDiff(double d, double[] predictions) { return Arrays.stream(predictions) .map({ it -> square(it - d) }) .average() ....
Give a code snippet in #Groovy The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation th...
christopher/rosetta-code
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the la...
#Rust
Rust
// The compiler can automatically implement Clone on structs (assuming all members have implemented Clone). #[derive(Clone)] struct Tree<T> { left: Leaf<T>, data: T, right: Leaf<T>, }   type Leaf<T> = Option<Box<Tree<T>>>;   impl<T> Tree<T> { fn root(data: T) -> Self { Self { left: None, data, r...
Give a code snippet in #Rust Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this fac...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#VBScript
VBScript
  filepath = "SPECIFY PATH TO TEXT FILE HERE"   Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(filepath,1,False,0)   Do Until objInFile.AtEndOfStream line = objInFile.ReadLine WScript.StdOut.WriteLine line Loop   objInFile.Close Set objFSO = Nothing  
Give a code snippet in #VBScript Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#zkl
zkl
fcn muncher{ bitmap:=PPM(256,256); coolness:=(1).random(0x10000); // 55379, 18180, 40, 51950, 57619, 43514, 65465 foreach y,x in ([0 .. 255],[0 .. 255]){ b:=x.bitXor(y); // shades of blue // rgb:=b*coolness; // kaleidoscopic image // rgb:=(b*coolness + b)*coolness + b; // more...
Give a code snippet in #zkl Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#VBScript
VBScript
  Function largestint(list) nums = Split(list,",") Do Until IsSorted = True IsSorted = True For i = 0 To UBound(nums) If i <> UBound(nums) Then a = nums(i) b = nums(i+1) If CLng(a&b) < CLng(b&a) Then tmpnum = nums(i) nums(i) = nums(i+1) nums(i+1) = tmpnum IsSorted = False En...
Give a code snippet in #VBScript Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1...
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: * * * * * * * * * * * * * * * ...
#uBasic.2F4tH
uBasic/4tH
Input "Triangle order: ";n n = 2^n   For y = n - 1 To 0 Step -1   For i = 0 To y Print " "; Next   x = 0   For x = 0 Step 1 While ((x + y) < n) If AND (x,y) Then Print " "; Else Print "* "; EndIf Next   Print Next End
Give a code snippet in #uBasic.2F4tH 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/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#Erlang
Erlang
  -module( strip_control_codes ).   -export( [is_not_control_code/1, is_not_control_code_nor_extended_character/1, task/0] ).   is_not_control_code( C ) when C > 127 -> true; is_not_control_code( C ) when C < 32; C =:= 127 -> false; is_not_control_code( _C ) -> true.   is_not_control_code_nor_extended_character( C ) wh...
Give a code snippet in #Erlang Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters strippe...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#FreeBASIC
FreeBASIC
''This works on Windows. Does anyone know how it would be done in Linux?   Sub speak(texto As String) Dim As String frase frase ="mshta vbscript:Execute(""CreateObject(""""SAPI.SpVoice"""").Speak("""""+texto+""""")(window.close)"")" Print texto Shell frase End Sub   speak "Vamos a contar " + str(123456...
Give a code snippet in #FreeBASIC Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
"<=: " <> ToString[#1] <> " " <> ToString[100. #1/#2] <> "%\n >: " <> ToString[#2 - #1] <> " " <> ToString[100. (1 - #1/#2)] <> "%" &[ Count[Total /@ Subsets[Join[#1, #2], {Length@#1}], n_ /; n <= Total@#1], Binomial[Length@#1 + Length@#2, Length@#1]] &[{85, 88, 75, 66, 25, 29, 83, 39, 97}, {68, 41...
Give a code snippet in #Mathematica.2FWolfram_Language Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned ei...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Smalltalk
Smalltalk
|c| "Create an ordered collection that will grow while we add elements" c := OrderedCollection new. "fill the collection with 9 arrays of 10 elements; elements (objects) are initialized to the nil object, which is a well-defined 'state'" 1 to: 9 do: [ :i | c add: (Array new: 10) ]. "However, let us show a way of filli...
Give a code snippet in #Smalltalk Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are cons...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Haskell
Haskell
class Animal a class Animal a => Cat a class Animal a => Dog a class Dog a => Lab a class Dog a => Collie a
Give a code snippet in #Haskell This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent typ...
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#8086_Assembly
8086 Assembly
JCXZ bar foo: LOOP foo ;subtract 1 from CX, and if CX is still nonzero jump back to foo bar:
Give a code snippet in #8086_Assembly Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the f...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor
Terminal control/Hiding the cursor
The task is to hide the cursor and show it again.
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { print("\u001B[?25l") // hide cursor Thread.sleep(2000) // wait 2 seconds before redisplaying cursor print("\u001B[?25h") // display cursor Thread.sleep(2000) // wait 2 more seconds before exiting }
Give a code snippet in #Kotlin The task is to hide the cursor and show it again.
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Scala
Scala
  package xyz.hyperreal.rosettacodeCompiler   import java.io.{BufferedReader, FileReader, Reader, StringReader}   import scala.collection.mutable import scala.collection.mutable.ArrayBuffer   object VirtualMachine {   private object Opcodes { val FETCH: Byte = 0 val STORE: Byte = 1 val PUSH: Byte = 2 ...
Give a code snippet in #Scala A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read inp...
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_sequence
Padovan sequence
The Padovan sequence is similar to the Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. Comment Padovan Fibonacci Named after. Richard Padovan Leonardo of Pisa: Fibonacci Recurrence initial values....
#jq
jq
# Output: first $n Padovans def padovanRecur($n): [range(0;$n) | 1] as $p | if $n < 3 then $p else reduce range(3;$n) as $i ($p; .[$i] = .[$i-2] + .[$i-3]) end;   # Output: first $n Padovans def padovanFloor($n): { p: 1.324717957244746025960908854, s: 1.0453567932525329623, pow: 1 } | reduce ran...
Give a code snippet in #jq The Padovan sequence is similar to the Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. Comment Padovan Fibonacci Named after. Richard Padovan Leonardo of Pisa: Fibonacci ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#SQL_PL
SQL PL
  CREATE TABLE TEST ( VAL1 INT, VAL2 INT ); INSERT INTO TEST (VAL1, VAL2) VALUES (1, 2), (2, 2), (2, 1); SELECT CASE WHEN VAL1 < VAL2 THEN VAL1 || ' less than ' || VAL2 WHEN VAL1 = VAL2 THEN VAL1 || ' equal to ' || VAL2 WHEN VAL1 > VAL2 THEN VAL1 || ' greater than ' || VAL2 END COMPARISON F...
Give a code snippet in #SQL_PL 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/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...
#Groovy
Groovy
def gcdR gcdR = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcdR(n, m%n) }
Give a code snippet in #Groovy 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   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Go
Go
package main   import ( "encoding/csv" "log" "os" "strconv" )   func main() { rows := readSample() appendSum(rows) writeChanges(rows) }   func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log...
Give a code snippet in #Go CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change ...
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...
#J
J
HELP=: 0 :0 Commands:   DBNAME add DATA DBNAME display the latest entry DBNAME display the latest entry where CATEGORY contains WORD DBNAME display all entries DBNAME display all entries order by CATEGORY   1) The first add with new DBNAME assign category names. 2) lower case arguments verbatim. 3) UPPER CASE: substitu...
Give a code snippet in #J 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 c...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#Elena
Elena
import extensions; import system'routines; import system'math;   extension op { get RootMeanSquare() = (self.selectBy:(x => x * x).summarize(Real.new()) / self.Length).sqrt(); }   public program() { console.printLine(new Range(1, 10).RootMeanSquare) }
Give a code snippet in #Elena Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 ...
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...
#Elixir
Elixir
defmodule ABC do def can_make_word(word, avail) do can_make_word(String.upcase(word) |> to_charlist, avail, []) end   defp can_make_word([], _, _), do: true defp can_make_word(_, [], _), do: false defp can_make_word([l|tail], [b|rest], tried) do (l in b and can_make_word(tail, rest++tried, [])) o...
Give a code snippet in #Elixir 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/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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <libgen.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h>   int main (int argc, char **argv) { char *str, *s; struct stat statBuf;   if (argc != 2) { fprintf (stderr, "usage: %s <path>\n", basename (argv[0])); exit (1); } ...
Give a code snippet in #C 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Maple
Maple
A := <<1|2|3>,<4|5|6>>;   B := <<1,2,3>|<4,5,6>|<7,8,9>|<10,11,12>>;   A . B;
Give a code snippet in #Maple Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#PicoLisp
PicoLisp
(stamp)
Give a code snippet in #PicoLisp Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/War_card_game
War card game
War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell Poker hand_analyser Go Fish...
#Raku
Raku
unit sub MAIN (:$war where 2..4 = 4, :$sleep = .1);   my %c = ( # convenience hash of ANSI colors red => "\e[38;2;255;10;0m", blue => "\e[38;2;05;10;200m", black => "\e[38;2;0;0;0m" );   my @cards = flat (flat <🂢 🂣 🂤 🂥 🂦 🂧 🂨 🂩 🂪 🂫 🂭 🂮 🂡 🃒 🃓 🃔 🃕 🃖 🃗 🃘 🃙 🃚 🃛 🃝 🃞 🃑>.map(...
Give a code snippet in #Raku War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Pascal
Pascal
program DigitalRoot;   {$mode objfpc}{$H+}   uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} SysUtils, StrUtils;   // FPC has no Big mumbers implementation, Int64 will suffice.   procedure GetDigitalRoot(Value: Int64; Base: Byte; var DRoot, Pers: Integer); var i: Integer; DigitSum: Int64; ...
Give a code snippet in #Pascal The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} ,...
christopher/rosetta-code
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: expandBraces (in string: stri) is func local var boolean: escaped is FALSE; var integer: depth is 0; var array integer: bracePoints is 0 times 0; var array integer: bracesToParse is 0 times 0; var string: prefix is ""; var string: suffix is ""; var s...
Give a code snippet in #Seed7 Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Smalltalk
Smalltalk
PackageLoader fileInPackage: 'Complex'. |a b| a := 1 + 1 i. b := 3.14159 + 1.2 i. (a + b) displayNl. (a * b) displayNl. (a / b) displayNl. a reciprocal displayNl. a conjugate displayNl. a abs displayNl. a real displayNl. a imaginary displayNl. a negated displayNl.
Give a code snippet in #Smalltalk A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#REXX
REXX
/*REXX program generates & displays primitive Heronian triangles by side length and area*/ parse arg N first area . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 200 /*Not specified? Then use the default.*/ if first=='' | first=="," then first= 10 ...
Give a code snippet in #REXX Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b...
christopher/rosetta-code
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#Wren
Wren
import "/fmt" for Fmt   var newSum // recursive newSum = Fn.new { var ms // also recursive ms = Fn.new { ms = newSum.call() return ms.call() } var msd = 0 var d = 0 return Fn.new { if (d < 9) { d = d + 1 } else { d = 0 msd = ms....
Give a code snippet in #Wren Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. T...
christopher/rosetta-code
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL 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) In computer science, an AVL tree is a self-balancing binary search tree....
#Julia
Julia
module AVLTrees   import Base.print export AVLNode, AVLTree, insert, deletekey, deletevalue, findnodebykey, findnodebyvalue, allnodes   @enum Direction LEFT RIGHT avlhash(x) = Int32(hash(x) & 0xfffffff) const MIDHASH = Int32(div(0xfffffff, 2))   mutable struct AVLNode{T} value::T key::Int32 balance::Int32 ...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at AVL 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) In computer science, an AVL tree is a sel...
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 ...
#PowerShell
PowerShell
  function isPrime ($n) { if ($n -eq 1) {$false} elseif ($n -eq 2) {$true} elseif ($n -eq 3) {$true} else{ $m = [Math]::Floor([Math]::Sqrt($n)) (@(2..$m | where {($_ -lt $n) -and ($n % $_ -eq 0) }).Count -eq 0) } } 1..15 | foreach{"isPrime $_ : $(isPrime $_)"}
Give a code snippet in #PowerShell 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function IsHumble(i As Long) As Boolean If i <= 1 Then Return True End If If i Mod 2 = 0 Then Return IsHumble(i \ 2) End If If i Mod 3 = 0 Then Return IsHumble(i \ 3) End If If i Mod 5 = 0 Then R...
Give a code snippet in #Visual_Basic_.NET Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to expre...
christopher/rosetta-code
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to ...
#Wren
Wren
import "/rat" for Rat import "/fmt" for Fmt, Conv   var calkinWilf = Fn.new { |n| var cw = List.filled(n, null) cw[0] = Rat.one for (i in 1...n) { var t = cw[i-1].floor * 2 - cw[i-1] + 1 cw[i] = Rat.one / t } return cw }   var toContinued = Fn.new { |r| var a = r.num var b = ...
Give a code snippet in #Wren The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating...
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...
#SQL_PL
SQL PL
  --#SET TERMINATOR @   SET SERVEROUTPUT ON @   CREATE OR REPLACE FUNCTION LUHN_TEST ( IN NUMBER VARCHAR(24) ) RETURNS SMALLINT --) RETURNS BOOLEAN BEGIN DECLARE TYPE CARD_NUMBER AS VARCHAR(1) ARRAY [24]; DECLARE LENGTH SMALLINT; DECLARE REVERSE CARD_NUMBER; DECLARE I SMALLINT; DECLARE POS SMALLINT; DE...
Give a code snippet in #SQL_PL 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#F.23
F#
  // Generate bell triangle. Nigel Galloway: July 6th., 2019 let bell=Seq.unfold(fun g->Some(g,List.scan(+) (List.last g) g))[1I]  
Give a code snippet in #F.23 Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <map> #include <sstream>   bool isHumble(int i) { if (i <= 1) return true; if (i % 2 == 0) return isHumble(i / 2); if (i % 3 == 0) return isHumble(i / 3); if (i % 5 == 0) return isHumble(i / 5); if (i % 7 == 0) return isHumble(i / 7); return false;...
Give a code snippet in #C.2B.2B Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the abo...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#8080_Assembly
8080 Assembly
; This is Hello World, written in 8080 assembly to run under CP/M ; As you can see, it is similar to the 8086, and CP/M is very ; similar to DOS in the way it is called. org 100h ; CP/M .COM entry point is 100h - like DOS mvi c,9 ; C holds the syscall, 9 = print string - like DOS lxi d,msg ; DE holds a pointer to...
Give a code snippet in #8080_Assembly Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#SAS
SAS
  /* Generate 1000 random numbers with mean 1 and standard deviation 0.5. SAS version 9.2 was used to create this code.*/   data norm1000; call streaminit(123456); /* Set the starting point, so we can replicate results. If you want different results each time, comment the above line. */ do i=1 to 1000; ...
Give a code snippet in #SAS Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related t...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#360_Assembly
360 Assembly
* CALENDAR FOR REAL PROGRAMMERS 05/03/2017 CALENDAR CSECT USING CALENDAR,R13 BASE REGISTER B 72(R15) SKIP MY SAVEAREA DC 17F'0' MY SAVEAREA STM R14,R12,12(R13) SAVE CALLER'S REGISTERS ST R13,4(R15) LINK BACK...
Give a code snippet in #360_Assembly Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert...
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...
#AutoHotkey
AutoHotkey
Loop { ; TEST LOOP n = Random Digits, 1, 36 ; random number with up to 36 digits Loop %Digits% { Random Digit, 0, 9 ; can have leading 0s n .= Digit } MsgBox 1, Number Names, % PrettyNumber(n) "`n`n" Spell(n) "`n`n" ...
Give a code snippet in #AutoHotkey Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than...
christopher/rosetta-code
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' uses same alphabet and key as Ada language example Const string1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Const string2 = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"   Sub process(inputFile As String, outputFile As String, encrypt As Boolean) Open inputFile For Input ...
Give a code snippet in #FreeBASIC Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and the...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Crystal
Crystal
require "random"   first = gets.not_nil!.to_i32 second = gets.not_nil!.to_i32   arr = Array(Array(Int32)).new(first, Array(Int32).new second, 0)   random = Random.new   first = random.rand 0..(first - 1) second = random.rand 0..(second - 1)   arr[first][second] = random.next_int puts arr[first][second]
Give a code snippet in #Crystal Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Racket
Racket
#lang racket   (define (string-reverse s) (list->string (reverse (string->list s))))   (string-reverse "aoeu")
Give a code snippet in #Racket Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the widt...
#Go
Go
package main   import ( "fmt" "math" )   // type requested by task type interval struct { lower, upper float64 }   // a constructor func stepAway(x float64) interval { return interval { math.Nextafter(x, math.Inf(-1)), math.Nextafter(x, math.Inf(1))} }   // function requested by task fun...
Give a code snippet in #Go Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#SenseTalk
SenseTalk
set inputs to [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0]   repeat with each num in inputs put num into output put middle3digits of num into character 15 of output -- will autofill with "."s put output end repeat   to handle middle3digits of number put e...
Give a code snippet in #SenseTalk Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should b...
christopher/rosetta-code
http://rosettacode.org/wiki/Equal_prime_and_composite_sums
Equal prime and composite sums
Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes. P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ... P = 2, 5, 10, 17, 28, etc. Further; suppose we have a sequence of composite sums, where each term Cm is the sum of the first m composites. C = (4...
#Raku
Raku
use Lingua::EN::Numbers:ver<2.8.2+>;   my $prime-sum = [\+] (2..*).grep: *.is-prime; my $composite-sum = [\+] (2..*).grep: !*.is-prime;   my $c-index = 0;   for ^∞ -> $p-index { next if $prime-sum[$p-index] < $composite-sum[$c-index]; printf( "%20s - %11s prime sum, %12s composite sum  %5.2f seconds\n", ...
Give a code snippet in #Raku Suppose we have a sequence of prime sums, where each term Pn is the sum of the first n primes. P = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ... P = 2, 5, 10, 17, 28, etc. Further; suppose we have a sequence of composite sums, where each term Cm is the sum of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#Racket
Racket
#lang racket   (define (all-words f (case-fold string-downcase)) (map case-fold (regexp-match* #px"\\w+" (file->string f))))   (define (l.|l| l) (cons (car l) (length l)))   (define (counts l (>? >)) (sort (map l.|l| (group-by values l)) >? #:key cdr))   (module+ main (take (counts (all-words "data/les-mis.txt")) 1...
Give a code snippet in #Racket Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define w...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Python
Python
#!/usr/bin/env python #four gray scaled stripes 8:16:32:64 in Python 2.7.1   from livewires import *   horiz=640; vert=480; pruh=vert/4; dpp=255.0 begin_graphics(width=horiz,height=vert,title="Gray stripes",background=Colour.black)   def ty_pruhy(each): hiy=each[0]*pruh; loy=hiy-pruh krok=horiz/each[1]; piecol=255.0/...
Give a code snippet in #Python The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we ...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#Common_Lisp
Common Lisp
  (defun factorial (n) (if (< n 2) 1 (* n (factorial (1- n)))) )     (defun primep (n) "Primality test using Wilson's Theorem" (unless (zerop n) (zerop (mod (1+ (factorial (1- n))) n)) ))  
Give a code snippet in #Common_Lisp Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theo...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#NewLISP
NewLISP
; file: arraycon.lsp ; url: http://rosettacode.org/wiki/Array_concatenation ; author: oofoe 2012-01-28   (println "Append lists: " (append '(3 a 5 3) (sequence 1 9)))   (println "Multi append: " (append '(this is) '(a test) '(of the emergency) (sequenc...
Give a code snippet in #NewLISP Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#F.23
F#
  let numbers = [| 1..10 |] let sum = numbers |> Array.sum let product = numbers |> Array.reduce (*)  
Give a code snippet in #F.23 Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "draw.s7i"; include "keybd.s7i";   const proc: main is func local var integer: barHeight is 0; var integer: barNumber is 0; var integer: colCount is 0; var integer: deltaX is 0; var integer: x is 0; var integer: col is 0; begin screen(640, 480); ...
Give a code snippet in #Seed7 The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we h...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#PowerShell
PowerShell
  function agm ([Double]$a, [Double]$g) { [Double]$eps = 1E-15 [Double]$a1 = [Double]$g1 = 0 while([Math]::Abs($a - $g) -gt $eps) { $a1, $g1 = $a, $g $a = ($a1 + $g1)/2 $g = [Math]::Sqrt($a1*$g1) } [pscustomobject]@{ a = "$a" g = "$g" } } agm 1 (1/[Math]::...
Give a code snippet in #PowerShell This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a funct...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#Lua
Lua
_G[io.read()] = 5 --puts 5 in a global variable named by the user
Give a code snippet in #Lua Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Forth
Forth
: prime? ( n -- ? ) here + c@ 0= ; : notprime! ( n -- ) here + 1 swap c! ;   : prime_sieve ( n -- ) here over erase 0 notprime! 1 notprime! 2 begin 2dup dup * > while dup prime? if 2dup dup * do i notprime! dup +loop then 1+ repeat 2drop ;   : digit_sum ( u -- u ) d...
Give a code snippet in #Forth Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#JavaScript
JavaScript
function tokenize(s, esc, sep) { for (var a=[], t='', i=0, e=s.length; i<e; i+=1) { var c = s.charAt(i) if (c == esc) t+=s.charAt(++i) else if (c != sep) t+=c else a.push(t), t='' } a.push(t) return a }   var s = 'one^|uno||three^^^^|four^^^|^cuatro|' document.write(s, '<br>') for (var a=tokenize(s,'^','...
Give a code snippet in #JavaScript Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#Red
Red
Red [ date: 2021-10-24 version: 0.6.4 summary: "Demonstrate the game of Nim in Red for Rosetta Code" ]   take-tokens: function [ "Ask the user to take between 1 and 3 tokens." ][ forever [ n: trim ask "Would you like to take 1, 2, or 3 tokens (q to quit)? " if n = "q" [quit] ...
Give a code snippet in #Red Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#XPL0
XPL0
  \Department numbers code CrLf=9, IntIn=10, IntOut=11, Text=12; integer P, S, F;   begin Text(0, "POLICE SANITATION FIRE"); CrLf(0); P:= 2; while P <= 7 do begin for S:= 1, 7 do if S # P then begin F:= (12 - P) - S; if (F > 0) & (F <= 7) & (F # S) & (F # P) then begin Text(0, ...
Give a code snippet in #XPL0 There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (dif...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#Kotlin
Kotlin
// version 1.0.6   import java.text.SimpleDateFormat import java.util.*   fun main(args: Array<String>) { val dts = "March 7 2009 7:30pm EST" val sdf = SimpleDateFormat("MMMM d yyyy h:mma z") val dt = sdf.parse(dts) val cal = GregorianCalendar(TimeZone.getTimeZone("EST")) // stay with EST cal....
Give a code snippet in #Kotlin Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Delphi
Delphi
  procedure Check(Condition1: Boolean; Condition2: Boolean) begin if Condition1 = True then begin if Condition2 = True then BothConditionsAreTrue else FirstConditionIsTrue; end else if Condition2 = True then SecondConditionIsTrue else NoConditionIsTrue; end;
Give a code snippet in #Delphi Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Java
Java
//All of these objects will be deallocated automatically once the program leaves //their scope and there are no more pointers to the objects Object foo = new Object(); //Allocate an Object and a reference to it int[] fooArray = new int[size]; //Allocate all spaces in an array and a reference to it int x = 0; //Allocate...
Give a code snippet in #Java Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Liberty_BASIC
Liberty BASIC
global pi pi = 3.14159265 input "Enter latitude (degrees)  : "; latitude ' -4.95 input "Enter longitude (degrees)  : "; longitude ' -150.5 input "Enter legal meridian (degrees): "; meridian ' -150.0 print print "Time Sun hour angle Dial hour line angle" for hour = 6 TO 18 hra = ...
Give a code snippet in #Liberty_BASIC 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 Lincol...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Haskell
Haskell
import Control.Concurrent (setNumCapabilities) import Control.Monad.Par (runPar, get, spawnP) import Control.Monad (join, (>=>)) import Data.List.Split (chunksOf) import Data.List (intercalate, mapAccumL, genericTake, genericDrop) import Data.Bifunctor (bimap) i...
Give a code snippet in #Haskell Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   ...
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.
#Ring
Ring
  fp = fopen("C:\Ring\ReadMe.txt","r") r = "" while isstring(r) r = fgetc(fp) if r = char(10) see nl else see r ok end fclose(fp)  
Give a code snippet in #Ring 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/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
#AppleScript
AppleScript
------------------------ THUE MORSE ----------------------   -- thueMorse :: Int -> String on thueMorse(nCycles) script concatBinaryInverse on |λ|(xs) script binaryInverse on |λ|(x) 1 - x end |λ| end script   xs & map(bi...
Give a code snippet in #AppleScript 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/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#UNIX_Shell
UNIX Shell
get_nth_line() { local file=$1 n=$2 line while ((n-- > 0)); do if ! IFS= read -r line; then echo "No such line $2 in $file" return 1 fi done < "$file" echo "$line" }   get_nth_line filename 7
Give a code snippet in #UNIX_Shell Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store...
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...
#zkl
zkl
fcn toGrayScale(img){ // in-place conversion foreach x,y in (img.w,img.h){ r,g,b:=img[x,y].toBigEndian(3); lum:=(0.2126*r + 0.7152*g + 0.0722*b).toInt(); img[x,y]=((lum*256) + lum)*256 + lum; } }
Give a code snippet in #zkl 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/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#JavaScript
JavaScript
export function encode (number) { return number ^ (number >> 1) }   export function decode (encodedNumber) { let number = encodedNumber   while (encodedNumber >>= 1) { number ^= encodedNumber }   return number }
Give a code snippet in #JavaScript Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#M2000_Interpreter
M2000 Interpreter
  Module Dining_philosophers (whichplan) { Form 80, 32 Const MayChangePick=Random(True, False) dim energy(1 to 5)=50 Document Doc$ const nl$={ } Print $(,12), ' set column width to 12 Pen 14 Pen 15 { Doc$="Dining Philosophers"+nl$ \\ we can change thread plan only if no threads defined if whichplan=1 th...
Give a code snippet in #M2000_Interpreter The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time think...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Racket
Racket
#lang racket   (require data/queue)   (define (simple-moving-average period) (define queue (make-queue)) (define sum 0.0)   (lambda (x) (enqueue! queue x) (set! sum (+ sum x)) (when (> (queue-length queue) period) (set! sum (- sum (dequeue! queue)))) (/ sum (queue-length queue))))   ;; Tests...
Give a code snippet in #Racket Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#SAS
SAS
/* create SAS data set */ data mydata; input item $1-23 weight value pieces; datalines; map 9 150 1 compass 13 35 1 water 153 200 2 sandwich 50 60 2 glucose 15 60 2 tin 68 45 3 bana...
Give a code snippet in #SAS A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weigh...
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...
#Swift
Swift
  var lead = 0 for r in 0..<rows { if (cols <= lead) { break } var i = r while (m[i][lead] == 0) { i += 1 if (i == rows) { i = r lead += 1 if (cols == lead) { ...
Give a code snippet in #Swift 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 convenien...
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...
#AWK
AWK
BEGIN { mystring="knights" print substr(mystring,2) # remove the first letter print substr(mystring,1,length(mystring)-1) # remove the last character print substr(mystring,2,length(mystring)-2) # remove both the first and last character }
Give a code snippet in #AWK 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on thi...
#ALGOL_68
ALGOL 68
BEGIN # find Wilson primes of order n, primes such that: # # ( ( n - 1 )! x ( p - n )! - (-1)^n ) mod p^2 = 0 # INT limit = 5 508; # max prime to consider #   # Build list of primes. # []INT primes = BEGIN # sieve the primes to limit^2 which wi...
Give a code snippet in #ALGOL_68 Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563....
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...
#SETL
SETL
a := 33; b := 77; print(" the gcd of",a," and ",b," is ",gcd(a,b));   c := 49865; d := 69811; print(" the gcd of",c," and ",d," is ",gcd(c,d));   proc gcd (u, v); return if v = 0 then abs u else gcd (v, u mod v) end; end;
Give a code snippet in #SETL 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#TXR
TXR
(defun f (n) (if (>= 0 n) 1 (- n (m (f (- n 1))))))   (defun m (n) (if (>= 0 n) 0 (- n (f (m (- n 1))))))   (each ((n (range 0 15))) (format t "f(~s) = ~s; m(~s) = ~s\n" n (f n) n (m n)))
Give a code snippet in #TXR Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#Julia
Julia
using Gtk, Graphics, Colors   function drawline(ctx, p1, p2, color, width) move_to(ctx, p1.x, p1.y) set_source(ctx, color) line_to(ctx, p2.x, p2.y) set_line_width(ctx, width) stroke(ctx) end   const can = @GtkCanvas() const win = GtkWindow(can, "Colour pinstripe/Display", 400, 400) const colors = [c...
Give a code snippet in #Julia The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   mag...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Dc
Dc
0 0^p  
Give a code snippet in #Dc Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or    ...
christopher/rosetta-code